# mulesoft Mule Runtime - Full Documentation --- product: Mule Runtime version: 4.11 --- # About Transformers (Deprecated) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Transformers, such as Object to XML and Object to String, are deprecated data transformation components that are distinct from the Transform component. In this release, you should use DataWeave expressions in the Transform component to perform data transformations instead of relying the deprecated components. Note that transformers are only available through the Compatibility module (available starting in Mule version 4.1). ## See Also [About the Transform Component](https://docs.mulesoft.com/mule-runtime/4.11/transform-component-about) --- product: Mule Runtime version: 4.12 --- # About Transformers (Deprecated) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Transformers, such as Object to XML and Object to String, are deprecated data transformation components that are distinct from the Transform component. In this release, you should use DataWeave expressions in the Transform component to perform data transformations instead of relying the deprecated components. Note that transformers are only available through the Compatibility module (available starting in Mule version 4.1). ## See Also [About the Transform Component](https://docs.mulesoft.com/mule-runtime/4.12/transform-component-about) --- product: Mule Runtime version: 4.3 --- # About Transformers (Deprecated) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Transformers, such as Object to XML and Object to String, are deprecated data transformation components that are distinct from the Transform component. In this release, you should use DataWeave expressions in the Transform component to perform data transformations instead of relying the deprecated components. Note that transformers are only available through the Compatibility module (available starting in Mule version 4.1). ## See Also [About the Transform Component](https://docs.mulesoft.com/mule-runtime/4.3/transform-component-about) --- product: Mule Runtime version: 4.4 --- # About Transformers (Deprecated) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Transformers, such as Object to XML and Object to String, are deprecated data transformation components that are distinct from the Transform component. In this release, you should use DataWeave expressions in the Transform component to perform data transformations instead of relying the deprecated components. Note that transformers are only available through the Compatibility module (available starting in Mule version 4.1). ## See Also [About the Transform Component](https://docs.mulesoft.com/mule-runtime/4.4/transform-component-about) --- product: Mule Runtime version: 4.6 --- # About Transformers (Deprecated) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Transformers, such as Object to XML and Object to String, are deprecated data transformation components that are distinct from the Transform component. In this release, you should use DataWeave expressions in the Transform component to perform data transformations instead of relying the deprecated components. Note that transformers are only available through the Compatibility module (available starting in Mule version 4.1). ## See Also [About the Transform Component](https://docs.mulesoft.com/mule-runtime/4.6/transform-component-about) --- product: Mule Runtime version: 4.9 --- # About Transformers (Deprecated) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Transformers, such as Object to XML and Object to String, are deprecated data transformation components that are distinct from the Transform component. In this release, you should use DataWeave expressions in the Transform component to perform data transformations instead of relying the deprecated components. Note that transformers are only available through the Compatibility module (available starting in Mule version 4.1). ## See Also [About the Transform Component](https://docs.mulesoft.com/mule-runtime/4.9/transform-component-about) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # About Transformers (Deprecated) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Transformers, such as Object to XML and Object to String, are deprecated data transformation components that are distinct from the Transform component. In this release, you should use DataWeave expressions in the Transform component to perform data transformations instead of relying the deprecated components. Note that transformers are only available through the Compatibility module (available starting in Mule version 4.1). ## See Also [About the Transform Component](https://docs.mulesoft.com/mule-runtime/latest/transform-component-about) --- product: Mule Runtime version: 4.11 --- # Add Another Output to the Transform Message Component (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A single Transform Message component can give shape to several different parts of the output Mule event (the payload, variables, and attributes). Each different output part must be defined in a separate target XML element inside the `` XML element as another block of DataWeave code. In Anypoint Studio 7, you do this by writing the DataWeave code in a separate tab of the Transform pane. For example, if one tab defines the payload, and another attributes, these are both parts of the same output Mule event. To add a new output target: 1. Click **Add new target**. ![Add icon](/mulesoft/current/en-us/mule-runtime/4.11/_images/using-dataweave-in-studio-34a3e.png) 2. Specify where in the output Mule message to place the result of this new DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![A Selection dialog output with an option to choose a source code](/mulesoft/current/en-us/mule-runtime/4.11/_images/dw-new-variable.png) Note that the execution order of multiple outputs can vary. Ensure that each transformation is independent of the order of execution and the other outputs. ## How Targets of a Transform Message Component are Represented in the Configuration XML File The payload is represented in an `` element, as a child element of the `` element. ```xml ``` Attributes are represented together inside the `` element, as a child of the `` element. ```xml ... ``` Each variable is represented inside a separate `` element, as a child the `` parent element. The `` element is a direct child of the `` element, so it is not part of the `` element. This XML structure reflects that variables and the message are carried along together with the parent event object. Here is an example of a variable target defined inside a Transform Message component: ```xml ... ``` ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.11/transform-component-about) [Change the Target Output of a Transformation](https://docs.mulesoft.com/mule-runtime/4.11/transform-change-target-output-transformation-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.11/dataweave) --- product: Mule Runtime version: 4.12 --- # Add Another Output to the Transform Message Component (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A single Transform Message component can give shape to several different parts of the output Mule event (the payload, variables, and attributes). Each different output part must be defined in a separate target XML element inside the `` XML element as another block of DataWeave code. In Anypoint Studio 7, you do this by writing the DataWeave code in a separate tab of the Transform pane. For example, if one tab defines the payload, and another attributes, these are both parts of the same output Mule event. To add a new output target: 1. Click **Add new target**. ![Add icon](/mulesoft/current/en-us/mule-runtime/4.12/_images/using-dataweave-in-studio-34a3e.png) 2. Specify where in the output Mule message to place the result of this new DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![A Selection dialog output with an option to choose a source code](/mulesoft/current/en-us/mule-runtime/4.12/_images/dw-new-variable.png) Note that the execution order of multiple outputs can vary. Ensure that each transformation is independent of the order of execution and the other outputs. ## How Targets of a Transform Message Component are Represented in the Configuration XML File The payload is represented in an `` element, as a child element of the `` element. ```xml ``` Attributes are represented together inside the `` element, as a child of the `` element. ```xml ... ``` Each variable is represented inside a separate `` element, as a child the `` parent element. The `` element is a direct child of the `` element, so it is not part of the `` element. This XML structure reflects that variables and the message are carried along together with the parent event object. Here is an example of a variable target defined inside a Transform Message component: ```xml ... ``` ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.12/transform-component-about) [Change the Target Output of a Transformation](https://docs.mulesoft.com/mule-runtime/4.12/transform-change-target-output-transformation-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.12/dataweave) --- product: Mule Runtime version: 4.3 --- # Add Another Output to the Transform Message Component (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A single Transform Message component can give shape to several different parts of the output Mule event (the payload, variables, and attributes). Each different output part must be defined in a separate target XML element inside the `` XML element as another block of DataWeave code. In Anypoint Studio 7, you do this by writing the DataWeave code in a separate tab of the Transform pane. For example, if one tab defines the payload, and another attributes, these are both parts of the same output Mule event. To add a new output target: 1. Click **Add new target**. ![using dataweave in studio 34a3e](/mulesoft/current/en-us/mule-runtime/4.3/_images/using-dataweave-in-studio-34a3e.png) 2. Specify where in the output Mule message to place the result of this new DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![new variable](/mulesoft/current/en-us/mule-runtime/4.3/_images/dw-new-variable.png) Note that the execution order of multiple outputs can vary. Ensure that each transformation is independent of the order of execution and the other outputs. ## How Targets of a Transform Message Component are Represented in the Configuration XML File The payload is represented in an `` element, as a child element of the `` element. ```xml ``` Attributes are represented together inside the `` element, as a child of the `` element. ```xml ... ``` Each variable is represented inside a separate `` element, as a child the `` parent element. The `` element is a direct child of the `` element, so it is not part of the `` element. This XML structure reflects that variables and the message are carried along together with the parent event object. Here is an example of a variable target defined inside a Transform Message component: ```xml ... ``` ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.3/transform-component-about) [Change the Target Output of a Transformation](https://docs.mulesoft.com/mule-runtime/4.3/transform-change-target-output-transformation-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) --- product: Mule Runtime version: 4.4 --- # Add Another Output to the Transform Message Component (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A single Transform Message component can give shape to several different parts of the output Mule event (the payload, variables, and attributes). Each different output part must be defined in a separate target XML element inside the `` XML element as another block of DataWeave code. In Anypoint Studio 7, you do this by writing the DataWeave code in a separate tab of the Transform pane. For example, if one tab defines the payload, and another attributes, these are both parts of the same output Mule event. To add a new output target: 1. Click **Add new target**. ![using dataweave in studio 34a3e](/mulesoft/current/en-us/mule-runtime/4.4/_images/using-dataweave-in-studio-34a3e.png) 2. Specify where in the output Mule message to place the result of this new DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![new variable](/mulesoft/current/en-us/mule-runtime/4.4/_images/dw-new-variable.png) Note that the execution order of multiple outputs can vary. Ensure that each transformation is independent of the order of execution and the other outputs. ## How Targets of a Transform Message Component are Represented in the Configuration XML File The payload is represented in an `` element, as a child element of the `` element. ```xml ``` Attributes are represented together inside the `` element, as a child of the `` element. ```xml ... ``` Each variable is represented inside a separate `` element, as a child the `` parent element. The `` element is a direct child of the `` element, so it is not part of the `` element. This XML structure reflects that variables and the message are carried along together with the parent event object. Here is an example of a variable target defined inside a Transform Message component: ```xml ... ``` ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.4/transform-component-about) [Change the Target Output of a Transformation](https://docs.mulesoft.com/mule-runtime/4.4/transform-change-target-output-transformation-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) --- product: Mule Runtime version: 4.6 --- # Add Another Output to the Transform Message Component (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A single Transform Message component can give shape to several different parts of the output Mule event (the payload, variables, and attributes). Each different output part must be defined in a separate target XML element inside the `` XML element as another block of DataWeave code. In Anypoint Studio 7, you do this by writing the DataWeave code in a separate tab of the Transform pane. For example, if one tab defines the payload, and another attributes, these are both parts of the same output Mule event. To add a new output target: 1. Click **Add new target**. ![using dataweave in studio 34a3e](/mulesoft/current/en-us/mule-runtime/4.6/_images/using-dataweave-in-studio-34a3e.png) 2. Specify where in the output Mule message to place the result of this new DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![new variable](/mulesoft/current/en-us/mule-runtime/4.6/_images/dw-new-variable.png) Note that the execution order of multiple outputs can vary. Ensure that each transformation is independent of the order of execution and the other outputs. ## How Targets of a Transform Message Component are Represented in the Configuration XML File The payload is represented in an `` element, as a child element of the `` element. ```xml ``` Attributes are represented together inside the `` element, as a child of the `` element. ```xml ... ``` Each variable is represented inside a separate `` element, as a child the `` parent element. The `` element is a direct child of the `` element, so it is not part of the `` element. This XML structure reflects that variables and the message are carried along together with the parent event object. Here is an example of a variable target defined inside a Transform Message component: ```xml ... ``` ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.6/transform-component-about) [Change the Target Output of a Transformation](https://docs.mulesoft.com/mule-runtime/4.6/transform-change-target-output-transformation-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.6/dataweave) --- product: Mule Runtime version: 4.9 --- # Add Another Output to the Transform Message Component (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A single Transform Message component can give shape to several different parts of the output Mule event (the payload, variables, and attributes). Each different output part must be defined in a separate target XML element inside the `` XML element as another block of DataWeave code. In Anypoint Studio 7, you do this by writing the DataWeave code in a separate tab of the Transform pane. For example, if one tab defines the payload, and another attributes, these are both parts of the same output Mule event. To add a new output target: 1. Click **Add new target**. ![Add icon](/mulesoft/current/en-us/mule-runtime/4.9/_images/using-dataweave-in-studio-34a3e.png) 2. Specify where in the output Mule message to place the result of this new DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![A Selection dialog output with an option to choose a source code](/mulesoft/current/en-us/mule-runtime/4.9/_images/dw-new-variable.png) Note that the execution order of multiple outputs can vary. Ensure that each transformation is independent of the order of execution and the other outputs. ## How Targets of a Transform Message Component are Represented in the Configuration XML File The payload is represented in an `` element, as a child element of the `` element. ```xml ``` Attributes are represented together inside the `` element, as a child of the `` element. ```xml ... ``` Each variable is represented inside a separate `` element, as a child the `` parent element. The `` element is a direct child of the `` element, so it is not part of the `` element. This XML structure reflects that variables and the message are carried along together with the parent event object. Here is an example of a variable target defined inside a Transform Message component: ```xml ... ``` ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.9/transform-component-about) [Change the Target Output of a Transformation](https://docs.mulesoft.com/mule-runtime/4.9/transform-change-target-output-transformation-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.9/dataweave) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Add Another Output to the Transform Message Component (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A single Transform Message component can give shape to several different parts of the output Mule event (the payload, variables, and attributes). Each different output part must be defined in a separate target XML element inside the `` XML element as another block of DataWeave code. In Anypoint Studio 7, you do this by writing the DataWeave code in a separate tab of the Transform pane. For example, if one tab defines the payload, and another attributes, these are both parts of the same output Mule event. To add a new output target: 1. Click **Add new target**. ![Add icon](/mulesoft/current/en-us/mule-runtime/latest/_images/using-dataweave-in-studio-34a3e.png) 2. Specify where in the output Mule message to place the result of this new DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![A Selection dialog output with an option to choose a source code](/mulesoft/current/en-us/mule-runtime/latest/_images/dw-new-variable.png) Note that the execution order of multiple outputs can vary. Ensure that each transformation is independent of the order of execution and the other outputs. ## How Targets of a Transform Message Component are Represented in the Configuration XML File The payload is represented in an `` element, as a child element of the `` element. ```xml ``` Attributes are represented together inside the `` element, as a child of the `` element. ```xml ... ``` Each variable is represented inside a separate `` element, as a child the `` parent element. The `` element is a direct child of the `` element, so it is not part of the `` element. This XML structure reflects that variables and the message are carried along together with the parent event object. Here is an example of a variable target defined inside a Transform Message component: ```xml ... ``` ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/latest/transform-component-about) [Change the Target Output of a Transformation](https://docs.mulesoft.com/mule-runtime/latest/transform-change-target-output-transformation-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/latest/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/latest/dataweave) --- product: Mule Runtime version: 4.11 keywords: advanced, mule, concepts, runtime, engine --- # Advanced Mule Concepts > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you become familiar with the basics of Mule application development and Mule runtime engine (Mule) concepts, you can focus on more advanced features, such as the execution engine, the classloading isolation mechanism, and distributed file polling. Learn about the [execution engine](https://docs.mulesoft.com/mule-runtime/4.11/execution-engine) to understand how Mule runtime engine processes the operations in a Mule application flow, and to understand how to change the thread pools if needed. Mule runtime engine uses execution metadata provided by operations in a flow to perform autotuning. The [classloading isolation](https://docs.mulesoft.com/mule-runtime/4.11/about-classloading-isolation) mechanism implemented in Mule 4 is designed to make upgrades easier by preventing components from exposing their internal resources. All components interact with each other through their defined APIs so that only exposed resources can be accessed by other components. Classloading isolation ensures that a component’s internal content is protected and can be changed any time, without affecting other components. Mule 4 supports [distributed file polling](https://docs.mulesoft.com/mule-runtime/4.11/distributed-file-polling), which allows connectors to read files from certain directories as they are created. Distributed file polling also makes it possible to poll files in all cluster nodes. Mule 4 also supports [distributed locking](https://docs.mulesoft.com/mule-runtime/4.11/distributed-locking), which provides the ability to create locks for synchronizing access to resources within Mule components. Learn more about [Mule data types](https://docs.mulesoft.com/mule-runtime/4.11/mule-data-types) to understand how Mule centralizes data access across different components, and also how DataWeave uses this information to determine which reader and writer to use. You can refer to the [Javadocs](https://docs.mulesoft.com/mule-runtime/4.11/mule-4-api-javadoc) for Mule Kernel (the community edition of Mule runtime engine) to learn definitions for classes, fields, and data types. You can see a list of [third-party software](https://docs.mulesoft.com/mule-runtime/4.11/third-party-software-in-mule) that is included as part of Mule runtime engine as internal dependencies. --- product: Mule Runtime version: 4.12 keywords: advanced, mule, concepts, runtime, engine --- # Advanced Mule Concepts > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you become familiar with the basics of Mule application development and Mule runtime engine (Mule) concepts, you can focus on more advanced features, such as the execution engine, the classloading isolation mechanism, and distributed file polling. Learn about the [execution engine](https://docs.mulesoft.com/mule-runtime/4.12/execution-engine) to understand how Mule runtime engine processes the operations in a Mule application flow, and to understand how to change the thread pools if needed. Mule runtime engine uses execution metadata provided by operations in a flow to perform autotuning. The [classloading isolation](https://docs.mulesoft.com/mule-runtime/4.12/about-classloading-isolation) mechanism implemented in Mule 4 is designed to make upgrades easier by preventing components from exposing their internal resources. All components interact with each other through their defined APIs so that only exposed resources can be accessed by other components. Classloading isolation ensures that a component’s internal content is protected and can be changed any time, without affecting other components. Mule 4 supports [distributed file polling](https://docs.mulesoft.com/mule-runtime/4.12/distributed-file-polling), which allows connectors to read files from certain directories as they are created. Distributed file polling also makes it possible to poll files in all cluster nodes. Mule 4 also supports [distributed locking](https://docs.mulesoft.com/mule-runtime/4.12/distributed-locking), which provides the ability to create locks for synchronizing access to resources within Mule components. Learn more about [Mule data types](https://docs.mulesoft.com/mule-runtime/4.12/mule-data-types) to understand how Mule centralizes data access across different components, and also how DataWeave uses this information to determine which reader and writer to use. You can refer to the [Javadocs](https://docs.mulesoft.com/mule-runtime/4.12/mule-4-api-javadoc) for Mule Kernel (the community edition of Mule runtime engine) to learn definitions for classes, fields, and data types. You can see a list of [third-party software](https://docs.mulesoft.com/mule-runtime/4.12/third-party-software-in-mule) that is included as part of Mule runtime engine as internal dependencies. --- product: Mule Runtime version: 4.3 keywords: advanced, mule, concepts, runtime, engine --- # Advanced Mule Concepts > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you become familiar with the basics of Mule application development and Mule runtime engine (Mule) concepts, you can focus on more advanced features, such as the execution engine, the classloading isolation mechanism, and distributed file polling. Learn about the [execution engine](https://docs.mulesoft.com/mule-runtime/4.3/execution-engine) to understand how Mule runtime engine processes the operations in a Mule application flow, and to understand how to change the thread pools if needed. Mule runtime engine uses execution metadata provided by operations in a flow to perform autotuning. The [classloading isolation](https://docs.mulesoft.com/mule-runtime/4.3/about-classloading-isolation) mechanism implemented in Mule 4 is designed to make upgrades easier by preventing components from exposing their internal resources. All components interact with each other through their defined APIs so that only exposed resources can be accessed by other components. Classloading isolation ensures that a component’s internal content is protected and can be changed any time, without affecting other components. Mule 4 supports [distributed file polling](https://docs.mulesoft.com/mule-runtime/4.3/distributed-file-polling), which allows connectors to read files from certain directories as they are created. Distributed file polling also makes it possible to poll files in all cluster nodes. Mule 4 also supports [distributed locking](https://docs.mulesoft.com/mule-runtime/4.3/distributed-locking), which provides the ability to create locks for synchronizing access to resources within Mule components. You can refer to the [Javadocs](https://docs.mulesoft.com/mule-runtime/4.3/mule-4-api-javadoc) for Mule Kernel (the community edition of Mule runtime engine) to learn definitions for classes, fields, and data types. You can see a list of [third-party software](https://docs.mulesoft.com/mule-runtime/4.3/third-party-software-in-mule) that is included as part of Mule runtime engine as internal dependencies. --- product: Mule Runtime version: 4.4 keywords: advanced, mule, concepts, runtime, engine --- # Advanced Mule Concepts > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you become familiar with the basics of Mule application development and Mule runtime engine (Mule) concepts, you can focus on more advanced features, such as the execution engine, the classloading isolation mechanism, and distributed file polling. Learn about the [execution engine](https://docs.mulesoft.com/mule-runtime/4.4/execution-engine) to understand how Mule runtime engine processes the operations in a Mule application flow, and to understand how to change the thread pools if needed. Mule runtime engine uses execution metadata provided by operations in a flow to perform autotuning. The [classloading isolation](https://docs.mulesoft.com/mule-runtime/4.4/about-classloading-isolation) mechanism implemented in Mule 4 is designed to make upgrades easier by preventing components from exposing their internal resources. All components interact with each other through their defined APIs so that only exposed resources can be accessed by other components. Classloading isolation ensures that a component’s internal content is protected and can be changed any time, without affecting other components. Mule 4 supports [distributed file polling](https://docs.mulesoft.com/mule-runtime/4.4/distributed-file-polling), which allows connectors to read files from certain directories as they are created. Distributed file polling also makes it possible to poll files in all cluster nodes. Mule 4 also supports [distributed locking](https://docs.mulesoft.com/mule-runtime/4.4/distributed-locking), which provides the ability to create locks for synchronizing access to resources within Mule components. Learn more about [Mule data types](https://docs.mulesoft.com/mule-runtime/4.4/mule-data-types) to understand how Mule centralizes data access across different components, and also how DataWeave uses this information to determine which reader and writer to use. You can refer to the [Javadocs](https://docs.mulesoft.com/mule-runtime/4.4/mule-4-api-javadoc) for Mule Kernel (the community edition of Mule runtime engine) to learn definitions for classes, fields, and data types. You can see a list of [third-party software](https://docs.mulesoft.com/mule-runtime/4.4/third-party-software-in-mule) that is included as part of Mule runtime engine as internal dependencies. --- product: Mule Runtime version: 4.6 keywords: advanced, mule, concepts, runtime, engine --- # Advanced Mule Concepts > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you become familiar with the basics of Mule application development and Mule runtime engine (Mule) concepts, you can focus on more advanced features, such as the execution engine, the classloading isolation mechanism, and distributed file polling. Learn about the [execution engine](https://docs.mulesoft.com/mule-runtime/4.6/execution-engine) to understand how Mule runtime engine processes the operations in a Mule application flow, and to understand how to change the thread pools if needed. Mule runtime engine uses execution metadata provided by operations in a flow to perform autotuning. The [classloading isolation](https://docs.mulesoft.com/mule-runtime/4.6/about-classloading-isolation) mechanism implemented in Mule 4 is designed to make upgrades easier by preventing components from exposing their internal resources. All components interact with each other through their defined APIs so that only exposed resources can be accessed by other components. Classloading isolation ensures that a component’s internal content is protected and can be changed any time, without affecting other components. Mule 4 supports [distributed file polling](https://docs.mulesoft.com/mule-runtime/4.6/distributed-file-polling), which allows connectors to read files from certain directories as they are created. Distributed file polling also makes it possible to poll files in all cluster nodes. Mule 4 also supports [distributed locking](https://docs.mulesoft.com/mule-runtime/4.6/distributed-locking), which provides the ability to create locks for synchronizing access to resources within Mule components. Learn more about [Mule data types](https://docs.mulesoft.com/mule-runtime/4.6/mule-data-types) to understand how Mule centralizes data access across different components, and also how DataWeave uses this information to determine which reader and writer to use. You can refer to the [Javadocs](https://docs.mulesoft.com/mule-runtime/4.6/mule-4-api-javadoc) for Mule Kernel (the community edition of Mule runtime engine) to learn definitions for classes, fields, and data types. You can see a list of [third-party software](https://docs.mulesoft.com/mule-runtime/4.6/third-party-software-in-mule) that is included as part of Mule runtime engine as internal dependencies. --- product: Mule Runtime version: 4.9 keywords: advanced, mule, concepts, runtime, engine --- # Advanced Mule Concepts > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you become familiar with the basics of Mule application development and Mule runtime engine (Mule) concepts, you can focus on more advanced features, such as the execution engine, the classloading isolation mechanism, and distributed file polling. Learn about the [execution engine](https://docs.mulesoft.com/mule-runtime/4.9/execution-engine) to understand how Mule runtime engine processes the operations in a Mule application flow, and to understand how to change the thread pools if needed. Mule runtime engine uses execution metadata provided by operations in a flow to perform autotuning. The [classloading isolation](https://docs.mulesoft.com/mule-runtime/4.9/about-classloading-isolation) mechanism implemented in Mule 4 is designed to make upgrades easier by preventing components from exposing their internal resources. All components interact with each other through their defined APIs so that only exposed resources can be accessed by other components. Classloading isolation ensures that a component’s internal content is protected and can be changed any time, without affecting other components. Mule 4 supports [distributed file polling](https://docs.mulesoft.com/mule-runtime/4.9/distributed-file-polling), which allows connectors to read files from certain directories as they are created. Distributed file polling also makes it possible to poll files in all cluster nodes. Mule 4 also supports [distributed locking](https://docs.mulesoft.com/mule-runtime/4.9/distributed-locking), which provides the ability to create locks for synchronizing access to resources within Mule components. Learn more about [Mule data types](https://docs.mulesoft.com/mule-runtime/4.9/mule-data-types) to understand how Mule centralizes data access across different components, and also how DataWeave uses this information to determine which reader and writer to use. You can refer to the [Javadocs](https://docs.mulesoft.com/mule-runtime/4.9/mule-4-api-javadoc) for Mule Kernel (the community edition of Mule runtime engine) to learn definitions for classes, fields, and data types. You can see a list of [third-party software](https://docs.mulesoft.com/mule-runtime/4.9/third-party-software-in-mule) that is included as part of Mule runtime engine as internal dependencies. --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: advanced, mule, concepts, runtime, engine --- # Advanced Mule Concepts > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you become familiar with the basics of Mule application development and Mule runtime engine (Mule) concepts, you can focus on more advanced features, such as the execution engine, the classloading isolation mechanism, and distributed file polling. Learn about the [execution engine](https://docs.mulesoft.com/mule-runtime/latest/execution-engine) to understand how Mule runtime engine processes the operations in a Mule application flow, and to understand how to change the thread pools if needed. Mule runtime engine uses execution metadata provided by operations in a flow to perform autotuning. The [classloading isolation](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation) mechanism implemented in Mule 4 is designed to make upgrades easier by preventing components from exposing their internal resources. All components interact with each other through their defined APIs so that only exposed resources can be accessed by other components. Classloading isolation ensures that a component’s internal content is protected and can be changed any time, without affecting other components. Mule 4 supports [distributed file polling](https://docs.mulesoft.com/mule-runtime/latest/distributed-file-polling), which allows connectors to read files from certain directories as they are created. Distributed file polling also makes it possible to poll files in all cluster nodes. Mule 4 also supports [distributed locking](https://docs.mulesoft.com/mule-runtime/latest/distributed-locking), which provides the ability to create locks for synchronizing access to resources within Mule components. Learn more about [Mule data types](https://docs.mulesoft.com/mule-runtime/latest/mule-data-types) to understand how Mule centralizes data access across different components, and also how DataWeave uses this information to determine which reader and writer to use. You can refer to the [Javadocs](https://docs.mulesoft.com/mule-runtime/latest/mule-4-api-javadoc) for Mule Kernel (the community edition of Mule runtime engine) to learn definitions for classes, fields, and data types. You can see a list of [third-party software](https://docs.mulesoft.com/mule-runtime/latest/third-party-software-in-mule) that is included as part of Mule runtime engine as internal dependencies. --- product: Mule Runtime version: 4.11 --- # App Design That Maximizes Process Performance > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you design your applications, consider the following best practices for enhancing processing performance. These practices include guidelines on choosing a Mule runtime engine (Mule) version, avoiding certain app design issues, and specific settings for using Mule components and connectors. ## Mule Runtime Engine Version Before you start tuning your application, review the following Mule version recommendations: - Use the latest Mule version to create and run the application. - Update your application dependencies to the latest version so you take advantage of the recent performance improvements and bug fixes. - Update to the latest version of the Mule patch whenever possible. - When developing and testing an application, use the same Mule version as used to deploy that application in your environments. ## Tips to Design for Enhanced Processing Performance As you design your apps, consider the following recommendations to increase performance: - Instead of repeatedly using the Java module to reuse code such as Java libraries, create an SDK module with operations that wrap Java invocations. - Use DataWeave to transform or enrich data, and create payloads instead of custom scripting code such as Java and Groovy. - Avoid sequences of `set-variable/set-payload` components such as in the following example: ```xml ``` Instead, combine them into a single `ee:transform` operation that avoids generating a new event for each component: ```xml ``` - Avoid using store transient values in `set-variable`, as shown in the following example: ```xml ``` Instead, move these values into components that need them: ```xml ``` - Avoid creating property resolvers, which require using DataWeave for every event and thereby increase process overhead: ```xml ``` Instead, place DataWeave logic in a property placeholder and use a static flow reference: ```xml ``` ## Avoid Recursive Flow References Using `flow-ref` to create recursive patterns (a flow that calls itself, or mutual recursion between flows) is an antipattern that can lead to resource exhaustion and should be replaced with iterative constructs. ### Why Recursion Is Problematic The Mule runtime maintains a flow call stack for each event being processed. Each `flow-ref` invocation adds an entry to this stack. When the stack depth limit is exceeded, the runtime raises a `CRITICAL` error that can’t be handled by error handlers. Additionally, extremely long flows with many processors generate deeply nested internal execution chains. When these flows are combined with recursive patterns or very deep call chains, the accumulated nesting can exhaust the JVM thread stack and produce a `StackOverflowError` or `VirtualMachineError`, which leaves the runtime in an inconsistent state (see [What Happens After a FATAL\_JVM\_ERROR](https://docs.mulesoft.com/mule-runtime/4.11/mule-error-concept#fatal_jvm_errors)). ### Antipattern: Recursive Flow-Ref This example is an antipattern because it creates a recursive pattern by calling the same flow repeatedly. ```xml ``` ### Recommended Alternatives
Use CaseRecommended Pattern

Process each item in a collection

Use <foreach> or <parallel-foreach> scope.

Process items in large datasets

Use <batch:job> for batch processing.

Retry an operation

Use <until-successful> with maxRetries.

Poll until a condition is met

Use a source-based polling trigger (for example, a Scheduler with a watermark).

Paginated API calls

Use connector-native pagination or a <foreach> over page numbers.

Complex iterative logic that can’t be expressed using built-in scopes

Implement a custom router by using the Mule SDK that encapsulates the iteration logic in Java, avoiding deep nesting in the Mule execution chain.

### Example: Replace Recursion with For Each This example shows how to replace recursion with a For Each scope. ```xml ``` ### Keep Flows Short Beyond avoiding recursion, keep individual flows at a reasonable length. Flows with hundreds of processors generate deep internal execution chains. If a flow grows too large, split it into smaller flows and invoke the flows with `flow-ref`. Unlike subflows, which are inlined at execution time and don’t reduce internal nesting, separate flows introduce independent execution chains and reset internal nesting depth. This helps prevent stack overflow conditions while improving readability and maintainability. ## Components and Connectors Best Practices When designing your apps using Mule components and connectors, consider the following recommendations to enhance the performance. ### APIkit To improve performance, disable APIkit validations. If payload validations are required, APIkit validates input requests against API specification. ### DataWeave When using DataWeave, consider the following ways to improve performance: - If payloads are large, include `indent=false` to improve client parsing and reduce response size. - Define `content-type` to avoid verbose messages in the log. - Use inline DataWeave scripts during development and then move them to an external file to have a clean XML and reusable scripts. - Do not log complex DataWeave expressions with every request. - Avoid patterns of iterating over a collection and then transforming each individual item: ```xml { (upper(key)): value } ]]> ... ``` Instead, transform the entire collection and iterate later: ```xml { book: item mapObject (value, key) -> { (upper(key)): value } } ]]> ... ``` ### Validator Use Validator Module instead of throwing exceptions with Groovy Scripts. ### HTTP and HTTPS For HTTP and HTTPS, consider the following recommendations: - Use the authentication mechanisms provided by Anypoint Connector for HTTP (HTTP Connector) instead using manual authentications such as manually generating the Basic auth header with a DataWeave expression. - If HTTPS is required, use the HTTPS Listener with a TLS Context reference, configuring the keystore with key-pair values generated with Keytool. You can avoid HTTPS configuration if the SSL can also be terminated at the Load Balancer level when using a dedicated load balancer in CloudHub or if there is an on-premises load balancer for hybrid scenarios: ```xml ``` ### Database Use parameterized queries. If you must use dynamic queries, remember to validate inputs first. Using dynamic queries could cause SQL-Injection vulnerability. ### File Connector Instead of using a transform component for the transformation in the write operation, use a DataWeave expression. This avoids message payload changes that occur after the write operation, as shown in the following example: ```xml #[%dw 2.0 output application/csv --- payload.customers.email ] ``` Use the recursive parameter to list files and folders within subfolders: ```xml ``` ### Web Service Consumer Connector To import WSDLs including all references (XSDs) in your project, use Anypoint Connector for Web Service Consumer (Web Service Consumer Connector) and point the configuration to the local WSDL. ### AMQP Connector Because the server constrains the performance and configuration of Anypoint Connector for AMQP (AMQP Connector), when you investigate performance issues, explore the server-side configuration to determine if consume or publish parameters have an impact on performance. #### Consume Parameters Review consume parameters that can have an impact on performance. ##### Number of Consumers Setting the number of consumers for an AMQP configuration and the Listener source determines how many consumers are spawned by the source and receive AMQP messages concurrently, as each consumer creates and uses a different channel. Message throughput depends on the number of consumers, becoming greater as the number of consumers increases. However, throughput is also affected by the performance characteristics of the flow. ##### ACK Mode Parameter ACK mode determines the acknowledgment mode to use when consuming from the AMQP broker. You set acknowledgment mode (ACK) at the configuration level (using the **Consumer** tab), but Listener and consume operations can override this mode. There are three acknowledgment modes: - `AUTO` Use Automatic to acknowledge a received message automatically only if the flow execution finishes successfully. - `MANUAL` Use Manual if you want the app logic to control message acknowledgment. - `IMMEDIATE` Use Immediate when you want to acknowledge messages as your app consumes them, before processing them. Note that if a transaction is opened in the channel, the ACK mode parameter is overruled and the commit automatically process the message acknowledgment and the rollback automatically process the recovery. ##### Quality of Service Tab You set QoS parameters at the configuration level (using the **Quality of Service** tab), with 0 representing an unlimited value. A Listener operation can override this setting. These are the parameters: - Prefetch Size Defines a prefetch size window. The broker sends as many messages as possible without exceeding the prefetch size window in octets (bytes). - Prefetch Count Specifies a global prefetch window in terms of the maximum number of whole messages. You can use this parameter in combination with the `prefetch-size` parameter to send a message in advance only it both prefetch windows sizes allow it. ##### ACK Mode and Prefetch The acknowledgment mode and QoS prefetch value that you choose have a significant effect on consumer throughput. In general, increasing the prefetch value and choosing Immediate acknowledgment mode yield the best possible rate of delivery. However, with both choices the number of delivered but not yet processed messages also increases, thereby increasing consumer RAM consumption Automatic acknowledgement mode or Manual acknowledgment mode with unlimited prefetch should be used with care. Consumption of a lot of messages without acknowledgement leads to increased memory consumption on the broker node. Finding a suitable prefetch value is a matter of trial and error and can vary from workload to workload. #### Publish Parameters Set the following parameters at the configuration level, using the **Publisher** tab. Publish and Publish-consume operations can override these parameters. Depending on your use case, you might need to enable only one of these parameters. ##### Delivery Mode Parameter Setting this parameter determines the delivery mode used to publish to the AMQP broker. Possible parameters values are: - `PERSISTENT` Delivered messages to durable queues are logged to disk on the broker. - `TRANSIENT` Delivered messages are not logged. The broker is responsible for the implementation of the recordable storage mechanism for persistent messages. The impact of this feature on performance depends on the AMQP server. ##### Request Broker Confirm Parameter If the broker provides no confirmation, setting this parameter determines whether the operation fails. Using this parameter adds one extra communication between the broker and the client per message published. ## See Also - [Configure Property Placeholders](https://docs.mulesoft.com/mule-runtime/4.11/mule-app-properties-to-configure) - [Getting Started with the Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) - [SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection) - [Finding bottlenecks with RabbitMQ 3.3](https://www.rabbitmq.com/blog/2014/04/14/finding-bottlenecks-with-rabbitmq-3-3/) --- product: Mule Runtime version: 4.12 --- # App Design That Maximizes Process Performance > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you design your applications, consider the following best practices for enhancing processing performance. These practices include guidelines on choosing a Mule runtime engine (Mule) version, avoiding certain app design issues, and specific settings for using Mule components and connectors. ## Mule Runtime Engine Version Before you start tuning your application, review the following Mule version recommendations: - Use the latest Mule version to create and run the application. - Update your application dependencies to the latest version so you take advantage of the recent performance improvements and bug fixes. - Update to the latest version of the Mule patch whenever possible. - When developing and testing an application, use the same Mule version as used to deploy that application in your environments. ## Tips to Design for Enhanced Processing Performance As you design your apps, consider the following recommendations to increase performance: - Instead of repeatedly using the Java module to reuse code such as Java libraries, create an SDK module with operations that wrap Java invocations. - Use DataWeave to transform or enrich data, and create payloads instead of custom scripting code such as Java and Groovy. - Avoid sequences of `set-variable/set-payload` components such as in the following example: ```xml ``` Instead, combine them into a single `ee:transform` operation that avoids generating a new event for each component: ```xml ``` - Avoid using store transient values in `set-variable`, as shown in the following example: ```xml ``` Instead, move these values into components that need them: ```xml ``` - Avoid creating property resolvers, which require using DataWeave for every event and thereby increase process overhead: ```xml ``` Instead, place DataWeave logic in a property placeholder and use a static flow reference: ```xml ``` ## Avoid Recursive Flow References Using `flow-ref` to create recursive patterns (a flow that calls itself, or mutual recursion between flows) is an antipattern that can lead to resource exhaustion and should be replaced with iterative constructs. ### Why Recursion Is Problematic The Mule runtime maintains a flow call stack for each event being processed. Each `flow-ref` invocation adds an entry to this stack. When the stack depth limit is exceeded, the runtime raises a `CRITICAL` error that can’t be handled by error handlers. Additionally, extremely long flows with many processors generate deeply nested internal execution chains. When these flows are combined with recursive patterns or very deep call chains, the accumulated nesting can exhaust the JVM thread stack and produce a `StackOverflowError` or `VirtualMachineError`, which leaves the runtime in an inconsistent state (see [What Happens After a FATAL\_JVM\_ERROR](https://docs.mulesoft.com/mule-runtime/4.12/mule-error-concept#fatal_jvm_errors)). ### Antipattern: Recursive Flow-Ref This example is an antipattern because it creates a recursive pattern by calling the same flow repeatedly. ```xml ``` ### Recommended Alternatives
Use CaseRecommended Pattern

Process each item in a collection

Use <foreach> or <parallel-foreach> scope.

Process items in large datasets

Use <batch:job> for batch processing.

Retry an operation

Use <until-successful> with maxRetries.

Poll until a condition is met

Use a source-based polling trigger (for example, a Scheduler with a watermark).

Paginated API calls

Use connector-native pagination or a <foreach> over page numbers.

Complex iterative logic that can’t be expressed using built-in scopes

Implement a custom router by using the Mule SDK that encapsulates the iteration logic in Java, avoiding deep nesting in the Mule execution chain.

### Example: Replace Recursion with For Each This example shows how to replace recursion with a For Each scope. ```xml ``` ### Keep Flows Short Beyond avoiding recursion, keep individual flows at a reasonable length. Flows with hundreds of processors generate deep internal execution chains. If a flow grows too large, split it into smaller flows and invoke the flows with `flow-ref`. Unlike subflows, which are inlined at execution time and don’t reduce internal nesting, separate flows introduce independent execution chains and reset internal nesting depth. This helps prevent stack overflow conditions while improving readability and maintainability. ## Components and Connectors Best Practices When designing your apps using Mule components and connectors, consider the following recommendations to enhance the performance. ### APIkit To improve performance, disable APIkit validations. If payload validations are required, APIkit validates input requests against API specification. ### DataWeave When using DataWeave, consider the following ways to improve performance: - If payloads are large, include `indent=false` to improve client parsing and reduce response size. - Define `content-type` to avoid verbose messages in the log. - Use inline DataWeave scripts during development and then move them to an external file to have a clean XML and reusable scripts. - Do not log complex DataWeave expressions with every request. - Avoid patterns of iterating over a collection and then transforming each individual item: ```xml { (upper(key)): value } ]]> ... ``` Instead, transform the entire collection and iterate later: ```xml { book: item mapObject (value, key) -> { (upper(key)): value } } ]]> ... ``` ### Validator Use Validator Module instead of throwing exceptions with Groovy Scripts. ### HTTP and HTTPS For HTTP and HTTPS, consider the following recommendations: - Use the authentication mechanisms provided by Anypoint Connector for HTTP (HTTP Connector) instead using manual authentications such as manually generating the Basic auth header with a DataWeave expression. - If HTTPS is required, use the HTTPS Listener with a TLS Context reference, configuring the keystore with key-pair values generated with Keytool. You can avoid HTTPS configuration if the SSL can also be terminated at the Load Balancer level when using a dedicated load balancer in CloudHub or if there is an on-premises load balancer for hybrid scenarios: ```xml ``` ### Database Use parameterized queries. If you must use dynamic queries, remember to validate inputs first. Using dynamic queries could cause SQL-Injection vulnerability. ### File Connector Instead of using a transform component for the transformation in the write operation, use a DataWeave expression. This avoids message payload changes that occur after the write operation, as shown in the following example: ```xml #[%dw 2.0 output application/csv --- payload.customers.email ] ``` Use the recursive parameter to list files and folders within subfolders: ```xml ``` ### Web Service Consumer Connector To import WSDLs including all references (XSDs) in your project, use Anypoint Connector for Web Service Consumer (Web Service Consumer Connector) and point the configuration to the local WSDL. ### AMQP Connector Because the server constrains the performance and configuration of Anypoint Connector for AMQP (AMQP Connector), when you investigate performance issues, explore the server-side configuration to determine if consume or publish parameters have an impact on performance. #### Consume Parameters Review consume parameters that can have an impact on performance. ##### Number of Consumers Setting the number of consumers for an AMQP configuration and the Listener source determines how many consumers are spawned by the source and receive AMQP messages concurrently, as each consumer creates and uses a different channel. Message throughput depends on the number of consumers, becoming greater as the number of consumers increases. However, throughput is also affected by the performance characteristics of the flow. ##### ACK Mode Parameter ACK mode determines the acknowledgment mode to use when consuming from the AMQP broker. You set acknowledgment mode (ACK) at the configuration level (using the **Consumer** tab), but Listener and consume operations can override this mode. There are three acknowledgment modes: - `AUTO` Use Automatic to acknowledge a received message automatically only if the flow execution finishes successfully. - `MANUAL` Use Manual if you want the app logic to control message acknowledgment. - `IMMEDIATE` Use Immediate when you want to acknowledge messages as your app consumes them, before processing them. Note that if a transaction is opened in the channel, the ACK mode parameter is overruled and the commit automatically process the message acknowledgment and the rollback automatically process the recovery. ##### Quality of Service Tab You set QoS parameters at the configuration level (using the **Quality of Service** tab), with 0 representing an unlimited value. A Listener operation can override this setting. These are the parameters: - Prefetch Size Defines a prefetch size window. The broker sends as many messages as possible without exceeding the prefetch size window in octets (bytes). - Prefetch Count Specifies a global prefetch window in terms of the maximum number of whole messages. You can use this parameter in combination with the `prefetch-size` parameter to send a message in advance only it both prefetch windows sizes allow it. ##### ACK Mode and Prefetch The acknowledgment mode and QoS prefetch value that you choose have a significant effect on consumer throughput. In general, increasing the prefetch value and choosing Immediate acknowledgment mode yield the best possible rate of delivery. However, with both choices the number of delivered but not yet processed messages also increases, thereby increasing consumer RAM consumption Automatic acknowledgement mode or Manual acknowledgment mode with unlimited prefetch should be used with care. Consumption of a lot of messages without acknowledgement leads to increased memory consumption on the broker node. Finding a suitable prefetch value is a matter of trial and error and can vary from workload to workload. #### Publish Parameters Set the following parameters at the configuration level, using the **Publisher** tab. Publish and Publish-consume operations can override these parameters. Depending on your use case, you might need to enable only one of these parameters. ##### Delivery Mode Parameter Setting this parameter determines the delivery mode used to publish to the AMQP broker. Possible parameters values are: - `PERSISTENT` Delivered messages to durable queues are logged to disk on the broker. - `TRANSIENT` Delivered messages are not logged. The broker is responsible for the implementation of the recordable storage mechanism for persistent messages. The impact of this feature on performance depends on the AMQP server. ##### Request Broker Confirm Parameter If the broker provides no confirmation, setting this parameter determines whether the operation fails. Using this parameter adds one extra communication between the broker and the client per message published. ## See Also - [Configure Property Placeholders](https://docs.mulesoft.com/mule-runtime/4.12/mule-app-properties-to-configure) - [Getting Started with the Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) - [SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection) - [Finding bottlenecks with RabbitMQ 3.3](https://www.rabbitmq.com/blog/2014/04/14/finding-bottlenecks-with-rabbitmq-3-3/) --- product: Mule Runtime version: 4.3 --- # App Design That Maximizes Process Performance > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you design your applications, consider the following best practices for enhancing processing performance. These practices include guidelines on choosing a Mule runtime engine (Mule) version, avoiding certain app design issues, and specific settings for using Mule components and connectors. ## Mule Runtime Engine Version Before you start tuning your application, review the following Mule version recommendations: - Use the latest Mule version to create and run the application. - Update your application dependencies to the latest version so you take advantage of the recent performance improvements and bug fixes. - Update to the latest version of the Mule patch whenever possible. - When developing and testing an application, use the same Mule version as used to deploy that application in your environments. ## Tips to Design for Enhanced Processing Performance As you design your apps, consider the following recommendations to increase performance: - Instead of repeatedly using the Java module to reuse code such as Java libraries, create an SDK module with operations that wrap Java invocations. - Use DataWeave to transform or enrich data, and create payloads instead of custom scripting code such as Java and Groovy. - Avoid sequences of `set-variable/set-payload` components such as in the following example: ```xml ``` Instead, combine them into a single `ee:transform` operation that avoids generating a new event for each component: ```xml ``` - Avoid using store transient values in `set-variable`, as shown in the following example: ```xml ``` Instead, move these values into components that need them: ```xml ``` - Avoid creating property resolvers, which require using DataWeave for every event and thereby increase process overhead: ```xml ``` Instead, place DataWeave logic in a property placeholder and use a static flow reference: ```xml ``` ## Components and Connectors Best Practices When designing your apps using Mule components and connectors, consider the following recommendations to enhance the performance. ### APIkit To improve performance, disable APIkit validations. If payload validations are required, APIkit validates input requests against API specification. ### DataWeave When using DataWeave, consider the following ways to improve performance: - If payloads are large, include `indent=false` to improve client parsing and reduce response size. - Define `content-type` to avoid verbose messages in the log. - Use inline DataWeave scripts during development and then move them to an external file to have a clean XML and reusable scripts. - Do not log complex DataWeave expressions with every request. - Avoid patterns of iterating over a collection and then transforming each individual item: ```xml { (upper(key)): value } ]]> ... ``` Instead, transform the entire collection and iterate later: ```xml { book: item mapObject (value, key) -> { (upper(key)): value } } ]]> ... ``` ### Validator Use Validator Module instead of throwing exceptions with Groovy Scripts. ### HTTP and HTTPS For HTTP and HTTPS, consider the following recommendations: - Use the authentication mechanisms provided by Anypoint Connector for HTTP (HTTP Connector) instead using manual authentications such as manually generating the Basic auth header with a DataWeave expression. - If HTTPS is required, use the HTTPS Listener with a TLS Context reference, configuring the keystore with key-pair values generated with Keytool. You can avoid HTTPS configuration if the SSL can also be terminated at the Load Balancer level when using a dedicated load balancer in CloudHub or if there is an on-premises load balancer for hybrid scenarios: ```xml ``` ### Database Use parameterized queries. If you must use dynamic queries, remember to validate inputs first. Using dynamic queries could cause SQL-Injection vulnerability. ### File Connector Instead of using a transform component for the transformation in the write operation, use a DataWeave expression. This avoids message payload changes that occur after the write operation, as shown in the following example: ```xml #[%dw 2.0 output application/csv --- payload.customers.email ] ``` Use the recursive parameter to list files and folders within subfolders: ```xml ``` ### Web Service Consumer Connector To import WSDLs including all references (XSDs) in your project, use Anypoint Connector for Web Service Consumer (Web Service Consumer Connector) and point the configuration to the local WSDL. ### AMQP Connector Because the server constrains the performance and configuration of Anypoint Connector for AMQP (AMQP Connector), when you investigate performance issues, explore the server-side configuration to determine if consume or publish parameters have an impact on performance. #### Consume Parameters Review consume parameters that can have an impact on performance. ##### Number of Consumers Setting the number of consumers for an AMQP configuration and the Listener source determines how many consumers are spawned by the source and receive AMQP messages concurrently, as each consumer creates and uses a different channel. Message throughput depends on the number of consumers, becoming greater as the number of consumers increases. However, throughput is also affected by the performance characteristics of the flow. ##### ACK Mode Parameter ACK mode determines the acknowledgment mode to use when consuming from the AMQP broker. You set acknowledgment mode (ACK) at the configuration level (using the **Consumer** tab), but Listener and consume operations can override this mode. There are three acknowledgment modes: - `AUTO` Use Automatic to acknowledge a received message automatically only if the flow execution finishes successfully. - `MANUAL` Use Manual if you want the app logic to control message acknowledgment. - `IMMEDIATE` Use Immediate when you want to acknowledge messages as your app consumes them, before processing them. Note that if a transaction is opened in the channel, the ACK mode parameter is overruled and the commit automatically process the message acknowledgment and the rollback automatically process the recovery. ##### Quality of Service Tab You set QoS parameters at the configuration level (using the **Quality of Service** tab), with 0 representing an unlimited value. A Listener operation can override this setting. These are the parameters: - Prefetch Size Defines a prefetch size window. The broker sends as many messages as possible without exceeding the prefetch size window in octets (bytes). - Prefetch Count Specifies a global prefetch window in terms of the maximum number of whole messages. You can use this parameter in combination with the `prefetch-size` parameter to send a message in advance only it both prefetch windows sizes allow it. ##### ACK Mode and Prefetch The acknowledgment mode and QoS prefetch value that you choose have a significant effect on consumer throughput. In general, increasing the prefetch value and choosing Immediate acknowledgment mode yield the best possible rate of delivery. However, with both choices the number of delivered but not yet processed messages also increases, thereby increasing consumer RAM consumption Automatic acknowledgement mode or Manual acknowledgment mode with unlimited prefetch should be used with care. Consumption of a lot of messages without acknowledgement leads to increased memory consumption on the broker node. Finding a suitable prefetch value is a matter of trial and error and can vary from workload to workload. #### Publish Parameters Set the following parameters at the configuration level, using the **Publisher** tab. Publish and Publish-consume operations can override these parameters. Depending on your use case, you might need to enable only one of these parameters. ##### Delivery Mode Parameter Setting this parameter determines the delivery mode used to publish to the AMQP broker. Possible parameters values are: - `PERSISTENT` Delivered messages to durable queues are logged to disk on the broker. - `TRANSIENT` Delivered messages are not logged. The broker is responsible for the implementation of the recordable storage mechanism for persistent messages. The impact of this feature on performance depends on the AMQP server. ##### Request Broker Confirm Parameter If the broker provides no confirmation, setting this parameter determines whether the operation fails. Using this parameter adds one extra communication between the broker and the client per message published. ## See Also - [Configure Property Placeholders](https://docs.mulesoft.com/mule-runtime/4.3/mule-app-properties-to-configure) - [Getting Started with the Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) - [SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection) - [Finding bottlenecks with RabbitMQ 3.3](https://www.rabbitmq.com/blog/2014/04/14/finding-bottlenecks-with-rabbitmq-3-3/) --- product: Mule Runtime version: 4.4 --- # App Design That Maximizes Process Performance > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you design your applications, consider the following best practices for enhancing processing performance. These practices include guidelines on choosing a Mule runtime engine (Mule) version, avoiding certain app design issues, and specific settings for using Mule components and connectors. ## Mule Runtime Engine Version Before you start tuning your application, review the following Mule version recommendations: - Use the latest Mule version to create and run the application. - Update your application dependencies to the latest version so you take advantage of the recent performance improvements and bug fixes. - Update to the latest version of the Mule patch whenever possible. - When developing and testing an application, use the same Mule version as used to deploy that application in your environments. ## Tips to Design for Enhanced Processing Performance As you design your apps, consider the following recommendations to increase performance: - Instead of repeatedly using the Java module to reuse code such as Java libraries, create an SDK module with operations that wrap Java invocations. - Use DataWeave to transform or enrich data, and create payloads instead of custom scripting code such as Java and Groovy. - Avoid sequences of `set-variable/set-payload` components such as in the following example: ```xml ``` Instead, combine them into a single `ee:transform` operation that avoids generating a new event for each component: ```xml ``` - Avoid using store transient values in `set-variable`, as shown in the following example: ```xml ``` Instead, move these values into components that need them: ```xml ``` - Avoid creating property resolvers, which require using DataWeave for every event and thereby increase process overhead: ```xml ``` Instead, place DataWeave logic in a property placeholder and use a static flow reference: ```xml ``` ## Components and Connectors Best Practices When designing your apps using Mule components and connectors, consider the following recommendations to enhance the performance. ### APIkit To improve performance, disable APIkit validations. If payload validations are required, APIkit validates input requests against API specification. ### DataWeave When using DataWeave, consider the following ways to improve performance: - If payloads are large, include `indent=false` to improve client parsing and reduce response size. - Define `content-type` to avoid verbose messages in the log. - Use inline DataWeave scripts during development and then move them to an external file to have a clean XML and reusable scripts. - Do not log complex DataWeave expressions with every request. - Avoid patterns of iterating over a collection and then transforming each individual item: ```xml { (upper(key)): value } ]]> ... ``` Instead, transform the entire collection and iterate later: ```xml { book: item mapObject (value, key) -> { (upper(key)): value } } ]]> ... ``` ### Validator Use Validator Module instead of throwing exceptions with Groovy Scripts. ### HTTP and HTTPS For HTTP and HTTPS, consider the following recommendations: - Use the authentication mechanisms provided by Anypoint Connector for HTTP (HTTP Connector) instead using manual authentications such as manually generating the Basic auth header with a DataWeave expression. - If HTTPS is required, use the HTTPS Listener with a TLS Context reference, configuring the keystore with key-pair values generated with Keytool. You can avoid HTTPS configuration if the SSL can also be terminated at the Load Balancer level when using a dedicated load balancer in CloudHub or if there is an on-premises load balancer for hybrid scenarios: ```xml ``` ### Database Use parameterized queries. If you must use dynamic queries, remember to validate inputs first. Using dynamic queries could cause SQL-Injection vulnerability. ### File Connector Instead of using a transform component for the transformation in the write operation, use a DataWeave expression. This avoids message payload changes that occur after the write operation, as shown in the following example: ```xml #[%dw 2.0 output application/csv --- payload.customers.email ] ``` Use the recursive parameter to list files and folders within subfolders: ```xml ``` ### Web Service Consumer Connector To import WSDLs including all references (XSDs) in your project, use Anypoint Connector for Web Service Consumer (Web Service Consumer Connector) and point the configuration to the local WSDL. ### AMQP Connector Because the server constrains the performance and configuration of Anypoint Connector for AMQP (AMQP Connector), when you investigate performance issues, explore the server-side configuration to determine if consume or publish parameters have an impact on performance. #### Consume Parameters Review consume parameters that can have an impact on performance. ##### Number of Consumers Setting the number of consumers for an AMQP configuration and the Listener source determines how many consumers are spawned by the source and receive AMQP messages concurrently, as each consumer creates and uses a different channel. Message throughput depends on the number of consumers, becoming greater as the number of consumers increases. However, throughput is also affected by the performance characteristics of the flow. ##### ACK Mode Parameter ACK mode determines the acknowledgment mode to use when consuming from the AMQP broker. You set acknowledgment mode (ACK) at the configuration level (using the **Consumer** tab), but Listener and consume operations can override this mode. There are three acknowledgment modes: - `AUTO` Use Automatic to acknowledge a received message automatically only if the flow execution finishes successfully. - `MANUAL` Use Manual if you want the app logic to control message acknowledgment. - `IMMEDIATE` Use Immediate when you want to acknowledge messages as your app consumes them, before processing them. Note that if a transaction is opened in the channel, the ACK mode parameter is overruled and the commit automatically process the message acknowledgment and the rollback automatically process the recovery. ##### Quality of Service Tab You set QoS parameters at the configuration level (using the **Quality of Service** tab), with 0 representing an unlimited value. A Listener operation can override this setting. These are the parameters: - Prefetch Size Defines a prefetch size window. The broker sends as many messages as possible without exceeding the prefetch size window in octets (bytes). - Prefetch Count Specifies a global prefetch window in terms of the maximum number of whole messages. You can use this parameter in combination with the `prefetch-size` parameter to send a message in advance only it both prefetch windows sizes allow it. ##### ACK Mode and Prefetch The acknowledgment mode and QoS prefetch value that you choose have a significant effect on consumer throughput. In general, increasing the prefetch value and choosing Immediate acknowledgment mode yield the best possible rate of delivery. However, with both choices the number of delivered but not yet processed messages also increases, thereby increasing consumer RAM consumption Automatic acknowledgement mode or Manual acknowledgment mode with unlimited prefetch should be used with care. Consumption of a lot of messages without acknowledgement leads to increased memory consumption on the broker node. Finding a suitable prefetch value is a matter of trial and error and can vary from workload to workload. #### Publish Parameters Set the following parameters at the configuration level, using the **Publisher** tab. Publish and Publish-consume operations can override these parameters. Depending on your use case, you might need to enable only one of these parameters. ##### Delivery Mode Parameter Setting this parameter determines the delivery mode used to publish to the AMQP broker. Possible parameters values are: - `PERSISTENT` Delivered messages to durable queues are logged to disk on the broker. - `TRANSIENT` Delivered messages are not logged. The broker is responsible for the implementation of the recordable storage mechanism for persistent messages. The impact of this feature on performance depends on the AMQP server. ##### Request Broker Confirm Parameter If the broker provides no confirmation, setting this parameter determines whether the operation fails. Using this parameter adds one extra communication between the broker and the client per message published. ## See Also - [Configure Property Placeholders](https://docs.mulesoft.com/mule-runtime/4.4/mule-app-properties-to-configure) - [Getting Started with the Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) - [SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection) - [Finding bottlenecks with RabbitMQ 3.3](https://www.rabbitmq.com/blog/2014/04/14/finding-bottlenecks-with-rabbitmq-3-3/) --- product: Mule Runtime version: 4.6 --- # App Design That Maximizes Process Performance > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you design your applications, consider the following best practices for enhancing processing performance. These practices include guidelines on choosing a Mule runtime engine (Mule) version, avoiding certain app design issues, and specific settings for using Mule components and connectors. ## Mule Runtime Engine Version Before you start tuning your application, review the following Mule version recommendations: - Use the latest Mule version to create and run the application. - Update your application dependencies to the latest version so you take advantage of the recent performance improvements and bug fixes. - Update to the latest version of the Mule patch whenever possible. - When developing and testing an application, use the same Mule version as used to deploy that application in your environments. ## Tips to Design for Enhanced Processing Performance As you design your apps, consider the following recommendations to increase performance: - Instead of repeatedly using the Java module to reuse code such as Java libraries, create an SDK module with operations that wrap Java invocations. - Use DataWeave to transform or enrich data, and create payloads instead of custom scripting code such as Java and Groovy. - Avoid sequences of `set-variable/set-payload` components such as in the following example: ```xml ``` Instead, combine them into a single `ee:transform` operation that avoids generating a new event for each component: ```xml ``` - Avoid using store transient values in `set-variable`, as shown in the following example: ```xml ``` Instead, move these values into components that need them: ```xml ``` - Avoid creating property resolvers, which require using DataWeave for every event and thereby increase process overhead: ```xml ``` Instead, place DataWeave logic in a property placeholder and use a static flow reference: ```xml ``` ## Avoid Recursive Flow References Using `flow-ref` to create recursive patterns (a flow that calls itself, or mutual recursion between flows) is an antipattern that can lead to resource exhaustion and should be replaced with iterative constructs. ### Why Recursion Is Problematic The Mule runtime maintains a flow call stack for each event being processed. Each `flow-ref` invocation adds an entry to this stack. When the stack depth limit is exceeded, the runtime raises a `CRITICAL` error that can’t be handled by error handlers. Additionally, extremely long flows with many processors generate deeply nested internal execution chains. When these flows are combined with recursive patterns or very deep call chains, the accumulated nesting can exhaust the JVM thread stack and produce a `StackOverflowError` or `VirtualMachineError`, which leaves the runtime in an inconsistent state (see [What Happens After a FATAL\_JVM\_ERROR](https://docs.mulesoft.com/mule-runtime/4.6/mule-error-concept#fatal_jvm_errors)). ### Antipattern: Recursive Flow-Ref This example is an antipattern because it creates a recursive pattern by calling the same flow repeatedly. ```xml ``` ### Recommended Alternatives
Use CaseRecommended Pattern

Process each item in a collection

Use <foreach> or <parallel-foreach> scope.

Process items in large datasets

Use <batch:job> for batch processing.

Retry an operation

Use <until-successful> with maxRetries.

Poll until a condition is met

Use a source-based polling trigger (for example, a Scheduler with a watermark).

Paginated API calls

Use connector-native pagination or a <foreach> over page numbers.

Complex iterative logic that can’t be expressed using built-in scopes

Implement a custom router by using the Mule SDK that encapsulates the iteration logic in Java, avoiding deep nesting in the Mule execution chain.

### Example: Replace Recursion with For Each This example shows how to replace recursion with a For Each scope. ```xml ``` ### Keep Flows Short Beyond avoiding recursion, keep individual flows at a reasonable length. Flows with hundreds of processors generate deep internal execution chains. If a flow grows too large, split it into smaller flows and invoke the flows with `flow-ref`. Unlike subflows, which are inlined at execution time and don’t reduce internal nesting, separate flows introduce independent execution chains and reset internal nesting depth. This helps prevent stack overflow conditions while improving readability and maintainability. ## Components and Connectors Best Practices When designing your apps using Mule components and connectors, consider the following recommendations to enhance the performance. ### APIkit To improve performance, disable APIkit validations. If payload validations are required, APIkit validates input requests against API specification. ### DataWeave When using DataWeave, consider the following ways to improve performance: - If payloads are large, include `indent=false` to improve client parsing and reduce response size. - Define `content-type` to avoid verbose messages in the log. - Use inline DataWeave scripts during development and then move them to an external file to have a clean XML and reusable scripts. - Do not log complex DataWeave expressions with every request. - Avoid patterns of iterating over a collection and then transforming each individual item: ```xml { (upper(key)): value } ]]> ... ``` Instead, transform the entire collection and iterate later: ```xml { book: item mapObject (value, key) -> { (upper(key)): value } } ]]> ... ``` ### Validator Use Validator Module instead of throwing exceptions with Groovy Scripts. ### HTTP and HTTPS For HTTP and HTTPS, consider the following recommendations: - Use the authentication mechanisms provided by Anypoint Connector for HTTP (HTTP Connector) instead using manual authentications such as manually generating the Basic auth header with a DataWeave expression. - If HTTPS is required, use the HTTPS Listener with a TLS Context reference, configuring the keystore with key-pair values generated with Keytool. You can avoid HTTPS configuration if the SSL can also be terminated at the Load Balancer level when using a dedicated load balancer in CloudHub or if there is an on-premises load balancer for hybrid scenarios: ```xml ``` ### Database Use parameterized queries. If you must use dynamic queries, remember to validate inputs first. Using dynamic queries could cause SQL-Injection vulnerability. ### File Connector Instead of using a transform component for the transformation in the write operation, use a DataWeave expression. This avoids message payload changes that occur after the write operation, as shown in the following example: ```xml #[%dw 2.0 output application/csv --- payload.customers.email ] ``` Use the recursive parameter to list files and folders within subfolders: ```xml ``` ### Web Service Consumer Connector To import WSDLs including all references (XSDs) in your project, use Anypoint Connector for Web Service Consumer (Web Service Consumer Connector) and point the configuration to the local WSDL. ### AMQP Connector Because the server constrains the performance and configuration of Anypoint Connector for AMQP (AMQP Connector), when you investigate performance issues, explore the server-side configuration to determine if consume or publish parameters have an impact on performance. #### Consume Parameters Review consume parameters that can have an impact on performance. ##### Number of Consumers Setting the number of consumers for an AMQP configuration and the Listener source determines how many consumers are spawned by the source and receive AMQP messages concurrently, as each consumer creates and uses a different channel. Message throughput depends on the number of consumers, becoming greater as the number of consumers increases. However, throughput is also affected by the performance characteristics of the flow. ##### ACK Mode Parameter ACK mode determines the acknowledgment mode to use when consuming from the AMQP broker. You set acknowledgment mode (ACK) at the configuration level (using the **Consumer** tab), but Listener and consume operations can override this mode. There are three acknowledgment modes: - `AUTO` Use Automatic to acknowledge a received message automatically only if the flow execution finishes successfully. - `MANUAL` Use Manual if you want the app logic to control message acknowledgment. - `IMMEDIATE` Use Immediate when you want to acknowledge messages as your app consumes them, before processing them. Note that if a transaction is opened in the channel, the ACK mode parameter is overruled and the commit automatically process the message acknowledgment and the rollback automatically process the recovery. ##### Quality of Service Tab You set QoS parameters at the configuration level (using the **Quality of Service** tab), with 0 representing an unlimited value. A Listener operation can override this setting. These are the parameters: - Prefetch Size Defines a prefetch size window. The broker sends as many messages as possible without exceeding the prefetch size window in octets (bytes). - Prefetch Count Specifies a global prefetch window in terms of the maximum number of whole messages. You can use this parameter in combination with the `prefetch-size` parameter to send a message in advance only it both prefetch windows sizes allow it. ##### ACK Mode and Prefetch The acknowledgment mode and QoS prefetch value that you choose have a significant effect on consumer throughput. In general, increasing the prefetch value and choosing Immediate acknowledgment mode yield the best possible rate of delivery. However, with both choices the number of delivered but not yet processed messages also increases, thereby increasing consumer RAM consumption Automatic acknowledgement mode or Manual acknowledgment mode with unlimited prefetch should be used with care. Consumption of a lot of messages without acknowledgement leads to increased memory consumption on the broker node. Finding a suitable prefetch value is a matter of trial and error and can vary from workload to workload. #### Publish Parameters Set the following parameters at the configuration level, using the **Publisher** tab. Publish and Publish-consume operations can override these parameters. Depending on your use case, you might need to enable only one of these parameters. ##### Delivery Mode Parameter Setting this parameter determines the delivery mode used to publish to the AMQP broker. Possible parameters values are: - `PERSISTENT` Delivered messages to durable queues are logged to disk on the broker. - `TRANSIENT` Delivered messages are not logged. The broker is responsible for the implementation of the recordable storage mechanism for persistent messages. The impact of this feature on performance depends on the AMQP server. ##### Request Broker Confirm Parameter If the broker provides no confirmation, setting this parameter determines whether the operation fails. Using this parameter adds one extra communication between the broker and the client per message published. ## See Also - [Configure Property Placeholders](https://docs.mulesoft.com/mule-runtime/4.6/mule-app-properties-to-configure) - [Getting Started with the Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) - [SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection) - [Finding bottlenecks with RabbitMQ 3.3](https://www.rabbitmq.com/blog/2014/04/14/finding-bottlenecks-with-rabbitmq-3-3/) --- product: Mule Runtime version: 4.9 --- # App Design That Maximizes Process Performance > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you design your applications, consider the following best practices for enhancing processing performance. These practices include guidelines on choosing a Mule runtime engine (Mule) version, avoiding certain app design issues, and specific settings for using Mule components and connectors. ## Mule Runtime Engine Version Before you start tuning your application, review the following Mule version recommendations: - Use the latest Mule version to create and run the application. - Update your application dependencies to the latest version so you take advantage of the recent performance improvements and bug fixes. - Update to the latest version of the Mule patch whenever possible. - When developing and testing an application, use the same Mule version as used to deploy that application in your environments. ## Tips to Design for Enhanced Processing Performance As you design your apps, consider the following recommendations to increase performance: - Instead of repeatedly using the Java module to reuse code such as Java libraries, create an SDK module with operations that wrap Java invocations. - Use DataWeave to transform or enrich data, and create payloads instead of custom scripting code such as Java and Groovy. - Avoid sequences of `set-variable/set-payload` components such as in the following example: ```xml ``` Instead, combine them into a single `ee:transform` operation that avoids generating a new event for each component: ```xml ``` - Avoid using store transient values in `set-variable`, as shown in the following example: ```xml ``` Instead, move these values into components that need them: ```xml ``` - Avoid creating property resolvers, which require using DataWeave for every event and thereby increase process overhead: ```xml ``` Instead, place DataWeave logic in a property placeholder and use a static flow reference: ```xml ``` ## Avoid Recursive Flow References Using `flow-ref` to create recursive patterns (a flow that calls itself, or mutual recursion between flows) is an antipattern that can lead to resource exhaustion and should be replaced with iterative constructs. ### Why Recursion Is Problematic The Mule runtime maintains a flow call stack for each event being processed. Each `flow-ref` invocation adds an entry to this stack. When the stack depth limit is exceeded, the runtime raises a `CRITICAL` error that can’t be handled by error handlers. Additionally, extremely long flows with many processors generate deeply nested internal execution chains. When these flows are combined with recursive patterns or very deep call chains, the accumulated nesting can exhaust the JVM thread stack and produce a `StackOverflowError` or `VirtualMachineError`, which leaves the runtime in an inconsistent state (see [What Happens After a FATAL\_JVM\_ERROR](https://docs.mulesoft.com/mule-runtime/4.9/mule-error-concept#fatal_jvm_errors)). ### Antipattern: Recursive Flow-Ref This example is an antipattern because it creates a recursive pattern by calling the same flow repeatedly. ```xml ``` ### Recommended Alternatives
Use CaseRecommended Pattern

Process each item in a collection

Use <foreach> or <parallel-foreach> scope.

Process items in large datasets

Use <batch:job> for batch processing.

Retry an operation

Use <until-successful> with maxRetries.

Poll until a condition is met

Use a source-based polling trigger (for example, a Scheduler with a watermark).

Paginated API calls

Use connector-native pagination or a <foreach> over page numbers.

Complex iterative logic that can’t be expressed using built-in scopes

Implement a custom router by using the Mule SDK that encapsulates the iteration logic in Java, avoiding deep nesting in the Mule execution chain.

### Example: Replace Recursion with For Each This example shows how to replace recursion with a For Each scope. ```xml ``` ### Keep Flows Short Beyond avoiding recursion, keep individual flows at a reasonable length. Flows with hundreds of processors generate deep internal execution chains. If a flow grows too large, split it into smaller flows and invoke the flows with `flow-ref`. Unlike subflows, which are inlined at execution time and don’t reduce internal nesting, separate flows introduce independent execution chains and reset internal nesting depth. This helps prevent stack overflow conditions while improving readability and maintainability. ## Components and Connectors Best Practices When designing your apps using Mule components and connectors, consider the following recommendations to enhance the performance. ### APIkit To improve performance, disable APIkit validations. If payload validations are required, APIkit validates input requests against API specification. ### DataWeave When using DataWeave, consider the following ways to improve performance: - If payloads are large, include `indent=false` to improve client parsing and reduce response size. - Define `content-type` to avoid verbose messages in the log. - Use inline DataWeave scripts during development and then move them to an external file to have a clean XML and reusable scripts. - Do not log complex DataWeave expressions with every request. - Avoid patterns of iterating over a collection and then transforming each individual item: ```xml { (upper(key)): value } ]]> ... ``` Instead, transform the entire collection and iterate later: ```xml { book: item mapObject (value, key) -> { (upper(key)): value } } ]]> ... ``` ### Validator Use Validator Module instead of throwing exceptions with Groovy Scripts. ### HTTP and HTTPS For HTTP and HTTPS, consider the following recommendations: - Use the authentication mechanisms provided by Anypoint Connector for HTTP (HTTP Connector) instead using manual authentications such as manually generating the Basic auth header with a DataWeave expression. - If HTTPS is required, use the HTTPS Listener with a TLS Context reference, configuring the keystore with key-pair values generated with Keytool. You can avoid HTTPS configuration if the SSL can also be terminated at the Load Balancer level when using a dedicated load balancer in CloudHub or if there is an on-premises load balancer for hybrid scenarios: ```xml ``` ### Database Use parameterized queries. If you must use dynamic queries, remember to validate inputs first. Using dynamic queries could cause SQL-Injection vulnerability. ### File Connector Instead of using a transform component for the transformation in the write operation, use a DataWeave expression. This avoids message payload changes that occur after the write operation, as shown in the following example: ```xml #[%dw 2.0 output application/csv --- payload.customers.email ] ``` Use the recursive parameter to list files and folders within subfolders: ```xml ``` ### Web Service Consumer Connector To import WSDLs including all references (XSDs) in your project, use Anypoint Connector for Web Service Consumer (Web Service Consumer Connector) and point the configuration to the local WSDL. ### AMQP Connector Because the server constrains the performance and configuration of Anypoint Connector for AMQP (AMQP Connector), when you investigate performance issues, explore the server-side configuration to determine if consume or publish parameters have an impact on performance. #### Consume Parameters Review consume parameters that can have an impact on performance. ##### Number of Consumers Setting the number of consumers for an AMQP configuration and the Listener source determines how many consumers are spawned by the source and receive AMQP messages concurrently, as each consumer creates and uses a different channel. Message throughput depends on the number of consumers, becoming greater as the number of consumers increases. However, throughput is also affected by the performance characteristics of the flow. ##### ACK Mode Parameter ACK mode determines the acknowledgment mode to use when consuming from the AMQP broker. You set acknowledgment mode (ACK) at the configuration level (using the **Consumer** tab), but Listener and consume operations can override this mode. There are three acknowledgment modes: - `AUTO` Use Automatic to acknowledge a received message automatically only if the flow execution finishes successfully. - `MANUAL` Use Manual if you want the app logic to control message acknowledgment. - `IMMEDIATE` Use Immediate when you want to acknowledge messages as your app consumes them, before processing them. Note that if a transaction is opened in the channel, the ACK mode parameter is overruled and the commit automatically process the message acknowledgment and the rollback automatically process the recovery. ##### Quality of Service Tab You set QoS parameters at the configuration level (using the **Quality of Service** tab), with 0 representing an unlimited value. A Listener operation can override this setting. These are the parameters: - Prefetch Size Defines a prefetch size window. The broker sends as many messages as possible without exceeding the prefetch size window in octets (bytes). - Prefetch Count Specifies a global prefetch window in terms of the maximum number of whole messages. You can use this parameter in combination with the `prefetch-size` parameter to send a message in advance only it both prefetch windows sizes allow it. ##### ACK Mode and Prefetch The acknowledgment mode and QoS prefetch value that you choose have a significant effect on consumer throughput. In general, increasing the prefetch value and choosing Immediate acknowledgment mode yield the best possible rate of delivery. However, with both choices the number of delivered but not yet processed messages also increases, thereby increasing consumer RAM consumption Automatic acknowledgement mode or Manual acknowledgment mode with unlimited prefetch should be used with care. Consumption of a lot of messages without acknowledgement leads to increased memory consumption on the broker node. Finding a suitable prefetch value is a matter of trial and error and can vary from workload to workload. #### Publish Parameters Set the following parameters at the configuration level, using the **Publisher** tab. Publish and Publish-consume operations can override these parameters. Depending on your use case, you might need to enable only one of these parameters. ##### Delivery Mode Parameter Setting this parameter determines the delivery mode used to publish to the AMQP broker. Possible parameters values are: - `PERSISTENT` Delivered messages to durable queues are logged to disk on the broker. - `TRANSIENT` Delivered messages are not logged. The broker is responsible for the implementation of the recordable storage mechanism for persistent messages. The impact of this feature on performance depends on the AMQP server. ##### Request Broker Confirm Parameter If the broker provides no confirmation, setting this parameter determines whether the operation fails. Using this parameter adds one extra communication between the broker and the client per message published. ## See Also - [Configure Property Placeholders](https://docs.mulesoft.com/mule-runtime/4.9/mule-app-properties-to-configure) - [Getting Started with the Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) - [SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection) - [Finding bottlenecks with RabbitMQ 3.3](https://www.rabbitmq.com/blog/2014/04/14/finding-bottlenecks-with-rabbitmq-3-3/) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # App Design That Maximizes Process Performance > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you design your applications, consider the following best practices for enhancing processing performance. These practices include guidelines on choosing a Mule runtime engine (Mule) version, avoiding certain app design issues, and specific settings for using Mule components and connectors. ## Mule Runtime Engine Version Before you start tuning your application, review the following Mule version recommendations: - Use the latest Mule version to create and run the application. - Update your application dependencies to the latest version so you take advantage of the recent performance improvements and bug fixes. - Update to the latest version of the Mule patch whenever possible. - When developing and testing an application, use the same Mule version as used to deploy that application in your environments. ## Tips to Design for Enhanced Processing Performance As you design your apps, consider the following recommendations to increase performance: - Instead of repeatedly using the Java module to reuse code such as Java libraries, create an SDK module with operations that wrap Java invocations. - Use DataWeave to transform or enrich data, and create payloads instead of custom scripting code such as Java and Groovy. - Avoid sequences of `set-variable/set-payload` components such as in the following example: ```xml ``` Instead, combine them into a single `ee:transform` operation that avoids generating a new event for each component: ```xml ``` - Avoid using store transient values in `set-variable`, as shown in the following example: ```xml ``` Instead, move these values into components that need them: ```xml ``` - Avoid creating property resolvers, which require using DataWeave for every event and thereby increase process overhead: ```xml ``` Instead, place DataWeave logic in a property placeholder and use a static flow reference: ```xml ``` ## Avoid Recursive Flow References Using `flow-ref` to create recursive patterns (a flow that calls itself, or mutual recursion between flows) is an antipattern that can lead to resource exhaustion and should be replaced with iterative constructs. ### Why Recursion Is Problematic The Mule runtime maintains a flow call stack for each event being processed. Each `flow-ref` invocation adds an entry to this stack. When the stack depth limit is exceeded, the runtime raises a `CRITICAL` error that can’t be handled by error handlers. Additionally, extremely long flows with many processors generate deeply nested internal execution chains. When these flows are combined with recursive patterns or very deep call chains, the accumulated nesting can exhaust the JVM thread stack and produce a `StackOverflowError` or `VirtualMachineError`, which leaves the runtime in an inconsistent state (see [What Happens After a FATAL\_JVM\_ERROR](https://docs.mulesoft.com/mule-runtime/latest/mule-error-concept#fatal_jvm_errors)). ### Antipattern: Recursive Flow-Ref This example is an antipattern because it creates a recursive pattern by calling the same flow repeatedly. ```xml ``` ### Recommended Alternatives
Use CaseRecommended Pattern

Process each item in a collection

Use <foreach> or <parallel-foreach> scope.

Process items in large datasets

Use <batch:job> for batch processing.

Retry an operation

Use <until-successful> with maxRetries.

Poll until a condition is met

Use a source-based polling trigger (for example, a Scheduler with a watermark).

Paginated API calls

Use connector-native pagination or a <foreach> over page numbers.

Complex iterative logic that can’t be expressed using built-in scopes

Implement a custom router by using the Mule SDK that encapsulates the iteration logic in Java, avoiding deep nesting in the Mule execution chain.

### Example: Replace Recursion with For Each This example shows how to replace recursion with a For Each scope. ```xml ``` ### Keep Flows Short Beyond avoiding recursion, keep individual flows at a reasonable length. Flows with hundreds of processors generate deep internal execution chains. If a flow grows too large, split it into smaller flows and invoke the flows with `flow-ref`. Unlike subflows, which are inlined at execution time and don’t reduce internal nesting, separate flows introduce independent execution chains and reset internal nesting depth. This helps prevent stack overflow conditions while improving readability and maintainability. ## Components and Connectors Best Practices When designing your apps using Mule components and connectors, consider the following recommendations to enhance the performance. ### APIkit To improve performance, disable APIkit validations. If payload validations are required, APIkit validates input requests against API specification. ### DataWeave When using DataWeave, consider the following ways to improve performance: - If payloads are large, include `indent=false` to improve client parsing and reduce response size. - Define `content-type` to avoid verbose messages in the log. - Use inline DataWeave scripts during development and then move them to an external file to have a clean XML and reusable scripts. - Do not log complex DataWeave expressions with every request. - Avoid patterns of iterating over a collection and then transforming each individual item: ```xml { (upper(key)): value } ]]> ... ``` Instead, transform the entire collection and iterate later: ```xml { book: item mapObject (value, key) -> { (upper(key)): value } } ]]> ... ``` ### Validator Use Validator Module instead of throwing exceptions with Groovy Scripts. ### HTTP and HTTPS For HTTP and HTTPS, consider the following recommendations: - Use the authentication mechanisms provided by Anypoint Connector for HTTP (HTTP Connector) instead using manual authentications such as manually generating the Basic auth header with a DataWeave expression. - If HTTPS is required, use the HTTPS Listener with a TLS Context reference, configuring the keystore with key-pair values generated with Keytool. You can avoid HTTPS configuration if the SSL can also be terminated at the Load Balancer level when using a dedicated load balancer in CloudHub or if there is an on-premises load balancer for hybrid scenarios: ```xml ``` ### Database Use parameterized queries. If you must use dynamic queries, remember to validate inputs first. Using dynamic queries could cause SQL-Injection vulnerability. ### File Connector Instead of using a transform component for the transformation in the write operation, use a DataWeave expression. This avoids message payload changes that occur after the write operation, as shown in the following example: ```xml #[%dw 2.0 output application/csv --- payload.customers.email ] ``` Use the recursive parameter to list files and folders within subfolders: ```xml ``` ### Web Service Consumer Connector To import WSDLs including all references (XSDs) in your project, use Anypoint Connector for Web Service Consumer (Web Service Consumer Connector) and point the configuration to the local WSDL. ### AMQP Connector Because the server constrains the performance and configuration of Anypoint Connector for AMQP (AMQP Connector), when you investigate performance issues, explore the server-side configuration to determine if consume or publish parameters have an impact on performance. #### Consume Parameters Review consume parameters that can have an impact on performance. ##### Number of Consumers Setting the number of consumers for an AMQP configuration and the Listener source determines how many consumers are spawned by the source and receive AMQP messages concurrently, as each consumer creates and uses a different channel. Message throughput depends on the number of consumers, becoming greater as the number of consumers increases. However, throughput is also affected by the performance characteristics of the flow. ##### ACK Mode Parameter ACK mode determines the acknowledgment mode to use when consuming from the AMQP broker. You set acknowledgment mode (ACK) at the configuration level (using the **Consumer** tab), but Listener and consume operations can override this mode. There are three acknowledgment modes: - `AUTO` Use Automatic to acknowledge a received message automatically only if the flow execution finishes successfully. - `MANUAL` Use Manual if you want the app logic to control message acknowledgment. - `IMMEDIATE` Use Immediate when you want to acknowledge messages as your app consumes them, before processing them. Note that if a transaction is opened in the channel, the ACK mode parameter is overruled and the commit automatically process the message acknowledgment and the rollback automatically process the recovery. ##### Quality of Service Tab You set QoS parameters at the configuration level (using the **Quality of Service** tab), with 0 representing an unlimited value. A Listener operation can override this setting. These are the parameters: - Prefetch Size Defines a prefetch size window. The broker sends as many messages as possible without exceeding the prefetch size window in octets (bytes). - Prefetch Count Specifies a global prefetch window in terms of the maximum number of whole messages. You can use this parameter in combination with the `prefetch-size` parameter to send a message in advance only it both prefetch windows sizes allow it. ##### ACK Mode and Prefetch The acknowledgment mode and QoS prefetch value that you choose have a significant effect on consumer throughput. In general, increasing the prefetch value and choosing Immediate acknowledgment mode yield the best possible rate of delivery. However, with both choices the number of delivered but not yet processed messages also increases, thereby increasing consumer RAM consumption Automatic acknowledgement mode or Manual acknowledgment mode with unlimited prefetch should be used with care. Consumption of a lot of messages without acknowledgement leads to increased memory consumption on the broker node. Finding a suitable prefetch value is a matter of trial and error and can vary from workload to workload. #### Publish Parameters Set the following parameters at the configuration level, using the **Publisher** tab. Publish and Publish-consume operations can override these parameters. Depending on your use case, you might need to enable only one of these parameters. ##### Delivery Mode Parameter Setting this parameter determines the delivery mode used to publish to the AMQP broker. Possible parameters values are: - `PERSISTENT` Delivered messages to durable queues are logged to disk on the broker. - `TRANSIENT` Delivered messages are not logged. The broker is responsible for the implementation of the recordable storage mechanism for persistent messages. The impact of this feature on performance depends on the AMQP server. ##### Request Broker Confirm Parameter If the broker provides no confirmation, setting this parameter determines whether the operation fails. Using this parameter adds one extra communication between the broker and the client per message published. ## See Also - [Configure Property Placeholders](https://docs.mulesoft.com/mule-runtime/latest/mule-app-properties-to-configure) - [Getting Started with the Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) - [SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection) - [Finding bottlenecks with RabbitMQ 3.3](https://www.rabbitmq.com/blog/2014/04/14/finding-bottlenecks-with-rabbitmq-3-3/) --- product: Mule Runtime version: 4.12 --- # Application Descriptor Reference (mule-artifact.json) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Every Mule application, domain, and policy includes an application descriptor file, `mule-artifact.json`, at the root of the artifact. This file declares metadata that the Mule runtime engine uses to load, validate, and run the artifact, independent of the XML configuration described in [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-configuration). This page documents the fields of `mule-artifact.json` for a Mule application. Anypoint Studio and Anypoint Code Builder generate and maintain this file automatically. You typically read or hand-edit it only when troubleshooting a deployment issue. ## Example Example `mule-artifact.json` file for an application ```json { "name": "retail-api", "minMuleVersion": "4.9.0", "requiredProduct": "MULE_EE", "configs": [ "http-api.xml", "jms-messaging-api.xml", "monitoring-tools.xml", "core-functionality.xml" ], "redeploymentEnabled": true, "secureProperties": ["secure.password"], "supportedJavaVersions": ["17"], "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [] } }, "bundleDescriptorLoader": { "id": "mule", "attributes": {} } } ``` ## Fields
FieldRequiredDescription

name

Yes

The name of the artifact.

minMuleVersion

Yes

The minimum Mule runtime feature set that the artifact requires, expressed as a full major.minor.patch version (for example 4.9.0). See Understanding minMuleVersion for what value to use and how the runtime and other tools check it.

requiredProduct

Yes

The target product for the artifact. MULE for Mule Kernel (CE) or MULE_EE for Mule runtime EE.

classLoaderModelLoaderDescriptor

Yes

Describes how to build the class loader for the artifact. Contains an id (typically mule) and an attributes map, for example exportedPackages, exportedResources, privilegedExportedPackages, and privilegedArtifactIds.

bundleDescriptorLoader

Yes

Describes how to resolve the artifact’s bundle descriptor (its Maven coordinates). Contains an id (typically mule) and an attributes map.

configs

No

The list of configuration XML files that compose the artifact. See Declaring Multiple Configurations.

redeploymentEnabled

No

Whether the artifact can be hot-redeployed. Defaults to true.

secureProperties

No

A list of configuration property names whose values are masked wherever the runtime would otherwise expose configuration (for example, in logs).

supportedJavaVersions

No

The JDK major versions that the artifact supports (for example, ["17", "21"]).

logConfigFile

No

The path, relative to the artifact root, to a custom Log4j2 configuration file for the artifact.

domain

No, applications only

The name of the Mule domain that this application belongs to. See Mule Domains.

## See Also - [Feature Flagging Mechanism](https://docs.mulesoft.com/mule-runtime/4.12/feature-flagging) - [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-configuration) - [Packaging Applications](https://docs.mulesoft.com/mule-runtime/4.12/mule-app-dev) --- product: Mule Runtime version: 4.9 --- # Application Descriptor Reference (mule-artifact.json) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Every Mule application, domain, and policy includes an application descriptor file, `mule-artifact.json`, at the root of the artifact. This file declares metadata that the Mule runtime engine uses to load, validate, and run the artifact, independent of the XML configuration described in [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-configuration). This page documents the fields of `mule-artifact.json` for a Mule application. Anypoint Studio and Anypoint Code Builder generate and maintain this file automatically. You typically read or hand-edit it only when troubleshooting a deployment issue. ## Example Example `mule-artifact.json` file for an application ```json { "name": "retail-api", "minMuleVersion": "4.9.0", "requiredProduct": "MULE_EE", "configs": [ "http-api.xml", "jms-messaging-api.xml", "monitoring-tools.xml", "core-functionality.xml" ], "redeploymentEnabled": true, "secureProperties": ["secure.password"], "supportedJavaVersions": ["17"], "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [] } }, "bundleDescriptorLoader": { "id": "mule", "attributes": {} } } ``` ## Fields
FieldRequiredDescription

name

Yes

The name of the artifact.

minMuleVersion

Yes

The minimum Mule runtime feature set that the artifact requires, expressed as a full major.minor.patch version (for example 4.9.0). See Understanding minMuleVersion for what value to use and how the runtime and other tools check it.

requiredProduct

Yes

The target product for the artifact. MULE for Mule Kernel (CE) or MULE_EE for Mule runtime EE.

classLoaderModelLoaderDescriptor

Yes

Describes how to build the class loader for the artifact. Contains an id (typically mule) and an attributes map, for example exportedPackages, exportedResources, privilegedExportedPackages, and privilegedArtifactIds.

bundleDescriptorLoader

Yes

Describes how to resolve the artifact’s bundle descriptor (its Maven coordinates). Contains an id (typically mule) and an attributes map.

configs

No

The list of configuration XML files that compose the artifact. See Declaring Multiple Configurations.

redeploymentEnabled

No

Whether the artifact can be hot-redeployed. Defaults to true.

secureProperties

No

A list of configuration property names whose values are masked wherever the runtime would otherwise expose configuration (for example, in logs).

supportedJavaVersions

No

The JDK major versions that the artifact supports (for example, ["17", "21"]).

logConfigFile

No

The path, relative to the artifact root, to a custom Log4j2 configuration file for the artifact.

domain

No, applications only

The name of the Mule domain that this application belongs to. See Mule Domains.

## See Also - [Feature Flagging Mechanism](https://docs.mulesoft.com/mule-runtime/4.9/feature-flagging) - [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-configuration) - [Packaging Applications](https://docs.mulesoft.com/mule-runtime/4.9/mule-app-dev) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Application Descriptor Reference (mule-artifact.json) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Every Mule application, domain, and policy includes an application descriptor file, `mule-artifact.json`, at the root of the artifact. This file declares metadata that the Mule runtime engine uses to load, validate, and run the artifact, independent of the XML configuration described in [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/latest/about-mule-configuration). This page documents the fields of `mule-artifact.json` for a Mule application. Anypoint Studio and Anypoint Code Builder generate and maintain this file automatically. You typically read or hand-edit it only when troubleshooting a deployment issue. ## Example Example `mule-artifact.json` file for an application ```json { "name": "retail-api", "minMuleVersion": "4.9.0", "requiredProduct": "MULE_EE", "configs": [ "http-api.xml", "jms-messaging-api.xml", "monitoring-tools.xml", "core-functionality.xml" ], "redeploymentEnabled": true, "secureProperties": ["secure.password"], "supportedJavaVersions": ["17"], "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [] } }, "bundleDescriptorLoader": { "id": "mule", "attributes": {} } } ``` ## Fields
FieldRequiredDescription

name

Yes

The name of the artifact.

minMuleVersion

Yes

The minimum Mule runtime feature set that the artifact requires, expressed as a full major.minor.patch version (for example 4.9.0). See Understanding minMuleVersion for what value to use and how the runtime and other tools check it.

requiredProduct

Yes

The target product for the artifact. MULE for Mule Kernel (CE) or MULE_EE for Mule runtime EE.

classLoaderModelLoaderDescriptor

Yes

Describes how to build the class loader for the artifact. Contains an id (typically mule) and an attributes map, for example exportedPackages, exportedResources, privilegedExportedPackages, and privilegedArtifactIds.

bundleDescriptorLoader

Yes

Describes how to resolve the artifact’s bundle descriptor (its Maven coordinates). Contains an id (typically mule) and an attributes map.

configs

No

The list of configuration XML files that compose the artifact. See Declaring Multiple Configurations.

redeploymentEnabled

No

Whether the artifact can be hot-redeployed. Defaults to true.

secureProperties

No

A list of configuration property names whose values are masked wherever the runtime would otherwise expose configuration (for example, in logs).

supportedJavaVersions

No

The JDK major versions that the artifact supports (for example, ["17", "21"]).

logConfigFile

No

The path, relative to the artifact root, to a custom Log4j2 configuration file for the artifact.

domain

No, applications only

The name of the Mule domain that this application belongs to. See Mule Domains.

## See Also - [Feature Flagging Mechanism](https://docs.mulesoft.com/mule-runtime/latest/feature-flagging) - [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/latest/about-mule-configuration) - [Packaging Applications](https://docs.mulesoft.com/mule-runtime/latest/mule-app-dev) --- product: Mule Runtime version: 4.11 keywords: Async, scopes, studio, anypoint --- # Async Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Async scope is a branch processing block that executes simultaneously with the main flow. The main flow continues to execute while it initiates and processes the Async scope. The flow does not have to pause until the last message processor embedded in the asynchronous flow has completed its task. Async can be useful for executing time-consuming operations that do not require you to send a response back to the initiating flow (such as printing a file or connecting to a mail server). To facilitate simultaneous branch processing, the Async scope sends one copy of the message it has received to the first embedded message processor in its own processing block. At the same time, it sends another copy of the message to the next message processor in the main flow. ![An embedded asynchronous processing block within a scope](/mulesoft/current/en-us/mule-runtime/4.11/_images/async-scope-schematic.png) Because the Async scope is executed in a "fire and forget" manner, the result of the processing within the scope is not available in the main flow. ## Async Configuration Async scopes are configurable.
FieldDescription

Display Name (name)

Name for the Async scope.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that the scope can process. By default, the container thread pool determines the maximum number of threads to use to optimize the performance when processing messages. When the scope is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the scope to process requests one at a time.

See Back-Pressure Management for details about Mule behavior after reaching the maximum concurrency value.

## Async Scopes versus Subflows Unlike a subflow, an Async scope: - Does not inherit the exception strategy of the main flow. To handle errors in an Async scope, use the Try scope. - Processes messages asynchronously. - Does not pass data back to the main flow. - Exists inline with the main flow thread. - Is not called by a Flow Reference component. - Is not reusable Note that even though the Async scope receives a copy of the Mule message, the payload is not copied. The same payload objects are referenced by both Mule messages: One that continues down the original flow, and the one processed by the Async scope. In other words, if the payload of your message is a mutable object (for example, a bean with different fields in it) and a message processor in your Async scope changes the value of one of the fields, the message processors outside of the Async scope see the changed values. ## Example Async Scope Configuration The following XML fragment shows an example configuration of an Async scope inside an application flow. The Async scope contains a `file:read` operation that executes asynchronously once triggered, while the application continues processing the next operation in the flow, `http:request`: ```xml ... ... ``` ## See Also - [Core Components](https://docs.mulesoft.com/mule-runtime/4.11/about-components) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.11/transaction-management#tx_scopes_routers) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.11/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.12 keywords: Async, scopes, studio, anypoint --- # Async Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Async scope is a branch processing block that executes simultaneously with the main flow. The main flow continues to execute while it initiates and processes the Async scope. The flow does not have to pause until the last message processor embedded in the asynchronous flow has completed its task. Async can be useful for executing time-consuming operations that do not require you to send a response back to the initiating flow (such as printing a file or connecting to a mail server). To facilitate simultaneous branch processing, the Async scope sends one copy of the message it has received to the first embedded message processor in its own processing block. At the same time, it sends another copy of the message to the next message processor in the main flow. ![An embedded asynchronous processing block within a scope](/mulesoft/current/en-us/mule-runtime/4.12/_images/async-scope-schematic.png) Because the Async scope is executed in a "fire and forget" manner, the result of the processing within the scope is not available in the main flow. ## Async Configuration Async scopes are configurable.
FieldDescription

Display Name (name)

Name for the Async scope.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that the scope can process. By default, the container thread pool determines the maximum number of threads to use to optimize the performance when processing messages. When the scope is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the scope to process requests one at a time.

See Back-Pressure Management for details about Mule behavior after reaching the maximum concurrency value.

## Async Scopes versus Subflows Unlike a subflow, an Async scope: - Does not inherit the exception strategy of the main flow. To handle errors in an Async scope, use the Try scope. - Processes messages asynchronously. - Does not pass data back to the main flow. - Exists inline with the main flow thread. - Is not called by a Flow Reference component. - Is not reusable Note that even though the Async scope receives a copy of the Mule message, the payload is not copied. The same payload objects are referenced by both Mule messages: One that continues down the original flow, and the one processed by the Async scope. In other words, if the payload of your message is a mutable object (for example, a bean with different fields in it) and a message processor in your Async scope changes the value of one of the fields, the message processors outside of the Async scope see the changed values. ## Example Async Scope Configuration The following XML fragment shows an example configuration of an Async scope inside an application flow. The Async scope contains a `file:read` operation that executes asynchronously once triggered, while the application continues processing the next operation in the flow, `http:request`: ```xml ... ... ``` ## See Also - [Core Components](https://docs.mulesoft.com/mule-runtime/4.12/about-components) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.12/transaction-management#tx_scopes_routers) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.12/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.3 keywords: Async, scopes, studio, anypoint --- # Async Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Async scope is a branch processing block that executes simultaneously with the main flow. The main flow continues to execute while it initiates and processes the Async scope. The flow does not have to pause until the last message processor embedded in the asynchronous flow has completed its task. Async can be useful for executing time-consuming operations that do not require you to send a response back to the initiating flow (such as printing a file or connecting to a mail server). To facilitate simultaneous branch processing, the Async scope sends one copy of the message it has received to the first embedded message processor in its own processing block. At the same time, it sends another copy of the message to the next message processor in the main flow. ![Async+scope+schematic](/mulesoft/current/en-us/mule-runtime/4.3/_images/async-scope-schematic.png) Because the Async scope is executed in a "fire and forget" manner, the result of the processing within the scope is not available in the main flow. ## Async Configuration Async scopes are configurable.
FieldDescription

Display Name (name)

Name for the Async scope.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that the scope can process. By default, the container thread pool determines the maximum number of threads to use to optimize the performance when processing messages. When the scope is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the scope to process requests one at a time.

See Back-Pressure Management for details about Mule behavior after reaching the maximum concurrency value.

## Async Scopes versus Subflows Unlike a subflow, an Async scope: - Does not inherit the exception strategy of the main flow. To handle errors in an Async scope, use the Try scope. - Processes messages asynchronously. - Does not pass data back to the main flow. - Exists inline with the main flow thread. - Is not called by a Flow Reference component. - Is not reusable Note that even though the Async scope receives a copy of the Mule message, the payload is not copied. The same payload objects are referenced by both Mule messages: One that continues down the original flow, and the one processed by the Async scope. In other words, if the payload of your message is a mutable object (for example, a bean with different fields in it) and a message processor in your Async scope changes the value of one of the fields, the message processors outside of the Async scope see the changed values. ## Example Async Scope Configuration The following XML fragment shows an example configuration of an Async scope inside an application flow. The Async scope contains a `file:read` operation that executes asynchronously once triggered, while the application continues processing the next operation in the flow, `http:request`: ```xml ... ... ``` ## See Also - [Core Components](https://docs.mulesoft.com/mule-runtime/4.3/about-components) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.3/transaction-management#tx_scopes_routers) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.3/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.4 keywords: Async, scopes, studio, anypoint --- # Async Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Async scope is a branch processing block that executes simultaneously with the main flow. The main flow continues to execute while it initiates and processes the Async scope. The flow does not have to pause until the last message processor embedded in the asynchronous flow has completed its task. Async can be useful for executing time-consuming operations that do not require you to send a response back to the initiating flow (such as printing a file or connecting to a mail server). To facilitate simultaneous branch processing, the Async scope sends one copy of the message it has received to the first embedded message processor in its own processing block. At the same time, it sends another copy of the message to the next message processor in the main flow. ![Async+scope+schematic](/mulesoft/current/en-us/mule-runtime/4.4/_images/async-scope-schematic.png) Because the Async scope is executed in a "fire and forget" manner, the result of the processing within the scope is not available in the main flow. ## Async Configuration Async scopes are configurable.
FieldDescription

Display Name (name)

Name for the Async scope.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that the scope can process. By default, the container thread pool determines the maximum number of threads to use to optimize the performance when processing messages. When the scope is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the scope to process requests one at a time.

See Back-Pressure Management for details about Mule behavior after reaching the maximum concurrency value.

## Async Scopes versus Subflows Unlike a subflow, an Async scope: - Does not inherit the exception strategy of the main flow. To handle errors in an Async scope, use the Try scope. - Processes messages asynchronously. - Does not pass data back to the main flow. - Exists inline with the main flow thread. - Is not called by a Flow Reference component. - Is not reusable Note that even though the Async scope receives a copy of the Mule message, the payload is not copied. The same payload objects are referenced by both Mule messages: One that continues down the original flow, and the one processed by the Async scope. In other words, if the payload of your message is a mutable object (for example, a bean with different fields in it) and a message processor in your Async scope changes the value of one of the fields, the message processors outside of the Async scope see the changed values. ## Example Async Scope Configuration The following XML fragment shows an example configuration of an Async scope inside an application flow. The Async scope contains a `file:read` operation that executes asynchronously once triggered, while the application continues processing the next operation in the flow, `http:request`: ```xml ... ... ``` ## See Also - [Core Components](https://docs.mulesoft.com/mule-runtime/4.4/about-components) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.4/transaction-management#tx_scopes_routers) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.4/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.6 keywords: Async, scopes, studio, anypoint --- # Async Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Async scope is a branch processing block that executes simultaneously with the main flow. The main flow continues to execute while it initiates and processes the Async scope. The flow does not have to pause until the last message processor embedded in the asynchronous flow has completed its task. Async can be useful for executing time-consuming operations that do not require you to send a response back to the initiating flow (such as printing a file or connecting to a mail server). To facilitate simultaneous branch processing, the Async scope sends one copy of the message it has received to the first embedded message processor in its own processing block. At the same time, it sends another copy of the message to the next message processor in the main flow. ![Async+scope+schematic](/mulesoft/current/en-us/mule-runtime/4.6/_images/async-scope-schematic.png) Because the Async scope is executed in a "fire and forget" manner, the result of the processing within the scope is not available in the main flow. ## Async Configuration Async scopes are configurable.
FieldDescription

Display Name (name)

Name for the Async scope.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that the scope can process. By default, the container thread pool determines the maximum number of threads to use to optimize the performance when processing messages. When the scope is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the scope to process requests one at a time.

See Back-Pressure Management for details about Mule behavior after reaching the maximum concurrency value.

## Async Scopes versus Subflows Unlike a subflow, an Async scope: - Does not inherit the exception strategy of the main flow. To handle errors in an Async scope, use the Try scope. - Processes messages asynchronously. - Does not pass data back to the main flow. - Exists inline with the main flow thread. - Is not called by a Flow Reference component. - Is not reusable Note that even though the Async scope receives a copy of the Mule message, the payload is not copied. The same payload objects are referenced by both Mule messages: One that continues down the original flow, and the one processed by the Async scope. In other words, if the payload of your message is a mutable object (for example, a bean with different fields in it) and a message processor in your Async scope changes the value of one of the fields, the message processors outside of the Async scope see the changed values. ## Example Async Scope Configuration The following XML fragment shows an example configuration of an Async scope inside an application flow. The Async scope contains a `file:read` operation that executes asynchronously once triggered, while the application continues processing the next operation in the flow, `http:request`: ```xml ... ... ``` ## See Also - [Core Components](https://docs.mulesoft.com/mule-runtime/4.6/about-components) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.6/transaction-management#tx_scopes_routers) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.6/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.9 keywords: Async, scopes, studio, anypoint --- # Async Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Async scope is a branch processing block that executes simultaneously with the main flow. The main flow continues to execute while it initiates and processes the Async scope. The flow does not have to pause until the last message processor embedded in the asynchronous flow has completed its task. Async can be useful for executing time-consuming operations that do not require you to send a response back to the initiating flow (such as printing a file or connecting to a mail server). To facilitate simultaneous branch processing, the Async scope sends one copy of the message it has received to the first embedded message processor in its own processing block. At the same time, it sends another copy of the message to the next message processor in the main flow. ![An embedded asynchronous processing block within a scope](/mulesoft/current/en-us/mule-runtime/4.9/_images/async-scope-schematic.png) Because the Async scope is executed in a "fire and forget" manner, the result of the processing within the scope is not available in the main flow. ## Async Configuration Async scopes are configurable.
FieldDescription

Display Name (name)

Name for the Async scope.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that the scope can process. By default, the container thread pool determines the maximum number of threads to use to optimize the performance when processing messages. When the scope is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the scope to process requests one at a time.

See Back-Pressure Management for details about Mule behavior after reaching the maximum concurrency value.

## Async Scopes versus Subflows Unlike a subflow, an Async scope: - Does not inherit the exception strategy of the main flow. To handle errors in an Async scope, use the Try scope. - Processes messages asynchronously. - Does not pass data back to the main flow. - Exists inline with the main flow thread. - Is not called by a Flow Reference component. - Is not reusable Note that even though the Async scope receives a copy of the Mule message, the payload is not copied. The same payload objects are referenced by both Mule messages: One that continues down the original flow, and the one processed by the Async scope. In other words, if the payload of your message is a mutable object (for example, a bean with different fields in it) and a message processor in your Async scope changes the value of one of the fields, the message processors outside of the Async scope see the changed values. ## Example Async Scope Configuration The following XML fragment shows an example configuration of an Async scope inside an application flow. The Async scope contains a `file:read` operation that executes asynchronously once triggered, while the application continues processing the next operation in the flow, `http:request`: ```xml ... ... ``` ## See Also - [Core Components](https://docs.mulesoft.com/mule-runtime/4.9/about-components) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.9/transaction-management#tx_scopes_routers) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.9/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: Async, scopes, studio, anypoint --- # Async Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Async scope is a branch processing block that executes simultaneously with the main flow. The main flow continues to execute while it initiates and processes the Async scope. The flow does not have to pause until the last message processor embedded in the asynchronous flow has completed its task. Async can be useful for executing time-consuming operations that do not require you to send a response back to the initiating flow (such as printing a file or connecting to a mail server). To facilitate simultaneous branch processing, the Async scope sends one copy of the message it has received to the first embedded message processor in its own processing block. At the same time, it sends another copy of the message to the next message processor in the main flow. ![An embedded asynchronous processing block within a scope](/mulesoft/current/en-us/mule-runtime/latest/_images/async-scope-schematic.png) Because the Async scope is executed in a "fire and forget" manner, the result of the processing within the scope is not available in the main flow. ## Async Configuration Async scopes are configurable.
FieldDescription

Display Name (name)

Name for the Async scope.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that the scope can process. By default, the container thread pool determines the maximum number of threads to use to optimize the performance when processing messages. When the scope is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the scope to process requests one at a time.

See Back-Pressure Management for details about Mule behavior after reaching the maximum concurrency value.

## Async Scopes versus Subflows Unlike a subflow, an Async scope: - Does not inherit the exception strategy of the main flow. To handle errors in an Async scope, use the Try scope. - Processes messages asynchronously. - Does not pass data back to the main flow. - Exists inline with the main flow thread. - Is not called by a Flow Reference component. - Is not reusable Note that even though the Async scope receives a copy of the Mule message, the payload is not copied. The same payload objects are referenced by both Mule messages: One that continues down the original flow, and the one processed by the Async scope. In other words, if the payload of your message is a mutable object (for example, a bean with different fields in it) and a message processor in your Async scope changes the value of one of the fields, the message processors outside of the Async scope see the changed values. ## Example Async Scope Configuration The following XML fragment shows an example configuration of an Async scope inside an application flow. The Async scope contains a `file:read` operation that executes asynchronously once triggered, while the application continues processing the next operation in the flow, `http:request`: ```xml ... ... ``` ## See Also - [Core Components](https://docs.mulesoft.com/mule-runtime/latest/about-components) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/latest/transaction-management#tx_scopes_routers) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/latest/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.11 --- # Back-Pressure and MaxConcurrency > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Under heavy load, Mule runtime engine (Mule) might not immediately have the resources available to process a specific event. This issue might occur because all threads are busy and the current flow’s concurrency is exceeded. When this occurs, Mule logs the following message: `Flow 'flowName' is unable to accept new events at this time` This message is known as back-pressure. Mule back-pressure actions are specific to each connector’s source. When a producer component outputs information at a higher rate than a consumer component can process it, you can use the `maxConcurrency` parameter to set the maximum number of concurrent messages that a flow can process at any given time, whether the components are internal or external, flows or sources, and so on. Although Mule applies back-pressure on its own, the `maxConcurrency` parameter helps to control the flow performance, especially when a backend server may affect when having high concurrency. See how to set the parameter in the following example: ```xml ``` Similarly, you can limit the number of records that can be processed in a batch job by setting the `maxConcurrency` parameter as in the following example: ```xml ``` By default, the Flow and Async scopes do not set a `maxConcurrency` limit, but the Batch Job component limits concurrency to twice the number of available cores. The capacity of your system also limits concurrency. ## Components with Max Concurrency Settings The following [components](https://docs.mulesoft.com/mule-runtime/4.11/about-components) provide a max concurrency setting: - Flow scope - Scatter-Gather router - Async scope - Batch Job scope - Parallel For Each scope ## Recommendation Unless a lower concurrency is required to artificially trigger a back-pressure event, use the default settings, and do not change the max concurrency value. ## See also - [Execution Engine Threads and Concurrency](https://docs.mulesoft.com/mule-runtime/4.11/execution-engine) --- product: Mule Runtime version: 4.12 --- # Back-Pressure and MaxConcurrency > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Under heavy load, Mule runtime engine (Mule) might not immediately have the resources available to process a specific event. This issue might occur because all threads are busy and the current flow’s concurrency is exceeded. When this occurs, Mule logs the following message: `Flow 'flowName' is unable to accept new events at this time` This message is known as back-pressure. Mule back-pressure actions are specific to each connector’s source. When a producer component outputs information at a higher rate than a consumer component can process it, you can use the `maxConcurrency` parameter to set the maximum number of concurrent messages that a flow can process at any given time, whether the components are internal or external, flows or sources, and so on. Although Mule applies back-pressure on its own, the `maxConcurrency` parameter helps to control the flow performance, especially when a backend server may affect when having high concurrency. See how to set the parameter in the following example: ```xml ``` Similarly, you can limit the number of records that can be processed in a batch job by setting the `maxConcurrency` parameter as in the following example: ```xml ``` By default, the Flow and Async scopes do not set a `maxConcurrency` limit, but the Batch Job component limits concurrency to twice the number of available cores. The capacity of your system also limits concurrency. ## Components with Max Concurrency Settings The following [components](https://docs.mulesoft.com/mule-runtime/4.12/about-components) provide a max concurrency setting: - Flow scope - Scatter-Gather router - Async scope - Batch Job scope - Parallel For Each scope ## Recommendation Unless a lower concurrency is required to artificially trigger a back-pressure event, use the default settings, and do not change the max concurrency value. ## See also - [Execution Engine Threads and Concurrency](https://docs.mulesoft.com/mule-runtime/4.12/execution-engine) --- product: Mule Runtime version: 4.3 --- # Back-Pressure and MaxConcurrency > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Under heavy load, Mule runtime engine (Mule) might not immediately have the resources available to process a specific event. This issue might occur because all threads are busy and the current flow’s concurrency is exceeded. When this occurs, Mule logs the following message: `Flow 'flowName' is unable to accept new events at this time` This message is known as back-pressure. Mule back-pressure actions are specific to each connector’s source. When a producer component outputs information at a higher rate than a consumer component can process it, you can use the `maxConcurrency` parameter to set the maximum number of concurrent messages that a flow can process at any given time, whether the components are internal or external, flows or sources, and so on. Although Mule applies back-pressure on its own, the `maxConcurrency` parameter helps to control the flow performance, especially when a backend server may affect when having high concurrency. See how to set the parameter in the following example: ```xml ``` Similarly, you can limit the number of records that can be processed in a batch job by setting the `maxConcurrency` parameter as in the following example: ```xml ``` By default, the Flow and Async scopes do not set a `maxConcurrency` limit, but the Batch Job component limits concurrency to twice the number of available cores. The capacity of your system also limits concurrency. ## Components with Max Concurrency Settings The following [components](https://docs.mulesoft.com/mule-runtime/4.3/about-components) provide a max concurrency setting: - Flow scope - Scatter-Gather router - Async scope - Batch Job scope - Parallel For Each scope ## Recommendation Unless a lower concurrency is required to artificially trigger a back-pressure event, use the default settings, and do not change the max concurrency value. ## See also - [Execution Engine Threads and Concurrency](https://docs.mulesoft.com/mule-runtime/4.3/intro-engine) --- product: Mule Runtime version: 4.4 --- # Back-Pressure and MaxConcurrency > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Under heavy load, Mule runtime engine (Mule) might not immediately have the resources available to process a specific event. This issue might occur because all threads are busy and the current flow’s concurrency is exceeded. When this occurs, Mule logs the following message: `Flow 'flowName' is unable to accept new events at this time` This message is known as back-pressure. Mule back-pressure actions are specific to each connector’s source. When a producer component outputs information at a higher rate than a consumer component can process it, you can use the `maxConcurrency` parameter to set the maximum number of concurrent messages that a flow can process at any given time, whether the components are internal or external, flows or sources, and so on. Although Mule applies back-pressure on its own, the `maxConcurrency` parameter helps to control the flow performance, especially when a backend server may affect when having high concurrency. See how to set the parameter in the following example: ```xml ``` Similarly, you can limit the number of records that can be processed in a batch job by setting the `maxConcurrency` parameter as in the following example: ```xml ``` By default, the Flow and Async scopes do not set a `maxConcurrency` limit, but the Batch Job component limits concurrency to twice the number of available cores. The capacity of your system also limits concurrency. ## Components with Max Concurrency Settings The following [components](https://docs.mulesoft.com/mule-runtime/4.4/about-components) provide a max concurrency setting: - Flow scope - Scatter-Gather router - Async scope - Batch Job scope - Parallel For Each scope ## Recommendation Unless a lower concurrency is required to artificially trigger a back-pressure event, use the default settings, and do not change the max concurrency value. ## See also - [Execution Engine Threads and Concurrency](https://docs.mulesoft.com/mule-runtime/4.4/intro-engine) --- product: Mule Runtime version: 4.6 --- # Back-Pressure and MaxConcurrency > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Under heavy load, Mule runtime engine (Mule) might not immediately have the resources available to process a specific event. This issue might occur because all threads are busy and the current flow’s concurrency is exceeded. When this occurs, Mule logs the following message: `Flow 'flowName' is unable to accept new events at this time` This message is known as back-pressure. Mule back-pressure actions are specific to each connector’s source. When a producer component outputs information at a higher rate than a consumer component can process it, you can use the `maxConcurrency` parameter to set the maximum number of concurrent messages that a flow can process at any given time, whether the components are internal or external, flows or sources, and so on. Although Mule applies back-pressure on its own, the `maxConcurrency` parameter helps to control the flow performance, especially when a backend server may affect when having high concurrency. See how to set the parameter in the following example: ```xml ``` Similarly, you can limit the number of records that can be processed in a batch job by setting the `maxConcurrency` parameter as in the following example: ```xml ``` By default, the Flow and Async scopes do not set a `maxConcurrency` limit, but the Batch Job component limits concurrency to twice the number of available cores. The capacity of your system also limits concurrency. ## Components with Max Concurrency Settings The following [components](https://docs.mulesoft.com/mule-runtime/4.6/about-components) provide a max concurrency setting: - Flow scope - Scatter-Gather router - Async scope - Batch Job scope - Parallel For Each scope ## Recommendation Unless a lower concurrency is required to artificially trigger a back-pressure event, use the default settings, and do not change the max concurrency value. ## See also - [Execution Engine Threads and Concurrency](https://docs.mulesoft.com/mule-runtime/4.6/execution-engine) --- product: Mule Runtime version: 4.9 --- # Back-Pressure and MaxConcurrency > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Under heavy load, Mule runtime engine (Mule) might not immediately have the resources available to process a specific event. This issue might occur because all threads are busy and the current flow’s concurrency is exceeded. When this occurs, Mule logs the following message: `Flow 'flowName' is unable to accept new events at this time` This message is known as back-pressure. Mule back-pressure actions are specific to each connector’s source. When a producer component outputs information at a higher rate than a consumer component can process it, you can use the `maxConcurrency` parameter to set the maximum number of concurrent messages that a flow can process at any given time, whether the components are internal or external, flows or sources, and so on. Although Mule applies back-pressure on its own, the `maxConcurrency` parameter helps to control the flow performance, especially when a backend server may affect when having high concurrency. See how to set the parameter in the following example: ```xml ``` Similarly, you can limit the number of records that can be processed in a batch job by setting the `maxConcurrency` parameter as in the following example: ```xml ``` By default, the Flow and Async scopes do not set a `maxConcurrency` limit, but the Batch Job component limits concurrency to twice the number of available cores. The capacity of your system also limits concurrency. ## Components with Max Concurrency Settings The following [components](https://docs.mulesoft.com/mule-runtime/4.9/about-components) provide a max concurrency setting: - Flow scope - Scatter-Gather router - Async scope - Batch Job scope - Parallel For Each scope ## Recommendation Unless a lower concurrency is required to artificially trigger a back-pressure event, use the default settings, and do not change the max concurrency value. ## See also - [Execution Engine Threads and Concurrency](https://docs.mulesoft.com/mule-runtime/4.9/execution-engine) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Back-Pressure and MaxConcurrency > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Under heavy load, Mule runtime engine (Mule) might not immediately have the resources available to process a specific event. This issue might occur because all threads are busy and the current flow’s concurrency is exceeded. When this occurs, Mule logs the following message: `Flow 'flowName' is unable to accept new events at this time` This message is known as back-pressure. Mule back-pressure actions are specific to each connector’s source. When a producer component outputs information at a higher rate than a consumer component can process it, you can use the `maxConcurrency` parameter to set the maximum number of concurrent messages that a flow can process at any given time, whether the components are internal or external, flows or sources, and so on. Although Mule applies back-pressure on its own, the `maxConcurrency` parameter helps to control the flow performance, especially when a backend server may affect when having high concurrency. See how to set the parameter in the following example: ```xml ``` Similarly, you can limit the number of records that can be processed in a batch job by setting the `maxConcurrency` parameter as in the following example: ```xml ``` By default, the Flow and Async scopes do not set a `maxConcurrency` limit, but the Batch Job component limits concurrency to twice the number of available cores. The capacity of your system also limits concurrency. ## Components with Max Concurrency Settings The following [components](https://docs.mulesoft.com/mule-runtime/latest/about-components) provide a max concurrency setting: - Flow scope - Scatter-Gather router - Async scope - Batch Job scope - Parallel For Each scope ## Recommendation Unless a lower concurrency is required to artificially trigger a back-pressure event, use the default settings, and do not change the max concurrency value. ## See also - [Execution Engine Threads and Concurrency](https://docs.mulesoft.com/mule-runtime/latest/execution-engine) --- product: Mule Runtime version: 4.11 --- # Backend Server Response Time > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot performance issues, first determine whether flow performance is heavily constrained by the latency of the remote hosts to which the flow connects. Failure to acknowledge the performance overhead added to a flow by the underlying complexities of the communication between the application and a remote host might mislead your optimization efforts and result in negligible improvement. Therefore, it is important that, before you begin any optimization in the Mule app, you first characterize the backend servers' average latency and throughput to determine if this is what is limiting your application’s scalability or performance. Some of the factors to consider are: - Average size of the payload exchanged between the app and the remote host - Network latency because of the application and remote host physical location Check if these are in the same network, same geographical region, same country, or the other side of the world. - Remote host response time. The throughput and response time of your application can improve if the remote host is located within the same network boundaries as the application. However, if the remote host is outside of your application’s local network, you may experience an increased latency which will be directly proportional to the remote host response time, regardless of the payload size. Other factors that affect application throughput include external dependencies, concurrency, flow complexity, deployment characteristics, and machine configuration. --- product: Mule Runtime version: 4.12 --- # Backend Server Response Time > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot performance issues, first determine whether flow performance is heavily constrained by the latency of the remote hosts to which the flow connects. Failure to acknowledge the performance overhead added to a flow by the underlying complexities of the communication between the application and a remote host might mislead your optimization efforts and result in negligible improvement. Therefore, it is important that, before you begin any optimization in the Mule app, you first characterize the backend servers' average latency and throughput to determine if this is what is limiting your application’s scalability or performance. Some of the factors to consider are: - Average size of the payload exchanged between the app and the remote host - Network latency because of the application and remote host physical location Check if these are in the same network, same geographical region, same country, or the other side of the world. - Remote host response time. The throughput and response time of your application can improve if the remote host is located within the same network boundaries as the application. However, if the remote host is outside of your application’s local network, you may experience an increased latency which will be directly proportional to the remote host response time, regardless of the payload size. Other factors that affect application throughput include external dependencies, concurrency, flow complexity, deployment characteristics, and machine configuration. --- product: Mule Runtime version: 4.3 --- # Backend Server Response Time > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot performance issues, first determine whether flow performance is heavily constrained by the latency of the remote hosts to which the flow connects. Failure to acknowledge the performance overhead added to a flow by the underlying complexities of the communication between the application and a remote host might mislead your optimization efforts and result in negligible improvement. Therefore, it is important that, before you begin any optimization in the Mule app, you first characterize the backend servers' average latency and throughput to determine if this is what is limiting your application’s scalability or performance. Some of the factors to consider are: - Average size of the payload exchanged between the app and the remote host - Network latency because of the application and remote host physical location Check if these are in the same network, same geographical region, same country, or the other side of the world. - Remote host response time. The throughput and response time of your application can improve if the remote host is located within the same network boundaries as the application. However, if the remote host is outside of your application’s local network, you may experience an increased latency which will be directly proportional to the remote host response time, regardless of the payload size. Other factors that affect application throughput include external dependencies, concurrency, flow complexity, deployment characteristics, and machine configuration. --- product: Mule Runtime version: 4.4 --- # Backend Server Response Time > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot performance issues, first determine whether flow performance is heavily constrained by the latency of the remote hosts to which the flow connects. Failure to acknowledge the performance overhead added to a flow by the underlying complexities of the communication between the application and a remote host might mislead your optimization efforts and result in negligible improvement. Therefore, it is important that, before you begin any optimization in the Mule app, you first characterize the backend servers' average latency and throughput to determine if this is what is limiting your application’s scalability or performance. Some of the factors to consider are: - Average size of the payload exchanged between the app and the remote host - Network latency because of the application and remote host physical location Check if these are in the same network, same geographical region, same country, or the other side of the world. - Remote host response time. The throughput and response time of your application can improve if the remote host is located within the same network boundaries as the application. However, if the remote host is outside of your application’s local network, you may experience an increased latency which will be directly proportional to the remote host response time, regardless of the payload size. Other factors that affect application throughput include external dependencies, concurrency, flow complexity, deployment characteristics, and machine configuration. --- product: Mule Runtime version: 4.6 --- # Backend Server Response Time > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot performance issues, first determine whether flow performance is heavily constrained by the latency of the remote hosts to which the flow connects. Failure to acknowledge the performance overhead added to a flow by the underlying complexities of the communication between the application and a remote host might mislead your optimization efforts and result in negligible improvement. Therefore, it is important that, before you begin any optimization in the Mule app, you first characterize the backend servers' average latency and throughput to determine if this is what is limiting your application’s scalability or performance. Some of the factors to consider are: - Average size of the payload exchanged between the app and the remote host - Network latency because of the application and remote host physical location Check if these are in the same network, same geographical region, same country, or the other side of the world. - Remote host response time. The throughput and response time of your application can improve if the remote host is located within the same network boundaries as the application. However, if the remote host is outside of your application’s local network, you may experience an increased latency which will be directly proportional to the remote host response time, regardless of the payload size. Other factors that affect application throughput include external dependencies, concurrency, flow complexity, deployment characteristics, and machine configuration. --- product: Mule Runtime version: 4.9 --- # Backend Server Response Time > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot performance issues, first determine whether flow performance is heavily constrained by the latency of the remote hosts to which the flow connects. Failure to acknowledge the performance overhead added to a flow by the underlying complexities of the communication between the application and a remote host might mislead your optimization efforts and result in negligible improvement. Therefore, it is important that, before you begin any optimization in the Mule app, you first characterize the backend servers' average latency and throughput to determine if this is what is limiting your application’s scalability or performance. Some of the factors to consider are: - Average size of the payload exchanged between the app and the remote host - Network latency because of the application and remote host physical location Check if these are in the same network, same geographical region, same country, or the other side of the world. - Remote host response time. The throughput and response time of your application can improve if the remote host is located within the same network boundaries as the application. However, if the remote host is outside of your application’s local network, you may experience an increased latency which will be directly proportional to the remote host response time, regardless of the payload size. Other factors that affect application throughput include external dependencies, concurrency, flow complexity, deployment characteristics, and machine configuration. --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Backend Server Response Time > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot performance issues, first determine whether flow performance is heavily constrained by the latency of the remote hosts to which the flow connects. Failure to acknowledge the performance overhead added to a flow by the underlying complexities of the communication between the application and a remote host might mislead your optimization efforts and result in negligible improvement. Therefore, it is important that, before you begin any optimization in the Mule app, you first characterize the backend servers' average latency and throughput to determine if this is what is limiting your application’s scalability or performance. Some of the factors to consider are: - Average size of the payload exchanged between the app and the remote host - Network latency because of the application and remote host physical location Check if these are in the same network, same geographical region, same country, or the other side of the world. - Remote host response time. The throughput and response time of your application can improve if the remote host is located within the same network boundaries as the application. However, if the remote host is outside of your application’s local network, you may experience an increased latency which will be directly proportional to the remote host response time, regardless of the payload size. Other factors that affect application throughput include external dependencies, concurrency, flow complexity, deployment characteristics, and machine configuration. --- product: Mule Runtime version: 4.11 --- # Batch Component Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch components manage bulk processing of records with minimal adjustments to default component settings. They are highly configurable to meet specific processing and performance requirements. A Batch Job component must contain at least one Batch Step component. Optionally, each Batch Step component can contain a single Batch Aggregator component. The Mule flow in the following figure shows batch components. ![A flow showing batch processing components in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/batch-flow-generic-example.png) The Batch Job component splits the payload of the Mule message into records. Within the Batch Step and Batch Aggregator components, these records are available with the keyword `payload`, and Mule variables are also accessible through the `vars` keyword. However, Mule attributes are not accessible from within these components. Both components return `null` on `attributes`. This reference assumes that you are familiar with the [batch processing phases](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases) of a batch job instance. ## Batch Job Component () This component prepares its input for processing and outputs a report with results of that processing. Preparation takes place during the [Load and Dispatch](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases#phase_load_dispatch) phase of a batch job instance, and the report is available in the [On Complete](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases#phase_on_complete) phase. In Studio, you can set these properties in the component’s [General](#ref_batch_job_general_fields) and [History](#ref_batch_job_history_fields) tabs. ### Batch Job Properties The Batch Job component provides a number of configurable properties that determine how batch processing takes place. It also provides a way of storing the input payload in a target variable for use by subsequent components in the flow, which can be useful because the Batch Job component consumes the message payload. Anypoint Studio provides the following fields in the **General** tab: ![Batch job fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/batch-job-fields-studio.png) The following table describes each field and includes the XML attribute for the field.
Field NameXMLDescription

Name

name

Configurable name for a Batch Job component. The default name appends Batch_Job to the name of the application.

Max Failed Records

maxFailedRecords

Maximum number of records that can fail within a batch job instance before the execution of that instance stops. The default is 0. Use -1 for no limit. This setting takes precedence over any accept policy (acceptPolicy) or expression (acceptExpression) filter on a Batch Step component within the Batch Job component. When a batch job instance exceeds the maxFailedRecords value, the Batch Job component stops processing of the batch job instance in which the failure occurs, assigns the instance the status FAILED_PROCESS_RECORDS, and reports the number of failed records in the instance. When a batch job instance reaches this threshold, the console prints a message such as this one (edited for readability):

INFO  ... DefaultBatchEngine:
 instance '6d85c380-f332-11ec-bb5f-147ddaaf4f97' of job 'Batch_Job_in_Mule_Flow'
 has reached the max allowed number of failed records. Record will be added to
 failed list and the instance will be removed from execution pool.
...
INFO  ... DefaultBatchEngine:
 instance 6d85c380-f332-11ec-bb5f-147ddaaf4f97 of job Batch_Job_in_Mule_Flow
 has been stopped. Instance status is FAILED_PROCESS_RECORDS

Note that parallel processing within a batch job instance makes it possible for the number of errors to exceed the configured maximum because it is possible for multiple records fail at the same time.

Scheduling Strategy

schedulingStrategy

When a Batch Job component triggers repeatedly, more than one batch job instance can be ready to execute at the same time. The instances can run sequentially based on their creation timestamp (the default) or according to a round-robin algorithm that attempts to maximize the use of available resources. This setting is appropriate only for jobs that have no side effects or dependencies on other records because the order of processing is not guaranteed.

  • ORDERED_SQUENTIAL (default): With this setting, batch job instances execute one at a time in the order established by their creation timestamp. An instance created earlier executes before an instance created at a later time and date.

  • ROUND_ROBIN: With this setting, all batch job instances execute based on a round-robin algorithm that assigns available resources. Order of execution is not predetermined. Batch instances can execute in any order. This option is viable only if you are certain that no execution of an instance is capable of producing a side effect on an execution of another instance. Best practices:

    • To avoid potential updates to the same record in concurrently running batch job instances, do not use this strategy for data synchronization jobs. Using this strategy when synchronizing data makes it possible to return a result with an earlier, incorrect version of the data.

    • Use this strategy to parallelize execution of batch job instances if you are certain that no record depends on the processing of another record within the Batch Job component, such as a case in which your batch job retrieves only new records from a database.

Job Instance ID

jobInstanceId

Optional expression that provides a recognizable, unique name for the batch instance. To make the name unique, you must use a DataWeave expression, for example, #[jobInstanceId="#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}] within this field. If an expression returns the same value more than once, Mule throws an error with a message such as, Batch Job 'my-batch-job-example' already has an instance with id 'my-repeated-id'. The Batch Job component uses this value to create a new identifier each time the Mule flow reaches the Batch Job component. If you do not provide an ID, Mule automatically creates a UUID that serves as the identifier for each batch job instance.

Batch Block Size

blockSize

Number of records to process per record block. The default is 100 records per block. If fewer records are available for processing than the configured size, Mule sends a block of a smaller size to the record processors. Such a case can occur, for example, if there are 1010 records and the block size is 100 because the modulo is 10, not 0. The block size setting provides a way to tune performance, which is affected by the size of records in each block and the maxConcurrency setting.

Max Concurrency

maxConcurrency

Property that sets the maximum level of parallelism to allow when processing record blocks within the component. The default is twice the number of cores available in the CPUs. The capacity of the system running the Mule instance also limits concurrency. Like the blockSize setting, this setting provides a way to tune performance.

Target

target

To use the payload received by a batch job instance in a component that is located after the Batch Job component, you can provide a unique value for the target and use payload in the downstream component to gain access that payload. Without a target value, the input payload to the Batch Job component is not available in downstream components. For more information about target variables, see Enrich Data with Target Variables. There is no default value.

### Batch Job History () A batch job history configuration enables you to address a `No space left on device` error by adjusting the amount of time that historical data for batch job instances persist in a temporary Mule directory. This error can occur if the frequency or number of records to process is too high for the available disk space or for a CloudHub worker of a given size to handle. By default, the history of batch job instances persists for 7 days. A monitoring process automatically removes that history when the period expires. ![Batch job history fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/batch-job-fields-history-studio.png) The following table describes each field and includes the XML attribute for the field.
NameXMLDescription

Max Age

maxAge

Maximum age of job instances before they expire, for example: expiration maxAge="10". Default: maxAge=7.

Time Unit

ageUnit

The unit of time to apply to the maxAge. Valid values: DAYS, HOURS, MILLISECONDS, MINUTES, and SECONDS. Default: ageUnit=DAYS.

Note that these fields are attributes to the `` element, which is embedded within ``: ```xml ``` The XML example is edited to focus on settings in the batch history fields. ## Batch Step Component () The Batch Step component runs during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases#phase_process) of a batch job instance, not during the Load and Dispatch or On Complete phases. A minimum of one Batch Step component is required within a Batch Job component. In addition to changing the name of a Batch Step component, you can configure _filters_ that determine which records the component accepts for processing within the component. Any processors that you add to the component act on records that the Batch Job component accepts. ![Batch job general fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/batch-step-fields-studio.png) The following table describes each field and includes the XML attribute for the field.
Field NameXMLDescription

Name

name

Configurable name for a Batch Step component. The default is Batch_Step for the first Batch Step component within a Batch Job component. Subsequent steps append a unique number to the name, following the sequence, Batch_Step1, Batch_Step2, and so on.

Accept Expression

acceptExpression

Optional DataWeave expression for a filter that determines whether to process a record in the component. If both the acceptExpression and the acceptPolicy values for a record evaluate to true, then the component accepts the record for processing. If not, the component skips the record, and the record becomes available to any downstream Batch Step components. Examples:

  • acceptExpression="#[payload.age > 21]" for a payload with an age field

  • acceptExpression="#[not isBlank(payload.name)]" for a payload with a name field.

Accept Policy

acceptPolicy

Accepts a record for processing only if the policy evaluates to true for that record. You can base acceptance on the success or failure of a record to process successfully in preceding (upstream) Batch Step components within the Batch Job component. You can configure the component to process only records that processed successfully, only records that failed to process successfully, or all records, regardless of whether they processed successfully. The default is NO_FAILURES. Note that the acceptPolicy evaluates before any acceptExpression on the component, and the maxFailedRecords setting on the Batch Job component takes precedence over acceptPolicy settings.

  • NO_FAILURES: Default setting. Accepts a record for processing if the record never failed to process successfully within a preceding Batch Step component or if there is no upstream Batch Step component.

  • ONLY_FAILURES: Accepts a record for processing if the record failed to process successfully within a preceding Batch Step component.

  • ALL: Accepts a record for processing regardless of processing successfully or failing within a preceding Batch Step component.

## Batch Aggregator Component () The Batch Aggregator component is an optional component that acts on an array of records. Aggregation takes place during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases#phase_process) of a batch job instance. There is no default configuration for the Batch Aggregator component. If you use this component, you must indicate whether to stream records (`streaming`) or pull records from the queue into separate arrays of a fixed size (`size`), but not both. The settings are mutually exclusive. Random access to streamed records is not possible. The Batch Aggregator component accepts one or more processors for the message `payload`. However, it is common to use a scope within the aggregator, such as [For Each](https://docs.mulesoft.com/mule-runtime/4.11/for-each-scope-concept) scope, to iterate over each record so that the child processors within the scope can act on each record individually. The Batch Aggregator component also provides a way preserve the MIME type of records (`preserveMimeTypes`), which is needed when accessing part of a record that you are aggregating as a fixed size (`size`). See [Preserving the MIME types of the Aggregated Records](https://docs.mulesoft.com/mule-runtime/4.11/batch-filters-and-batch-aggregator#preserving-the-mime-types-of-the-aggregated-records). To learn about record processing within this component, see batch aggregation information in [Process Phase](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases#batch_aggregator_processing). Note that some connectors, such as [Anypoint Connector for Salesforce (Salesforce Connector)](https://docs.mulesoft.com/salesforce-connector/latest/salesforce-connector-reference#upsert) and [Anypoint Connector for NetSuite (NetSuite Connector)](https://docs.mulesoft.com/netsuite-connector/latest/netsuite-reference#upsert), provide operations that can handle record-level errors without causing the batch aggregation process to fail. When using Batch Aggregators, consider the following limitations: - When using a Batch Aggregator component, do not attempt to process Guava data types, such as `ImmutableMap`. Instead, use a Java `Map` to avoid serialization issues. - The Batch Aggregator component does not support job-instance-wide [transactions](https://docs.mulesoft.com/mule-runtime/4.11/transaction-management). Within a Batch Step component, you can define a transaction that processes each record in a separate transaction. However, any transaction started by a Batch Step component ends before the Batch Aggregator component starts processing. Components cannot share a transaction because a transaction cannot cross the boundary between the components. ![Batch Aggregator component fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/batch-aggregator-fields-studio.png) The following table describes each field and includes the XML element for the field.
Field NameXMLDescription

Display Name

doc:name

Configurable name for the component. Example: doc:name="My Aggregator". The default name is Batch Aggregator.

Aggregator Size

size

Size of each array of records to process. There is no default size. The processor within the component must accept an array as input. The component continues pulling records from the batch stepping queue into arrays of the configured size until none are left. If the queue contains fewer records than the configured size, the component pulls those records into a smaller array for processing. You must set the Size (size) or Streaming (streaming) property but not both.

When using this configuration, the component does not wait for the Batch Step component to finish processing all records in an instance or batch. Once the set number of records is available in the stepping queue, the Batch Aggregator component pulls those records into an array and processes them.

Streaming

streaming

When streaming=true, the component acts on all records in a batch job instance and returns the results in an array of a size equal to the number of records in the instance. The batch size setting through the Batch Job component does not limit the number of records to process or return in the array. For example, assume that the aggregator returns the numeric IDs of a small batch job instance that processes only ten records of the form {"id": 1}, {"id": 2}, and so on. In this case, the output array for the instance contains ten IDs, such as [1, 6, 2, 7, 3, 8, 4, 9, 5, 10], even if the blockSize on the Batch Job component is set to a number smaller than the number of records in the instance, such as 5.

Processors can gain sequential access to the array of streamed records. Random access to the streamed records is not allowed because the aggregator does not preserve the processed records.

There is no default. You must set the Size (size) or Streaming (streaming) property but not both.

Preserve Mime Types

preserveMimeTypes

Defaults to false. To preserve the MIME type of records processed within this component, set this attribute to true. Processors that cannot determine the MIME type of data return output, such as null, or unreadable references to the payload, such as [[B@e596d5c, [B@1c4c3b32], …​]. Setting preserveMimeTypes=true is useful when this component is set to process a fixed number (size) of records.

When deciding whether to stream aggregated records, consider the following: - SaaS providers often have restrictions on accepting streaming input. - Batch streaming is often useful in batch processing when writing to a file such as CSV, JSON, or XML. - Batch streaming affects the performance of your application because the array of records is stored in RAM, which can slow the pace of transaction processing. Though performance slows, the trade-off of streaming data can warrant its use. - Streaming prevents random access to records because a streaming commit is a one-read, forward-only iterator. However, you can perform random access operations when streaming if you use a component like [For Each](https://docs.mulesoft.com/mule-runtime/4.11/for-each-scope-concept). For Each provides a separate array of records, which is accessible through its `records` variable. --- product: Mule Runtime version: 4.12 --- # Batch Component Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch components manage bulk processing of records with minimal adjustments to default component settings. They are highly configurable to meet specific processing and performance requirements. A Batch Job component must contain at least one Batch Step component. Optionally, each Batch Step component can contain a single Batch Aggregator component. The Mule flow in the following figure shows batch components. ![A flow showing batch processing components in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/batch-flow-generic-example.png) The Batch Job component splits the payload of the Mule message into records. Within the Batch Step and Batch Aggregator components, these records are available with the keyword `payload`, and Mule variables are also accessible through the `vars` keyword. However, Mule attributes are not accessible from within these components. Both components return `null` on `attributes`. This reference assumes that you are familiar with the [batch processing phases](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases) of a batch job instance. ## Batch Job Component () This component prepares its input for processing and outputs a report with results of that processing. Preparation takes place during the [Load and Dispatch](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases#phase_load_dispatch) phase of a batch job instance, and the report is available in the [On Complete](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases#phase_on_complete) phase. In Studio, you can set these properties in the component’s [General](#ref_batch_job_general_fields) and [History](#ref_batch_job_history_fields) tabs. ### Batch Job Properties The Batch Job component provides a number of configurable properties that determine how batch processing takes place. It also provides a way of storing the input payload in a target variable for use by subsequent components in the flow, which can be useful because the Batch Job component consumes the message payload. Anypoint Studio provides the following fields in the **General** tab: ![Batch job fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/batch-job-fields-studio.png) The following table describes each field and includes the XML attribute for the field.
Field NameXMLDescription

Name

name

Configurable name for a Batch Job component. The default name appends Batch_Job to the name of the application.

Max Failed Records

maxFailedRecords

Maximum number of records that can fail within a batch job instance before the execution of that instance stops. The default is 0. Use -1 for no limit. This setting takes precedence over any accept policy (acceptPolicy) or expression (acceptExpression) filter on a Batch Step component within the Batch Job component. When a batch job instance exceeds the maxFailedRecords value, the Batch Job component stops processing of the batch job instance in which the failure occurs, assigns the instance the status FAILED_PROCESS_RECORDS, and reports the number of failed records in the instance. When a batch job instance reaches this threshold, the console prints a message such as this one (edited for readability):

INFO  ... DefaultBatchEngine:
 instance '6d85c380-f332-11ec-bb5f-147ddaaf4f97' of job 'Batch_Job_in_Mule_Flow'
 has reached the max allowed number of failed records. Record will be added to
 failed list and the instance will be removed from execution pool.
...
INFO  ... DefaultBatchEngine:
 instance 6d85c380-f332-11ec-bb5f-147ddaaf4f97 of job Batch_Job_in_Mule_Flow
 has been stopped. Instance status is FAILED_PROCESS_RECORDS

Note that parallel processing within a batch job instance makes it possible for the number of errors to exceed the configured maximum because it is possible for multiple records fail at the same time.

Scheduling Strategy

schedulingStrategy

When a Batch Job component triggers repeatedly, more than one batch job instance can be ready to execute at the same time. The instances can run sequentially based on their creation timestamp (the default) or according to a round-robin algorithm that attempts to maximize the use of available resources. This setting is appropriate only for jobs that have no side effects or dependencies on other records because the order of processing is not guaranteed.

  • ORDERED_SQUENTIAL (default): With this setting, batch job instances execute one at a time in the order established by their creation timestamp. An instance created earlier executes before an instance created at a later time and date.

  • ROUND_ROBIN: With this setting, all batch job instances execute based on a round-robin algorithm that assigns available resources. Order of execution is not predetermined. Batch instances can execute in any order. This option is viable only if you are certain that no execution of an instance is capable of producing a side effect on an execution of another instance. Best practices:

    • To avoid potential updates to the same record in concurrently running batch job instances, do not use this strategy for data synchronization jobs. Using this strategy when synchronizing data makes it possible to return a result with an earlier, incorrect version of the data.

    • Use this strategy to parallelize execution of batch job instances if you are certain that no record depends on the processing of another record within the Batch Job component, such as a case in which your batch job retrieves only new records from a database.

Job Instance ID

jobInstanceId

Optional expression that provides a recognizable, unique name for the batch instance. To make the name unique, you must use a DataWeave expression, for example, #[jobInstanceId="#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}] within this field. If an expression returns the same value more than once, Mule throws an error with a message such as, Batch Job 'my-batch-job-example' already has an instance with id 'my-repeated-id'. The Batch Job component uses this value to create a new identifier each time the Mule flow reaches the Batch Job component. If you do not provide an ID, Mule automatically creates a UUID that serves as the identifier for each batch job instance.

Batch Block Size

blockSize

Number of records to process per record block. The default is 100 records per block. If fewer records are available for processing than the configured size, Mule sends a block of a smaller size to the record processors. Such a case can occur, for example, if there are 1010 records and the block size is 100 because the modulo is 10, not 0. The block size setting provides a way to tune performance, which is affected by the size of records in each block and the maxConcurrency setting.

Max Concurrency

maxConcurrency

Property that sets the maximum level of parallelism to allow when processing record blocks within the component. The default is twice the number of cores available in the CPUs. The capacity of the system running the Mule instance also limits concurrency. Like the blockSize setting, this setting provides a way to tune performance.

Target

target

To use the payload received by a batch job instance in a component that is located after the Batch Job component, you can provide a unique value for the target and use payload in the downstream component to gain access that payload. Without a target value, the input payload to the Batch Job component is not available in downstream components. For more information about target variables, see Enrich Data with Target Variables. There is no default value.

### Batch Job History () A batch job history configuration enables you to address a `No space left on device` error by adjusting the amount of time that historical data for batch job instances persist in a temporary Mule directory. This error can occur if the frequency or number of records to process is too high for the available disk space or for a CloudHub worker of a given size to handle. By default, the history of batch job instances persists for 7 days. A monitoring process automatically removes that history when the period expires. ![Batch job history fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/batch-job-fields-history-studio.png) The following table describes each field and includes the XML attribute for the field.
NameXMLDescription

Max Age

maxAge

Maximum age of job instances before they expire, for example: expiration maxAge="10". Default: maxAge=7.

Time Unit

ageUnit

The unit of time to apply to the maxAge. Valid values: DAYS, HOURS, MILLISECONDS, MINUTES, and SECONDS. Default: ageUnit=DAYS.

Note that these fields are attributes to the `` element, which is embedded within ``: ```xml ``` The XML example is edited to focus on settings in the batch history fields. ## Batch Step Component () The Batch Step component runs during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases#phase_process) of a batch job instance, not during the Load and Dispatch or On Complete phases. A minimum of one Batch Step component is required within a Batch Job component. In addition to changing the name of a Batch Step component, you can configure _filters_ that determine which records the component accepts for processing within the component. Any processors that you add to the component act on records that the Batch Job component accepts. ![Batch job general fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/batch-step-fields-studio.png) The following table describes each field and includes the XML attribute for the field.
Field NameXMLDescription

Name

name

Configurable name for a Batch Step component. The default is Batch_Step for the first Batch Step component within a Batch Job component. Subsequent steps append a unique number to the name, following the sequence, Batch_Step1, Batch_Step2, and so on.

Accept Expression

acceptExpression

Optional DataWeave expression for a filter that determines whether to process a record in the component. If both the acceptExpression and the acceptPolicy values for a record evaluate to true, then the component accepts the record for processing. If not, the component skips the record, and the record becomes available to any downstream Batch Step components. Examples:

  • acceptExpression="#[payload.age > 21]" for a payload with an age field

  • acceptExpression="#[not isBlank(payload.name)]" for a payload with a name field.

Accept Policy

acceptPolicy

Accepts a record for processing only if the policy evaluates to true for that record. You can base acceptance on the success or failure of a record to process successfully in preceding (upstream) Batch Step components within the Batch Job component. You can configure the component to process only records that processed successfully, only records that failed to process successfully, or all records, regardless of whether they processed successfully. The default is NO_FAILURES. Note that the acceptPolicy evaluates before any acceptExpression on the component, and the maxFailedRecords setting on the Batch Job component takes precedence over acceptPolicy settings.

  • NO_FAILURES: Default setting. Accepts a record for processing if the record never failed to process successfully within a preceding Batch Step component or if there is no upstream Batch Step component.

  • ONLY_FAILURES: Accepts a record for processing if the record failed to process successfully within a preceding Batch Step component.

  • ALL: Accepts a record for processing regardless of processing successfully or failing within a preceding Batch Step component.

## Batch Aggregator Component () The Batch Aggregator component is an optional component that acts on an array of records. Aggregation takes place during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases#phase_process) of a batch job instance. There is no default configuration for the Batch Aggregator component. If you use this component, you must indicate whether to stream records (`streaming`) or pull records from the queue into separate arrays of a fixed size (`size`), but not both. The settings are mutually exclusive. Random access to streamed records is not possible. The Batch Aggregator component accepts one or more processors for the message `payload`. However, it is common to use a scope within the aggregator, such as [For Each](https://docs.mulesoft.com/mule-runtime/4.12/for-each-scope-concept) scope, to iterate over each record so that the child processors within the scope can act on each record individually. The Batch Aggregator component also provides a way preserve the MIME type of records (`preserveMimeTypes`), which is needed when accessing part of a record that you are aggregating as a fixed size (`size`). See [Preserving the MIME types of the Aggregated Records](https://docs.mulesoft.com/mule-runtime/4.12/batch-filters-and-batch-aggregator#preserving-the-mime-types-of-the-aggregated-records). To learn about record processing within this component, see batch aggregation information in [Process Phase](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases#batch_aggregator_processing). Note that some connectors, such as [Anypoint Connector for Salesforce (Salesforce Connector)](https://docs.mulesoft.com/salesforce-connector/latest/salesforce-connector-reference#upsert) and [Anypoint Connector for NetSuite (NetSuite Connector)](https://docs.mulesoft.com/netsuite-connector/latest/netsuite-reference#upsert), provide operations that can handle record-level errors without causing the batch aggregation process to fail. When using Batch Aggregators, consider the following limitations: - When using a Batch Aggregator component, do not attempt to process Guava data types, such as `ImmutableMap`. Instead, use a Java `Map` to avoid serialization issues. - The Batch Aggregator component does not support job-instance-wide [transactions](https://docs.mulesoft.com/mule-runtime/4.12/transaction-management). Within a Batch Step component, you can define a transaction that processes each record in a separate transaction. However, any transaction started by a Batch Step component ends before the Batch Aggregator component starts processing. Components cannot share a transaction because a transaction cannot cross the boundary between the components. ![Batch Aggregator component fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/batch-aggregator-fields-studio.png) The following table describes each field and includes the XML element for the field.
Field NameXMLDescription

Display Name

doc:name

Configurable name for the component. Example: doc:name="My Aggregator". The default name is Batch Aggregator.

Aggregator Size

size

Size of each array of records to process. There is no default size. The processor within the component must accept an array as input. The component continues pulling records from the batch stepping queue into arrays of the configured size until none are left. If the queue contains fewer records than the configured size, the component pulls those records into a smaller array for processing. You must set the Size (size) or Streaming (streaming) property but not both.

When using this configuration, the component does not wait for the Batch Step component to finish processing all records in an instance or batch. Once the set number of records is available in the stepping queue, the Batch Aggregator component pulls those records into an array and processes them.

Streaming

streaming

When streaming=true, the component acts on all records in a batch job instance and returns the results in an array of a size equal to the number of records in the instance. The batch size setting through the Batch Job component does not limit the number of records to process or return in the array. For example, assume that the aggregator returns the numeric IDs of a small batch job instance that processes only ten records of the form {"id": 1}, {"id": 2}, and so on. In this case, the output array for the instance contains ten IDs, such as [1, 6, 2, 7, 3, 8, 4, 9, 5, 10], even if the blockSize on the Batch Job component is set to a number smaller than the number of records in the instance, such as 5.

Processors can gain sequential access to the array of streamed records. Random access to the streamed records is not allowed because the aggregator does not preserve the processed records.

There is no default. You must set the Size (size) or Streaming (streaming) property but not both.

Preserve Mime Types

preserveMimeTypes

Defaults to false. To preserve the MIME type of records processed within this component, set this attribute to true. Processors that cannot determine the MIME type of data return output, such as null, or unreadable references to the payload, such as [[B@e596d5c, [B@1c4c3b32], …​]. Setting preserveMimeTypes=true is useful when this component is set to process a fixed number (size) of records.

When deciding whether to stream aggregated records, consider the following: - SaaS providers often have restrictions on accepting streaming input. - Batch streaming is often useful in batch processing when writing to a file such as CSV, JSON, or XML. - Batch streaming affects the performance of your application because the array of records is stored in RAM, which can slow the pace of transaction processing. Though performance slows, the trade-off of streaming data can warrant its use. - Streaming prevents random access to records because a streaming commit is a one-read, forward-only iterator. However, you can perform random access operations when streaming if you use a component like [For Each](https://docs.mulesoft.com/mule-runtime/4.12/for-each-scope-concept). For Each provides a separate array of records, which is accessible through its `records` variable. --- product: Mule Runtime version: 4.4 --- # Batch Component Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch components manage bulk processing of records with minimal adjustments to default component settings. They are highly configurable to meet specific processing and performance requirements. A Batch Job component must contain at least one Batch Step component. Optionally, each Batch Step component can contain a single Batch Aggregator component. The Mule flow in the following figure shows batch components. ![Batch Processing Components in a Mule Flow within Studio](/mulesoft/current/en-us/mule-runtime/4.4/_images/batch-flow-generic-example.png) The Batch Job component splits the payload of the Mule message into records. Within the Batch Step and Batch Aggregator components, these records are available with the keyword `payload`, and Mule variables are also accessible through the `vars` keyword. However, Mule attributes are not accessible from within these components. Both components return `null` on `attributes`. This reference assumes that you are familiar with the [batch processing phases](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases) of a batch job instance. ## Batch Job Component () This component prepares its input for processing and outputs a report with results of that processing. Preparation takes place during the [Load and Dispatch](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases#phase_load_dispatch) phase of a batch job instance, and the report is available in the [On Complete](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases#phase_on_complete) phase. In Studio, you can set these properties in the component’s [General](#ref_batch_job_general_fields) and [History](#ref_batch_job_history_fields) tabs. ### Batch Job Properties The Batch Job component provides a number of configurable properties that determine how batch processing takes place. It also provides a way of storing the input payload in a target variable for use by subsequent components in the flow, which can be useful because the Batch Job component consumes the message payload. Anypoint Studio provides the following fields in the **General** tab: ![Batch Job fields in Studio](/mulesoft/current/en-us/mule-runtime/4.4/_images/batch-job-fields-studio.png) The following table describes each field and includes the XML attribute for the field.
Field NameXMLDescription

Name

name

Configurable name for a Batch Job component. The default name appends Batch_Job to the name of the application.

Max Failed Records

maxFailedRecords

Maximum number of records that can fail within a batch job instance before the execution of that instance stops. The default is 0. Use -1 for no limit. This setting takes precedence over any accept policy (acceptPolicy) or expression (acceptExpression) filter on a Batch Step component within the Batch Job component. When a batch job instance exceeds the maxFailedRecords value, the Batch Job component stops processing of the batch job instance in which the failure occurs, assigns the instance the status FAILED_PROCESS_RECORDS, and reports the number of failed records in the instance. When a batch job instance reaches this threshold, the console prints a message such as this one (edited for readability):

INFO  ... DefaultBatchEngine:
 instance '6d85c380-f332-11ec-bb5f-147ddaaf4f97' of job 'Batch_Job_in_Mule_Flow'
 has reached the max allowed number of failed records. Record will be added to
 failed list and the instance will be removed from execution pool.
...
INFO  ... DefaultBatchEngine:
 instance 6d85c380-f332-11ec-bb5f-147ddaaf4f97 of job Batch_Job_in_Mule_Flow
 has been stopped. Instance status is FAILED_PROCESS_RECORDS

Note that parallel processing within a batch job instance makes it possible for the number of errors to exceed the configured maximum because it is possible for multiple records fail at the same time.

Scheduling Strategy

schedulingStrategy

When a Batch Job component triggers repeatedly, more than one batch job instance can be ready to execute at the same time. The instances can run sequentially based on their creation timestamp (the default) or according to a round-robin algorithm that attempts to maximize the use of available resources. This setting is appropriate only for jobs that have no side effects or dependencies on other records because the order of processing is not guaranteed.

  • ORDERED_SQUENTIAL (default): With this setting, batch job instances execute one at a time in the order established by their creation timestamp. An instance created earlier executes before an instance created at a later time and date.

  • ROUND_ROBIN: With this setting, all batch job instances execute based on a round-robin algorithm that assigns available resources. Order of execution is not predetermined. Batch instances can execute in any order. This option is viable only if you are certain that no execution of an instance is capable of producing a side effect on an execution of another instance. Best practices:

    • To avoid potential updates to the same record in concurrently running batch job instances, do not use this strategy for data synchronization jobs. Using this strategy when synchronizing data makes it possible to return a result with an earlier, incorrect version of the data.

    • Use this strategy to parallelize execution of batch job instances if you are certain that no record depends on the processing of another record within the Batch Job component, such as a case in which your batch job retrieves only new records from a database.

Job Instance ID

jobInstanceId

Optional expression that provides a recognizable, unique name for the batch instance. To make the name unique, you must use a DataWeave expression, for example, #[jobInstanceId="#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}] within this field. If an expression returns the same value more than once, Mule throws an error with a message such as, Batch Job 'my-batch-job-example' already has an instance with id 'my-repeated-id'. The Batch Job component uses this value to create a new identifier each time the Mule flow reaches the Batch Job component. If you do not provide an ID, Mule automatically creates a UUID that serves as the identifier for each batch job instance.

Batch Block Size

blockSize

Number of records to process per record block. The default is 100 records per block. If fewer records are available for processing than the configured size, Mule sends a block of a smaller size to the record processors. Such a case can occur, for example, if there are 1010 records and the block size is 100 because the modulo is 10, not 0. The block size setting provides a way to tune performance, which is affected by the size of records in each block and the maxConcurrency setting.

Max Concurrency

maxConcurrency

Property that sets the maximum level of parallelism to allow when processing record blocks within the component. The default is twice the number of cores available in the CPUs. The capacity of the system running the Mule instance also limits concurrency. Like the blockSize setting, this setting provides a way to tune performance.

Target

target

To use the payload received by a batch job instance in a component that is located after the Batch Job component, you can provide a unique value for the target and use payload in the downstream component to gain access that payload. Without a target value, the input payload to the Batch Job component is not available in downstream components. For more information about target variables, see Enrich Data with Target Variables. There is no default value.

### Batch Job History () A batch job history configuration enables you to address a `No space left on device` error by adjusting the amount of time that historical data for batch job instances persist in a temporary Mule directory. This error can occur if the frequency or number of records to process is too high for the available disk space or for a CloudHub worker of a given size to handle. By default, the history of batch job instances persists for 7 days. A monitoring process automatically removes that history when the period expires. ![Batch Job History fields in Studio](/mulesoft/current/en-us/mule-runtime/4.4/_images/batch-job-fields-history-studio.png) The following table describes each field and includes the XML attribute for the field.
NameXMLDescription

Max Age

maxAge

Maximum age of job instances before they expire, for example: expiration maxAge="10". Default: maxAge=7.

Time Unit

ageUnit

The unit of time to apply to the maxAge. Valid values: DAYS, HOURS, MILLISECONDS, MINUTES, and SECONDS. Default: ageUnit=DAYS.

Note that these fields are attributes to the `` element, which is embedded within ``: ```xml ``` The XML example is edited to focus on settings in the batch history fields. ## Batch Step Component () The Batch Step component runs during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases#phase_process) of a batch job instance, not during the Load and Dispatch or On Complete phases. A minimum of one Batch Step component is required within a Batch Job component. In addition to changing the name of a Batch Step component, you can configure _filters_ that determine which records the component accepts for processing within the component. Any processors that you add to the component act on records that the Batch Job component accepts. ![Batch Step fields in Studio](/mulesoft/current/en-us/mule-runtime/4.4/_images/batch-step-fields-studio.png) The following table describes each field and includes the XML attribute for the field.
Field NameXMLDescription

Name

name

Configurable name for a Batch Step component. The default is Batch_Step for the first Batch Step component within a Batch Job component. Subsequent steps append a unique number to the name, following the sequence, Batch_Step1, Batch_Step2, and so on.

Accept Expression

acceptExpression

Optional DataWeave expression for a filter that determines whether to process a record in the component. If both the acceptExpression and the acceptPolicy values for a record evaluate to true, then the component accepts the record for processing. If not, the component skips the record, and the record becomes available to any downstream Batch Step components. Examples:

  • acceptExpression="#[payload.age > 21]" for a payload with an age field

  • acceptExpression="#[not isBlank(payload.name)]" for a payload with a name field.

Accept Policy

acceptPolicy

Accepts a record for processing only if the policy evaluates to true for that record. You can base acceptance on the success or failure of a record to process successfully in preceding (upstream) Batch Step components within the Batch Job component. You can configure the component to process only records that processed successfully, only records that failed to process successfully, or all records, regardless of whether they processed successfully. The default is NO_FAILURES. Note that the acceptPolicy evaluates before any acceptExpression on the component, and the maxFailedRecords setting on the Batch Job component takes precedence over acceptPolicy settings.

  • NO_FAILURES: Default setting. Accepts a record for processing if the record never failed to process successfully within a preceding Batch Step component or if there is no upstream Batch Step component.

  • ONLY_FAILURES: Accepts a record for processing if the record failed to process successfully within a preceding Batch Step component.

  • ALL: Accepts a record for processing regardless of processing successfully or failing within a preceding Batch Step component.

## Batch Aggregator Component () The Batch Aggregator component is an optional component that acts on an array of records. Aggregation takes place during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases#phase_process) of a batch job instance. There is no default configuration for the Batch Aggregator component. If you use this component, you must indicate whether to stream records (`streaming`) or pull records from the queue into separate arrays of a fixed size (`size`), but not both. The settings are mutually exclusive. Random access to streamed records is not possible. The Batch Aggregator component accepts one or more processors for the message `payload`. However, it is common to use a scope within the aggregator, such as [For Each](https://docs.mulesoft.com/mule-runtime/4.4/for-each-scope-concept) scope, to iterate over each record so that the child processors within the scope can act on each record individually. The Batch Aggregator component also provides a way preserve the MIME type of records (`preserveMimeTypes`), which is needed when accessing part of a record that you are aggregating as a fixed size (`size`). See [Preserving the MIME types of the Aggregated Records](https://docs.mulesoft.com/mule-runtime/4.4/batch-filters-and-batch-aggregator#preserving-the-mime-types-of-the-aggregated-records). To learn about record processing within this component, see batch aggregation information in [Process Phase](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases#batch_aggregator_processing). Note that some connectors, such as [Anypoint Connector for Salesforce (Salesforce Connector)](https://docs.mulesoft.com/salesforce-connector/latest/salesforce-connector-reference#upsert) and [Anypoint Connector for NetSuite (NetSuite Connector)](https://docs.mulesoft.com/netsuite-connector/latest/netsuite-reference#upsert), provide operations that can handle record-level errors without causing the batch aggregation process to fail. When using Batch Aggregators, consider the following limitations: - When using a Batch Aggregator component, do not attempt to process Guava data types, such as `ImmutableMap`. Instead, use a Java `Map` to avoid serialization issues. - The Batch Aggregator component does not support job-instance-wide [transactions](https://docs.mulesoft.com/mule-runtime/4.4/transaction-management). Within a Batch Step component, you can define a transaction that processes each record in a separate transaction. However, any transaction started by a Batch Step component ends before the Batch Aggregator component starts processing. Components cannot share a transaction because a transaction cannot cross the boundary between the components. ![Batch Aggregator fields in Studio](/mulesoft/current/en-us/mule-runtime/4.4/_images/batch-aggregator-fields-studio.png) The following table describes each field and includes the XML element for the field.
Field NameXMLDescription

Display Name

doc:name

Configurable name for the component. Example: doc:name="My Aggregator". The default name is Batch Aggregator.

Aggregator Size

size

Size of each array of records to process. There is no default size. The processor within the component must accept an array as input. The component continues pulling records from the batch stepping queue into arrays of the configured size until none are left. If the queue contains fewer records than the configured size, the component pulls those records into a smaller array for processing. You must set the Size (size) or Streaming (streaming) property but not both.

When using this configuration, the component does not wait for the Batch Step component to finish processing all records in an instance or batch. Once the set number of records is available in the stepping queue, the Batch Aggregator component pulls those records into an array and processes them.

Streaming

streaming

When streaming=true, the component acts on all records in a batch job instance and returns the results in an array of a size equal to the number of records in the instance. The batch size setting through the Batch Job component does not limit the number of records to process or return in the array. For example, assume that the aggregator returns the numeric IDs of a small batch job instance that processes only ten records of the form {"id": 1}, {"id": 2}, and so on. In this case, the output array for the instance contains ten IDs, such as [1, 6, 2, 7, 3, 8, 4, 9, 5, 10], even if the blockSize on the Batch Job component is set to a number smaller than the number of records in the instance, such as 5.

Processors can gain sequential access to the array of streamed records. Random access to the streamed records is not allowed because the aggregator does not preserve the processed records.

There is no default. You must set the Size (size) or Streaming (streaming) property but not both.

Preserve Mime Types

preserveMimeTypes

Defaults to false. To preserve the MIME type of records processed within this component, set this attribute to true. Processors that cannot determine the MIME type of data return output, such as null, or unreadable references to the payload, such as [[B@e596d5c, [B@1c4c3b32], …​]. Setting preserveMimeTypes=true is useful when this component is set to process a fixed number (size) of records.

When deciding whether to stream aggregated records, consider the following: - SaaS providers often have restrictions on accepting streaming input. - Batch streaming is often useful in batch processing when writing to a file such as CSV, JSON, or XML. - Batch streaming affects the performance of your application because the array of records is stored in RAM, which can slow the pace of transaction processing. Though performance slows, the trade-off of streaming data can warrant its use. - Streaming prevents random access to records because a streaming commit is a one-read, forward-only iterator. However, you can perform random access operations when streaming if you use a component like [For Each](https://docs.mulesoft.com/mule-runtime/4.4/for-each-scope-concept). For Each provides a separate array of records, which is accessible through its `records` variable. --- product: Mule Runtime version: 4.6 --- # Batch Component Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch components manage bulk processing of records with minimal adjustments to default component settings. They are highly configurable to meet specific processing and performance requirements. A Batch Job component must contain at least one Batch Step component. Optionally, each Batch Step component can contain a single Batch Aggregator component. The Mule flow in the following figure shows batch components. ![Batch Processing Components in a Mule Flow within Studio](/mulesoft/current/en-us/mule-runtime/4.6/_images/batch-flow-generic-example.png) The Batch Job component splits the payload of the Mule message into records. Within the Batch Step and Batch Aggregator components, these records are available with the keyword `payload`, and Mule variables are also accessible through the `vars` keyword. However, Mule attributes are not accessible from within these components. Both components return `null` on `attributes`. This reference assumes that you are familiar with the [batch processing phases](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases) of a batch job instance. ## Batch Job Component () This component prepares its input for processing and outputs a report with results of that processing. Preparation takes place during the [Load and Dispatch](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases#phase_load_dispatch) phase of a batch job instance, and the report is available in the [On Complete](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases#phase_on_complete) phase. In Studio, you can set these properties in the component’s [General](#ref_batch_job_general_fields) and [History](#ref_batch_job_history_fields) tabs. ### Batch Job Properties The Batch Job component provides a number of configurable properties that determine how batch processing takes place. It also provides a way of storing the input payload in a target variable for use by subsequent components in the flow, which can be useful because the Batch Job component consumes the message payload. Anypoint Studio provides the following fields in the **General** tab: ![Batch Job fields in Studio](/mulesoft/current/en-us/mule-runtime/4.6/_images/batch-job-fields-studio.png) The following table describes each field and includes the XML attribute for the field.
Field NameXMLDescription

Name

name

Configurable name for a Batch Job component. The default name appends Batch_Job to the name of the application.

Max Failed Records

maxFailedRecords

Maximum number of records that can fail within a batch job instance before the execution of that instance stops. The default is 0. Use -1 for no limit. This setting takes precedence over any accept policy (acceptPolicy) or expression (acceptExpression) filter on a Batch Step component within the Batch Job component. When a batch job instance exceeds the maxFailedRecords value, the Batch Job component stops processing of the batch job instance in which the failure occurs, assigns the instance the status FAILED_PROCESS_RECORDS, and reports the number of failed records in the instance. When a batch job instance reaches this threshold, the console prints a message such as this one (edited for readability):

INFO  ... DefaultBatchEngine:
 instance '6d85c380-f332-11ec-bb5f-147ddaaf4f97' of job 'Batch_Job_in_Mule_Flow'
 has reached the max allowed number of failed records. Record will be added to
 failed list and the instance will be removed from execution pool.
...
INFO  ... DefaultBatchEngine:
 instance 6d85c380-f332-11ec-bb5f-147ddaaf4f97 of job Batch_Job_in_Mule_Flow
 has been stopped. Instance status is FAILED_PROCESS_RECORDS

Note that parallel processing within a batch job instance makes it possible for the number of errors to exceed the configured maximum because it is possible for multiple records fail at the same time.

Scheduling Strategy

schedulingStrategy

When a Batch Job component triggers repeatedly, more than one batch job instance can be ready to execute at the same time. The instances can run sequentially based on their creation timestamp (the default) or according to a round-robin algorithm that attempts to maximize the use of available resources. This setting is appropriate only for jobs that have no side effects or dependencies on other records because the order of processing is not guaranteed.

  • ORDERED_SQUENTIAL (default): With this setting, batch job instances execute one at a time in the order established by their creation timestamp. An instance created earlier executes before an instance created at a later time and date.

  • ROUND_ROBIN: With this setting, all batch job instances execute based on a round-robin algorithm that assigns available resources. Order of execution is not predetermined. Batch instances can execute in any order. This option is viable only if you are certain that no execution of an instance is capable of producing a side effect on an execution of another instance. Best practices:

    • To avoid potential updates to the same record in concurrently running batch job instances, do not use this strategy for data synchronization jobs. Using this strategy when synchronizing data makes it possible to return a result with an earlier, incorrect version of the data.

    • Use this strategy to parallelize execution of batch job instances if you are certain that no record depends on the processing of another record within the Batch Job component, such as a case in which your batch job retrieves only new records from a database.

Job Instance ID

jobInstanceId

Optional expression that provides a recognizable, unique name for the batch instance. To make the name unique, you must use a DataWeave expression, for example, #[jobInstanceId="#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}] within this field. If an expression returns the same value more than once, Mule throws an error with a message such as, Batch Job 'my-batch-job-example' already has an instance with id 'my-repeated-id'. The Batch Job component uses this value to create a new identifier each time the Mule flow reaches the Batch Job component. If you do not provide an ID, Mule automatically creates a UUID that serves as the identifier for each batch job instance.

Batch Block Size

blockSize

Number of records to process per record block. The default is 100 records per block. If fewer records are available for processing than the configured size, Mule sends a block of a smaller size to the record processors. Such a case can occur, for example, if there are 1010 records and the block size is 100 because the modulo is 10, not 0. The block size setting provides a way to tune performance, which is affected by the size of records in each block and the maxConcurrency setting.

Max Concurrency

maxConcurrency

Property that sets the maximum level of parallelism to allow when processing record blocks within the component. The default is twice the number of cores available in the CPUs. The capacity of the system running the Mule instance also limits concurrency. Like the blockSize setting, this setting provides a way to tune performance.

Target

target

To use the payload received by a batch job instance in a component that is located after the Batch Job component, you can provide a unique value for the target and use payload in the downstream component to gain access that payload. Without a target value, the input payload to the Batch Job component is not available in downstream components. For more information about target variables, see Enrich Data with Target Variables. There is no default value.

### Batch Job History () A batch job history configuration enables you to address a `No space left on device` error by adjusting the amount of time that historical data for batch job instances persist in a temporary Mule directory. This error can occur if the frequency or number of records to process is too high for the available disk space or for a CloudHub worker of a given size to handle. By default, the history of batch job instances persists for 7 days. A monitoring process automatically removes that history when the period expires. ![Batch Job History fields in Studio](/mulesoft/current/en-us/mule-runtime/4.6/_images/batch-job-fields-history-studio.png) The following table describes each field and includes the XML attribute for the field.
NameXMLDescription

Max Age

maxAge

Maximum age of job instances before they expire, for example: expiration maxAge="10". Default: maxAge=7.

Time Unit

ageUnit

The unit of time to apply to the maxAge. Valid values: DAYS, HOURS, MILLISECONDS, MINUTES, and SECONDS. Default: ageUnit=DAYS.

Note that these fields are attributes to the `` element, which is embedded within ``: ```xml ``` The XML example is edited to focus on settings in the batch history fields. ## Batch Step Component () The Batch Step component runs during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases#phase_process) of a batch job instance, not during the Load and Dispatch or On Complete phases. A minimum of one Batch Step component is required within a Batch Job component. In addition to changing the name of a Batch Step component, you can configure _filters_ that determine which records the component accepts for processing within the component. Any processors that you add to the component act on records that the Batch Job component accepts. ![Batch Step fields in Studio](/mulesoft/current/en-us/mule-runtime/4.6/_images/batch-step-fields-studio.png) The following table describes each field and includes the XML attribute for the field.
Field NameXMLDescription

Name

name

Configurable name for a Batch Step component. The default is Batch_Step for the first Batch Step component within a Batch Job component. Subsequent steps append a unique number to the name, following the sequence, Batch_Step1, Batch_Step2, and so on.

Accept Expression

acceptExpression

Optional DataWeave expression for a filter that determines whether to process a record in the component. If both the acceptExpression and the acceptPolicy values for a record evaluate to true, then the component accepts the record for processing. If not, the component skips the record, and the record becomes available to any downstream Batch Step components. Examples:

  • acceptExpression="#[payload.age > 21]" for a payload with an age field

  • acceptExpression="#[not isBlank(payload.name)]" for a payload with a name field.

Accept Policy

acceptPolicy

Accepts a record for processing only if the policy evaluates to true for that record. You can base acceptance on the success or failure of a record to process successfully in preceding (upstream) Batch Step components within the Batch Job component. You can configure the component to process only records that processed successfully, only records that failed to process successfully, or all records, regardless of whether they processed successfully. The default is NO_FAILURES. Note that the acceptPolicy evaluates before any acceptExpression on the component, and the maxFailedRecords setting on the Batch Job component takes precedence over acceptPolicy settings.

  • NO_FAILURES: Default setting. Accepts a record for processing if the record never failed to process successfully within a preceding Batch Step component or if there is no upstream Batch Step component.

  • ONLY_FAILURES: Accepts a record for processing if the record failed to process successfully within a preceding Batch Step component.

  • ALL: Accepts a record for processing regardless of processing successfully or failing within a preceding Batch Step component.

## Batch Aggregator Component () The Batch Aggregator component is an optional component that acts on an array of records. Aggregation takes place during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases#phase_process) of a batch job instance. There is no default configuration for the Batch Aggregator component. If you use this component, you must indicate whether to stream records (`streaming`) or pull records from the queue into separate arrays of a fixed size (`size`), but not both. The settings are mutually exclusive. Random access to streamed records is not possible. The Batch Aggregator component accepts one or more processors for the message `payload`. However, it is common to use a scope within the aggregator, such as [For Each](https://docs.mulesoft.com/mule-runtime/4.6/for-each-scope-concept) scope, to iterate over each record so that the child processors within the scope can act on each record individually. The Batch Aggregator component also provides a way preserve the MIME type of records (`preserveMimeTypes`), which is needed when accessing part of a record that you are aggregating as a fixed size (`size`). See [Preserving the MIME types of the Aggregated Records](https://docs.mulesoft.com/mule-runtime/4.6/batch-filters-and-batch-aggregator#preserving-the-mime-types-of-the-aggregated-records). To learn about record processing within this component, see batch aggregation information in [Process Phase](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases#batch_aggregator_processing). Note that some connectors, such as [Anypoint Connector for Salesforce (Salesforce Connector)](https://docs.mulesoft.com/salesforce-connector/latest/salesforce-connector-reference#upsert) and [Anypoint Connector for NetSuite (NetSuite Connector)](https://docs.mulesoft.com/netsuite-connector/latest/netsuite-reference#upsert), provide operations that can handle record-level errors without causing the batch aggregation process to fail. When using Batch Aggregators, consider the following limitations: - When using a Batch Aggregator component, do not attempt to process Guava data types, such as `ImmutableMap`. Instead, use a Java `Map` to avoid serialization issues. - The Batch Aggregator component does not support job-instance-wide [transactions](https://docs.mulesoft.com/mule-runtime/4.6/transaction-management). Within a Batch Step component, you can define a transaction that processes each record in a separate transaction. However, any transaction started by a Batch Step component ends before the Batch Aggregator component starts processing. Components cannot share a transaction because a transaction cannot cross the boundary between the components. ![Batch Aggregator fields in Studio](/mulesoft/current/en-us/mule-runtime/4.6/_images/batch-aggregator-fields-studio.png) The following table describes each field and includes the XML element for the field.
Field NameXMLDescription

Display Name

doc:name

Configurable name for the component. Example: doc:name="My Aggregator". The default name is Batch Aggregator.

Aggregator Size

size

Size of each array of records to process. There is no default size. The processor within the component must accept an array as input. The component continues pulling records from the batch stepping queue into arrays of the configured size until none are left. If the queue contains fewer records than the configured size, the component pulls those records into a smaller array for processing. You must set the Size (size) or Streaming (streaming) property but not both.

When using this configuration, the component does not wait for the Batch Step component to finish processing all records in an instance or batch. Once the set number of records is available in the stepping queue, the Batch Aggregator component pulls those records into an array and processes them.

Streaming

streaming

When streaming=true, the component acts on all records in a batch job instance and returns the results in an array of a size equal to the number of records in the instance. The batch size setting through the Batch Job component does not limit the number of records to process or return in the array. For example, assume that the aggregator returns the numeric IDs of a small batch job instance that processes only ten records of the form {"id": 1}, {"id": 2}, and so on. In this case, the output array for the instance contains ten IDs, such as [1, 6, 2, 7, 3, 8, 4, 9, 5, 10], even if the blockSize on the Batch Job component is set to a number smaller than the number of records in the instance, such as 5.

Processors can gain sequential access to the array of streamed records. Random access to the streamed records is not allowed because the aggregator does not preserve the processed records.

There is no default. You must set the Size (size) or Streaming (streaming) property but not both.

Preserve Mime Types

preserveMimeTypes

Defaults to false. To preserve the MIME type of records processed within this component, set this attribute to true. Processors that cannot determine the MIME type of data return output, such as null, or unreadable references to the payload, such as [[B@e596d5c, [B@1c4c3b32], …​]. Setting preserveMimeTypes=true is useful when this component is set to process a fixed number (size) of records.

When deciding whether to stream aggregated records, consider the following: - SaaS providers often have restrictions on accepting streaming input. - Batch streaming is often useful in batch processing when writing to a file such as CSV, JSON, or XML. - Batch streaming affects the performance of your application because the array of records is stored in RAM, which can slow the pace of transaction processing. Though performance slows, the trade-off of streaming data can warrant its use. - Streaming prevents random access to records because a streaming commit is a one-read, forward-only iterator. However, you can perform random access operations when streaming if you use a component like [For Each](https://docs.mulesoft.com/mule-runtime/4.6/for-each-scope-concept). For Each provides a separate array of records, which is accessible through its `records` variable. --- product: Mule Runtime version: 4.9 --- # Batch Component Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch components manage bulk processing of records with minimal adjustments to default component settings. They are highly configurable to meet specific processing and performance requirements. A Batch Job component must contain at least one Batch Step component. Optionally, each Batch Step component can contain a single Batch Aggregator component. The Mule flow in the following figure shows batch components. ![A flow showing batch processing components in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/batch-flow-generic-example.png) The Batch Job component splits the payload of the Mule message into records. Within the Batch Step and Batch Aggregator components, these records are available with the keyword `payload`, and Mule variables are also accessible through the `vars` keyword. However, Mule attributes are not accessible from within these components. Both components return `null` on `attributes`. This reference assumes that you are familiar with the [batch processing phases](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases) of a batch job instance. ## Batch Job Component () This component prepares its input for processing and outputs a report with results of that processing. Preparation takes place during the [Load and Dispatch](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases#phase_load_dispatch) phase of a batch job instance, and the report is available in the [On Complete](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases#phase_on_complete) phase. In Studio, you can set these properties in the component’s [General](#ref_batch_job_general_fields) and [History](#ref_batch_job_history_fields) tabs. ### Batch Job Properties The Batch Job component provides a number of configurable properties that determine how batch processing takes place. It also provides a way of storing the input payload in a target variable for use by subsequent components in the flow, which can be useful because the Batch Job component consumes the message payload. Anypoint Studio provides the following fields in the **General** tab: ![Batch job fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/batch-job-fields-studio.png) The following table describes each field and includes the XML attribute for the field.
Field NameXMLDescription

Name

name

Configurable name for a Batch Job component. The default name appends Batch_Job to the name of the application.

Max Failed Records

maxFailedRecords

Maximum number of records that can fail within a batch job instance before the execution of that instance stops. The default is 0. Use -1 for no limit. This setting takes precedence over any accept policy (acceptPolicy) or expression (acceptExpression) filter on a Batch Step component within the Batch Job component. When a batch job instance exceeds the maxFailedRecords value, the Batch Job component stops processing of the batch job instance in which the failure occurs, assigns the instance the status FAILED_PROCESS_RECORDS, and reports the number of failed records in the instance. When a batch job instance reaches this threshold, the console prints a message such as this one (edited for readability):

INFO  ... DefaultBatchEngine:
 instance '6d85c380-f332-11ec-bb5f-147ddaaf4f97' of job 'Batch_Job_in_Mule_Flow'
 has reached the max allowed number of failed records. Record will be added to
 failed list and the instance will be removed from execution pool.
...
INFO  ... DefaultBatchEngine:
 instance 6d85c380-f332-11ec-bb5f-147ddaaf4f97 of job Batch_Job_in_Mule_Flow
 has been stopped. Instance status is FAILED_PROCESS_RECORDS

Note that parallel processing within a batch job instance makes it possible for the number of errors to exceed the configured maximum because it is possible for multiple records fail at the same time.

Scheduling Strategy

schedulingStrategy

When a Batch Job component triggers repeatedly, more than one batch job instance can be ready to execute at the same time. The instances can run sequentially based on their creation timestamp (the default) or according to a round-robin algorithm that attempts to maximize the use of available resources. This setting is appropriate only for jobs that have no side effects or dependencies on other records because the order of processing is not guaranteed.

  • ORDERED_SQUENTIAL (default): With this setting, batch job instances execute one at a time in the order established by their creation timestamp. An instance created earlier executes before an instance created at a later time and date.

  • ROUND_ROBIN: With this setting, all batch job instances execute based on a round-robin algorithm that assigns available resources. Order of execution is not predetermined. Batch instances can execute in any order. This option is viable only if you are certain that no execution of an instance is capable of producing a side effect on an execution of another instance. Best practices:

    • To avoid potential updates to the same record in concurrently running batch job instances, do not use this strategy for data synchronization jobs. Using this strategy when synchronizing data makes it possible to return a result with an earlier, incorrect version of the data.

    • Use this strategy to parallelize execution of batch job instances if you are certain that no record depends on the processing of another record within the Batch Job component, such as a case in which your batch job retrieves only new records from a database.

Job Instance ID

jobInstanceId

Optional expression that provides a recognizable, unique name for the batch instance. To make the name unique, you must use a DataWeave expression, for example, #[jobInstanceId="#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}] within this field. If an expression returns the same value more than once, Mule throws an error with a message such as, Batch Job 'my-batch-job-example' already has an instance with id 'my-repeated-id'. The Batch Job component uses this value to create a new identifier each time the Mule flow reaches the Batch Job component. If you do not provide an ID, Mule automatically creates a UUID that serves as the identifier for each batch job instance.

Batch Block Size

blockSize

Number of records to process per record block. The default is 100 records per block. If fewer records are available for processing than the configured size, Mule sends a block of a smaller size to the record processors. Such a case can occur, for example, if there are 1010 records and the block size is 100 because the modulo is 10, not 0. The block size setting provides a way to tune performance, which is affected by the size of records in each block and the maxConcurrency setting.

Max Concurrency

maxConcurrency

Property that sets the maximum level of parallelism to allow when processing record blocks within the component. The default is twice the number of cores available in the CPUs. The capacity of the system running the Mule instance also limits concurrency. Like the blockSize setting, this setting provides a way to tune performance.

Target

target

To use the payload received by a batch job instance in a component that is located after the Batch Job component, you can provide a unique value for the target and use payload in the downstream component to gain access that payload. Without a target value, the input payload to the Batch Job component is not available in downstream components. For more information about target variables, see Enrich Data with Target Variables. There is no default value.

### Batch Job History () A batch job history configuration enables you to address a `No space left on device` error by adjusting the amount of time that historical data for batch job instances persist in a temporary Mule directory. This error can occur if the frequency or number of records to process is too high for the available disk space or for a CloudHub worker of a given size to handle. By default, the history of batch job instances persists for 7 days. A monitoring process automatically removes that history when the period expires. ![Batch job history fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/batch-job-fields-history-studio.png) The following table describes each field and includes the XML attribute for the field.
NameXMLDescription

Max Age

maxAge

Maximum age of job instances before they expire, for example: expiration maxAge="10". Default: maxAge=7.

Time Unit

ageUnit

The unit of time to apply to the maxAge. Valid values: DAYS, HOURS, MILLISECONDS, MINUTES, and SECONDS. Default: ageUnit=DAYS.

Note that these fields are attributes to the `` element, which is embedded within ``: ```xml ``` The XML example is edited to focus on settings in the batch history fields. ## Batch Step Component () The Batch Step component runs during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases#phase_process) of a batch job instance, not during the Load and Dispatch or On Complete phases. A minimum of one Batch Step component is required within a Batch Job component. In addition to changing the name of a Batch Step component, you can configure _filters_ that determine which records the component accepts for processing within the component. Any processors that you add to the component act on records that the Batch Job component accepts. ![Batch job general fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/batch-step-fields-studio.png) The following table describes each field and includes the XML attribute for the field.
Field NameXMLDescription

Name

name

Configurable name for a Batch Step component. The default is Batch_Step for the first Batch Step component within a Batch Job component. Subsequent steps append a unique number to the name, following the sequence, Batch_Step1, Batch_Step2, and so on.

Accept Expression

acceptExpression

Optional DataWeave expression for a filter that determines whether to process a record in the component. If both the acceptExpression and the acceptPolicy values for a record evaluate to true, then the component accepts the record for processing. If not, the component skips the record, and the record becomes available to any downstream Batch Step components. Examples:

  • acceptExpression="#[payload.age > 21]" for a payload with an age field

  • acceptExpression="#[not isBlank(payload.name)]" for a payload with a name field.

Accept Policy

acceptPolicy

Accepts a record for processing only if the policy evaluates to true for that record. You can base acceptance on the success or failure of a record to process successfully in preceding (upstream) Batch Step components within the Batch Job component. You can configure the component to process only records that processed successfully, only records that failed to process successfully, or all records, regardless of whether they processed successfully. The default is NO_FAILURES. Note that the acceptPolicy evaluates before any acceptExpression on the component, and the maxFailedRecords setting on the Batch Job component takes precedence over acceptPolicy settings.

  • NO_FAILURES: Default setting. Accepts a record for processing if the record never failed to process successfully within a preceding Batch Step component or if there is no upstream Batch Step component.

  • ONLY_FAILURES: Accepts a record for processing if the record failed to process successfully within a preceding Batch Step component.

  • ALL: Accepts a record for processing regardless of processing successfully or failing within a preceding Batch Step component.

## Batch Aggregator Component () The Batch Aggregator component is an optional component that acts on an array of records. Aggregation takes place during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases#phase_process) of a batch job instance. There is no default configuration for the Batch Aggregator component. If you use this component, you must indicate whether to stream records (`streaming`) or pull records from the queue into separate arrays of a fixed size (`size`), but not both. The settings are mutually exclusive. Random access to streamed records is not possible. The Batch Aggregator component accepts one or more processors for the message `payload`. However, it is common to use a scope within the aggregator, such as [For Each](https://docs.mulesoft.com/mule-runtime/4.9/for-each-scope-concept) scope, to iterate over each record so that the child processors within the scope can act on each record individually. The Batch Aggregator component also provides a way preserve the MIME type of records (`preserveMimeTypes`), which is needed when accessing part of a record that you are aggregating as a fixed size (`size`). See [Preserving the MIME types of the Aggregated Records](https://docs.mulesoft.com/mule-runtime/4.9/batch-filters-and-batch-aggregator#preserving-the-mime-types-of-the-aggregated-records). To learn about record processing within this component, see batch aggregation information in [Process Phase](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases#batch_aggregator_processing). Note that some connectors, such as [Anypoint Connector for Salesforce (Salesforce Connector)](https://docs.mulesoft.com/salesforce-connector/latest/salesforce-connector-reference#upsert) and [Anypoint Connector for NetSuite (NetSuite Connector)](https://docs.mulesoft.com/netsuite-connector/latest/netsuite-reference#upsert), provide operations that can handle record-level errors without causing the batch aggregation process to fail. When using Batch Aggregators, consider the following limitations: - When using a Batch Aggregator component, do not attempt to process Guava data types, such as `ImmutableMap`. Instead, use a Java `Map` to avoid serialization issues. - The Batch Aggregator component does not support job-instance-wide [transactions](https://docs.mulesoft.com/mule-runtime/4.9/transaction-management). Within a Batch Step component, you can define a transaction that processes each record in a separate transaction. However, any transaction started by a Batch Step component ends before the Batch Aggregator component starts processing. Components cannot share a transaction because a transaction cannot cross the boundary between the components. ![Batch Aggregator component fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/batch-aggregator-fields-studio.png) The following table describes each field and includes the XML element for the field.
Field NameXMLDescription

Display Name

doc:name

Configurable name for the component. Example: doc:name="My Aggregator". The default name is Batch Aggregator.

Aggregator Size

size

Size of each array of records to process. There is no default size. The processor within the component must accept an array as input. The component continues pulling records from the batch stepping queue into arrays of the configured size until none are left. If the queue contains fewer records than the configured size, the component pulls those records into a smaller array for processing. You must set the Size (size) or Streaming (streaming) property but not both.

When using this configuration, the component does not wait for the Batch Step component to finish processing all records in an instance or batch. Once the set number of records is available in the stepping queue, the Batch Aggregator component pulls those records into an array and processes them.

Streaming

streaming

When streaming=true, the component acts on all records in a batch job instance and returns the results in an array of a size equal to the number of records in the instance. The batch size setting through the Batch Job component does not limit the number of records to process or return in the array. For example, assume that the aggregator returns the numeric IDs of a small batch job instance that processes only ten records of the form {"id": 1}, {"id": 2}, and so on. In this case, the output array for the instance contains ten IDs, such as [1, 6, 2, 7, 3, 8, 4, 9, 5, 10], even if the blockSize on the Batch Job component is set to a number smaller than the number of records in the instance, such as 5.

Processors can gain sequential access to the array of streamed records. Random access to the streamed records is not allowed because the aggregator does not preserve the processed records.

There is no default. You must set the Size (size) or Streaming (streaming) property but not both.

Preserve Mime Types

preserveMimeTypes

Defaults to false. To preserve the MIME type of records processed within this component, set this attribute to true. Processors that cannot determine the MIME type of data return output, such as null, or unreadable references to the payload, such as [[B@e596d5c, [B@1c4c3b32], …​]. Setting preserveMimeTypes=true is useful when this component is set to process a fixed number (size) of records.

When deciding whether to stream aggregated records, consider the following: - SaaS providers often have restrictions on accepting streaming input. - Batch streaming is often useful in batch processing when writing to a file such as CSV, JSON, or XML. - Batch streaming affects the performance of your application because the array of records is stored in RAM, which can slow the pace of transaction processing. Though performance slows, the trade-off of streaming data can warrant its use. - Streaming prevents random access to records because a streaming commit is a one-read, forward-only iterator. However, you can perform random access operations when streaming if you use a component like [For Each](https://docs.mulesoft.com/mule-runtime/4.9/for-each-scope-concept). For Each provides a separate array of records, which is accessible through its `records` variable. --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Batch Component Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch components manage bulk processing of records with minimal adjustments to default component settings. They are highly configurable to meet specific processing and performance requirements. A Batch Job component must contain at least one Batch Step component. Optionally, each Batch Step component can contain a single Batch Aggregator component. The Mule flow in the following figure shows batch components. ![A flow showing batch processing components in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/batch-flow-generic-example.png) The Batch Job component splits the payload of the Mule message into records. Within the Batch Step and Batch Aggregator components, these records are available with the keyword `payload`, and Mule variables are also accessible through the `vars` keyword. However, Mule attributes are not accessible from within these components. Both components return `null` on `attributes`. This reference assumes that you are familiar with the [batch processing phases](https://docs.mulesoft.com/mule-runtime/latest/batch-phases) of a batch job instance. ## Batch Job Component () This component prepares its input for processing and outputs a report with results of that processing. Preparation takes place during the [Load and Dispatch](https://docs.mulesoft.com/mule-runtime/latest/batch-phases#phase_load_dispatch) phase of a batch job instance, and the report is available in the [On Complete](https://docs.mulesoft.com/mule-runtime/latest/batch-phases#phase_on_complete) phase. In Studio, you can set these properties in the component’s [General](#ref_batch_job_general_fields) and [History](#ref_batch_job_history_fields) tabs. ### Batch Job Properties The Batch Job component provides a number of configurable properties that determine how batch processing takes place. It also provides a way of storing the input payload in a target variable for use by subsequent components in the flow, which can be useful because the Batch Job component consumes the message payload. Anypoint Studio provides the following fields in the **General** tab: ![Batch job fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/batch-job-fields-studio.png) The following table describes each field and includes the XML attribute for the field.
Field NameXMLDescription

Name

name

Configurable name for a Batch Job component. The default name appends Batch_Job to the name of the application.

Max Failed Records

maxFailedRecords

Maximum number of records that can fail within a batch job instance before the execution of that instance stops. The default is 0. Use -1 for no limit. This setting takes precedence over any accept policy (acceptPolicy) or expression (acceptExpression) filter on a Batch Step component within the Batch Job component. When a batch job instance exceeds the maxFailedRecords value, the Batch Job component stops processing of the batch job instance in which the failure occurs, assigns the instance the status FAILED_PROCESS_RECORDS, and reports the number of failed records in the instance. When a batch job instance reaches this threshold, the console prints a message such as this one (edited for readability):

INFO  ... DefaultBatchEngine:
 instance '6d85c380-f332-11ec-bb5f-147ddaaf4f97' of job 'Batch_Job_in_Mule_Flow'
 has reached the max allowed number of failed records. Record will be added to
 failed list and the instance will be removed from execution pool.
...
INFO  ... DefaultBatchEngine:
 instance 6d85c380-f332-11ec-bb5f-147ddaaf4f97 of job Batch_Job_in_Mule_Flow
 has been stopped. Instance status is FAILED_PROCESS_RECORDS

Note that parallel processing within a batch job instance makes it possible for the number of errors to exceed the configured maximum because it is possible for multiple records fail at the same time.

Scheduling Strategy

schedulingStrategy

When a Batch Job component triggers repeatedly, more than one batch job instance can be ready to execute at the same time. The instances can run sequentially based on their creation timestamp (the default) or according to a round-robin algorithm that attempts to maximize the use of available resources. This setting is appropriate only for jobs that have no side effects or dependencies on other records because the order of processing is not guaranteed.

  • ORDERED_SQUENTIAL (default): With this setting, batch job instances execute one at a time in the order established by their creation timestamp. An instance created earlier executes before an instance created at a later time and date.

  • ROUND_ROBIN: With this setting, all batch job instances execute based on a round-robin algorithm that assigns available resources. Order of execution is not predetermined. Batch instances can execute in any order. This option is viable only if you are certain that no execution of an instance is capable of producing a side effect on an execution of another instance. Best practices:

    • To avoid potential updates to the same record in concurrently running batch job instances, do not use this strategy for data synchronization jobs. Using this strategy when synchronizing data makes it possible to return a result with an earlier, incorrect version of the data.

    • Use this strategy to parallelize execution of batch job instances if you are certain that no record depends on the processing of another record within the Batch Job component, such as a case in which your batch job retrieves only new records from a database.

Job Instance ID

jobInstanceId

Optional expression that provides a recognizable, unique name for the batch instance. To make the name unique, you must use a DataWeave expression, for example, #[jobInstanceId="#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}] within this field. If an expression returns the same value more than once, Mule throws an error with a message such as, Batch Job 'my-batch-job-example' already has an instance with id 'my-repeated-id'. The Batch Job component uses this value to create a new identifier each time the Mule flow reaches the Batch Job component. If you do not provide an ID, Mule automatically creates a UUID that serves as the identifier for each batch job instance.

Batch Block Size

blockSize

Number of records to process per record block. The default is 100 records per block. If fewer records are available for processing than the configured size, Mule sends a block of a smaller size to the record processors. Such a case can occur, for example, if there are 1010 records and the block size is 100 because the modulo is 10, not 0. The block size setting provides a way to tune performance, which is affected by the size of records in each block and the maxConcurrency setting.

Max Concurrency

maxConcurrency

Property that sets the maximum level of parallelism to allow when processing record blocks within the component. The default is twice the number of cores available in the CPUs. The capacity of the system running the Mule instance also limits concurrency. Like the blockSize setting, this setting provides a way to tune performance.

Target

target

To use the payload received by a batch job instance in a component that is located after the Batch Job component, you can provide a unique value for the target and use payload in the downstream component to gain access that payload. Without a target value, the input payload to the Batch Job component is not available in downstream components. For more information about target variables, see Enrich Data with Target Variables. There is no default value.

### Batch Job History () A batch job history configuration enables you to address a `No space left on device` error by adjusting the amount of time that historical data for batch job instances persist in a temporary Mule directory. This error can occur if the frequency or number of records to process is too high for the available disk space or for a CloudHub worker of a given size to handle. By default, the history of batch job instances persists for 7 days. A monitoring process automatically removes that history when the period expires. ![Batch job history fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/batch-job-fields-history-studio.png) The following table describes each field and includes the XML attribute for the field.
NameXMLDescription

Max Age

maxAge

Maximum age of job instances before they expire, for example: expiration maxAge="10". Default: maxAge=7.

Time Unit

ageUnit

The unit of time to apply to the maxAge. Valid values: DAYS, HOURS, MILLISECONDS, MINUTES, and SECONDS. Default: ageUnit=DAYS.

Note that these fields are attributes to the `` element, which is embedded within ``: ```xml ``` The XML example is edited to focus on settings in the batch history fields. ## Batch Step Component () The Batch Step component runs during the [Process phase](https://docs.mulesoft.com/mule-runtime/latest/batch-phases#phase_process) of a batch job instance, not during the Load and Dispatch or On Complete phases. A minimum of one Batch Step component is required within a Batch Job component. In addition to changing the name of a Batch Step component, you can configure _filters_ that determine which records the component accepts for processing within the component. Any processors that you add to the component act on records that the Batch Job component accepts. ![Batch job general fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/batch-step-fields-studio.png) The following table describes each field and includes the XML attribute for the field.
Field NameXMLDescription

Name

name

Configurable name for a Batch Step component. The default is Batch_Step for the first Batch Step component within a Batch Job component. Subsequent steps append a unique number to the name, following the sequence, Batch_Step1, Batch_Step2, and so on.

Accept Expression

acceptExpression

Optional DataWeave expression for a filter that determines whether to process a record in the component. If both the acceptExpression and the acceptPolicy values for a record evaluate to true, then the component accepts the record for processing. If not, the component skips the record, and the record becomes available to any downstream Batch Step components. Examples:

  • acceptExpression="#[payload.age > 21]" for a payload with an age field

  • acceptExpression="#[not isBlank(payload.name)]" for a payload with a name field.

Accept Policy

acceptPolicy

Accepts a record for processing only if the policy evaluates to true for that record. You can base acceptance on the success or failure of a record to process successfully in preceding (upstream) Batch Step components within the Batch Job component. You can configure the component to process only records that processed successfully, only records that failed to process successfully, or all records, regardless of whether they processed successfully. The default is NO_FAILURES. Note that the acceptPolicy evaluates before any acceptExpression on the component, and the maxFailedRecords setting on the Batch Job component takes precedence over acceptPolicy settings.

  • NO_FAILURES: Default setting. Accepts a record for processing if the record never failed to process successfully within a preceding Batch Step component or if there is no upstream Batch Step component.

  • ONLY_FAILURES: Accepts a record for processing if the record failed to process successfully within a preceding Batch Step component.

  • ALL: Accepts a record for processing regardless of processing successfully or failing within a preceding Batch Step component.

## Batch Aggregator Component () The Batch Aggregator component is an optional component that acts on an array of records. Aggregation takes place during the [Process phase](https://docs.mulesoft.com/mule-runtime/latest/batch-phases#phase_process) of a batch job instance. There is no default configuration for the Batch Aggregator component. If you use this component, you must indicate whether to stream records (`streaming`) or pull records from the queue into separate arrays of a fixed size (`size`), but not both. The settings are mutually exclusive. Random access to streamed records is not possible. The Batch Aggregator component accepts one or more processors for the message `payload`. However, it is common to use a scope within the aggregator, such as [For Each](https://docs.mulesoft.com/mule-runtime/latest/for-each-scope-concept) scope, to iterate over each record so that the child processors within the scope can act on each record individually. The Batch Aggregator component also provides a way preserve the MIME type of records (`preserveMimeTypes`), which is needed when accessing part of a record that you are aggregating as a fixed size (`size`). See [Preserving the MIME types of the Aggregated Records](https://docs.mulesoft.com/mule-runtime/latest/batch-filters-and-batch-aggregator#preserving-the-mime-types-of-the-aggregated-records). To learn about record processing within this component, see batch aggregation information in [Process Phase](https://docs.mulesoft.com/mule-runtime/latest/batch-phases#batch_aggregator_processing). Note that some connectors, such as [Anypoint Connector for Salesforce (Salesforce Connector)](https://docs.mulesoft.com/salesforce-connector/latest/salesforce-connector-reference#upsert) and [Anypoint Connector for NetSuite (NetSuite Connector)](https://docs.mulesoft.com/netsuite-connector/latest/netsuite-reference#upsert), provide operations that can handle record-level errors without causing the batch aggregation process to fail. When using Batch Aggregators, consider the following limitations: - When using a Batch Aggregator component, do not attempt to process Guava data types, such as `ImmutableMap`. Instead, use a Java `Map` to avoid serialization issues. - The Batch Aggregator component does not support job-instance-wide [transactions](https://docs.mulesoft.com/mule-runtime/latest/transaction-management). Within a Batch Step component, you can define a transaction that processes each record in a separate transaction. However, any transaction started by a Batch Step component ends before the Batch Aggregator component starts processing. Components cannot share a transaction because a transaction cannot cross the boundary between the components. ![Batch Aggregator component fields in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/batch-aggregator-fields-studio.png) The following table describes each field and includes the XML element for the field.
Field NameXMLDescription

Display Name

doc:name

Configurable name for the component. Example: doc:name="My Aggregator". The default name is Batch Aggregator.

Aggregator Size

size

Size of each array of records to process. There is no default size. The processor within the component must accept an array as input. The component continues pulling records from the batch stepping queue into arrays of the configured size until none are left. If the queue contains fewer records than the configured size, the component pulls those records into a smaller array for processing. You must set the Size (size) or Streaming (streaming) property but not both.

When using this configuration, the component does not wait for the Batch Step component to finish processing all records in an instance or batch. Once the set number of records is available in the stepping queue, the Batch Aggregator component pulls those records into an array and processes them.

Streaming

streaming

When streaming=true, the component acts on all records in a batch job instance and returns the results in an array of a size equal to the number of records in the instance. The batch size setting through the Batch Job component does not limit the number of records to process or return in the array. For example, assume that the aggregator returns the numeric IDs of a small batch job instance that processes only ten records of the form {"id": 1}, {"id": 2}, and so on. In this case, the output array for the instance contains ten IDs, such as [1, 6, 2, 7, 3, 8, 4, 9, 5, 10], even if the blockSize on the Batch Job component is set to a number smaller than the number of records in the instance, such as 5.

Processors can gain sequential access to the array of streamed records. Random access to the streamed records is not allowed because the aggregator does not preserve the processed records.

There is no default. You must set the Size (size) or Streaming (streaming) property but not both.

Preserve Mime Types

preserveMimeTypes

Defaults to false. To preserve the MIME type of records processed within this component, set this attribute to true. Processors that cannot determine the MIME type of data return output, such as null, or unreadable references to the payload, such as [[B@e596d5c, [B@1c4c3b32], …​]. Setting preserveMimeTypes=true is useful when this component is set to process a fixed number (size) of records.

When deciding whether to stream aggregated records, consider the following: - SaaS providers often have restrictions on accepting streaming input. - Batch streaming is often useful in batch processing when writing to a file such as CSV, JSON, or XML. - Batch streaming affects the performance of your application because the array of records is stored in RAM, which can slow the pace of transaction processing. Though performance slows, the trade-off of streaming data can warrant its use. - Streaming prevents random access to records because a streaming commit is a one-read, forward-only iterator. However, you can perform random access operations when streaming if you use a component like [For Each](https://docs.mulesoft.com/mule-runtime/latest/for-each-scope-concept). For Each provides a separate array of records, which is accessible through its `records` variable. --- product: Mule Runtime version: 4.11 --- # Batch Errors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When a Mule app processes records through batch steps, record-level failures result in a `BatchError` object associated with the failed record. You can use DataWeave functions and selector expressions to inspect error details such as description, type, and stack trace. Starting with Mule 4.11, batch record errors replace exception-based tracking and wrap [Mule error](https://docs.mulesoft.com/mule-runtime/4.11/mule-error-concept) objects with enhanced error data. ## Accessing Batch Errors Within a batch step, you can access record errors using these DataWeave functions:
DataWeave FunctionDescription

#[Batch::failureErrorForStep(String)]

Receives the name of a step as a String argument. Returns the BatchError object if the current record failed on that step. Otherwise, returns null.

#[Batch::getStepErrors()]

Returns a Map<String, BatchError> where keys are batch step names where the current record failed, and values are the corresponding errors.
If the record hasn’t failed in any step, returns an empty map (never null). The map doesn’t contain entries for steps in which the record hasn’t failed.

#[Batch::getFirstError()]

Returns the BatchError object for the first step in which the current record has failed. If the record hasn’t failed in any step, returns null.

#[Batch::getLastError()]

Returns the BatchError object for the last step in which the current record failed. Otherwise, returns null.

## Selector Expressions for Batch Errors Batch errors are complex data types with several fields, such as a description and type. When logging and handling batch errors, you can select values from any of these fields. This table shows selector expressions for the first step in which the current record failed:
FieldDescriptionSelector Expression

Description

A description of the problem.

#[Batch::getFirstError().description]

Detailed Description

A description of the problem, which can be the same or more extensive than the description field.

#[Batch::getFirstError().detailedDescription]

Type

A type that characterizes the problem and allows for routing within an error handler.

#[Batch::getFirstError().errorType]

Failing Component

The component where the error is generated.

#[Batch::getFirstError().failingComponent]

DSL Source

The DSL source of the component where the error is generated.

#[Batch::getFirstError().dslSource]

Error Message

An optional Mule message with error data (for example, HTTP response content for invalid status codes).

#[Batch::getFirstError().errorMessage]

Child Errors

An optional collection of inner errors, used by elements like Scatter-Gather to provide aggregated route errors.

#[Batch::getFirstError().childErrors]

Failure During Handling

Any error that occurs while handling this error.

#[Batch::getFirstError().failureDuringHandling]

Stack Trace

The Java stack trace of the exception.

#[Batch::getFirstError().stackTrace]

## Batch Error Types Batch errors follow the same error type hierarchy as standard Mule errors. A special `MULE:BATCH` error type exists for errors that arise during internal batch processing (rather than chain execution) and don’t belong to any specific type. ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.11/mule-error-concept) - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.11/batch-processing-concept) --- product: Mule Runtime version: 4.12 --- # Batch Errors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When a Mule app processes records through batch steps, record-level failures result in a `BatchError` object associated with the failed record. You can use DataWeave functions and selector expressions to inspect error details such as description, type, and stack trace. Starting with Mule 4.11, batch record errors replace exception-based tracking and wrap [Mule error](https://docs.mulesoft.com/mule-runtime/4.12/mule-error-concept) objects with enhanced error data. ## Accessing Batch Errors Within a batch step, you can access record errors using these DataWeave functions:
DataWeave FunctionDescription

#[Batch::failureErrorForStep(String)]

Receives the name of a step as a String argument. Returns the BatchError object if the current record failed on that step. Otherwise, returns null.

#[Batch::getStepErrors()]

Returns a Map<String, BatchError> where keys are batch step names where the current record failed, and values are the corresponding errors.
If the record hasn’t failed in any step, returns an empty map (never null). The map doesn’t contain entries for steps in which the record hasn’t failed.

#[Batch::getFirstError()]

Returns the BatchError object for the first step in which the current record has failed. If the record hasn’t failed in any step, returns null.

#[Batch::getLastError()]

Returns the BatchError object for the last step in which the current record failed. Otherwise, returns null.

## Selector Expressions for Batch Errors Batch errors are complex data types with several fields, such as a description and type. When logging and handling batch errors, you can select values from any of these fields. This table shows selector expressions for the first step in which the current record failed:
FieldDescriptionSelector Expression

Description

A description of the problem.

#[Batch::getFirstError().description]

Detailed Description

A description of the problem, which can be the same or more extensive than the description field.

#[Batch::getFirstError().detailedDescription]

Type

A type that characterizes the problem and allows for routing within an error handler.

#[Batch::getFirstError().errorType]

Failing Component

The component where the error is generated.

#[Batch::getFirstError().failingComponent]

DSL Source

The DSL source of the component where the error is generated.

#[Batch::getFirstError().dslSource]

Error Message

An optional Mule message with error data (for example, HTTP response content for invalid status codes).

#[Batch::getFirstError().errorMessage]

Child Errors

An optional collection of inner errors, used by elements like Scatter-Gather to provide aggregated route errors.

#[Batch::getFirstError().childErrors]

Failure During Handling

Any error that occurs while handling this error.

#[Batch::getFirstError().failureDuringHandling]

Stack Trace

The Java stack trace of the exception.

#[Batch::getFirstError().stackTrace]

## Batch Error Types Batch errors follow the same error type hierarchy as standard Mule errors. A special `MULE:BATCH` error type exists for errors that arise during internal batch processing (rather than chain execution) and don’t belong to any specific type. ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.12/mule-error-concept) - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.12/batch-processing-concept) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Batch Errors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When a Mule app processes records through batch steps, record-level failures result in a `BatchError` object associated with the failed record. You can use DataWeave functions and selector expressions to inspect error details such as description, type, and stack trace. Starting with Mule 4.11, batch record errors replace exception-based tracking and wrap [Mule error](https://docs.mulesoft.com/mule-runtime/latest/mule-error-concept) objects with enhanced error data. ## Accessing Batch Errors Within a batch step, you can access record errors using these DataWeave functions:
DataWeave FunctionDescription

#[Batch::failureErrorForStep(String)]

Receives the name of a step as a String argument. Returns the BatchError object if the current record failed on that step. Otherwise, returns null.

#[Batch::getStepErrors()]

Returns a Map<String, BatchError> where keys are batch step names where the current record failed, and values are the corresponding errors.
If the record hasn’t failed in any step, returns an empty map (never null). The map doesn’t contain entries for steps in which the record hasn’t failed.

#[Batch::getFirstError()]

Returns the BatchError object for the first step in which the current record has failed. If the record hasn’t failed in any step, returns null.

#[Batch::getLastError()]

Returns the BatchError object for the last step in which the current record failed. Otherwise, returns null.

## Selector Expressions for Batch Errors Batch errors are complex data types with several fields, such as a description and type. When logging and handling batch errors, you can select values from any of these fields. This table shows selector expressions for the first step in which the current record failed:
FieldDescriptionSelector Expression

Description

A description of the problem.

#[Batch::getFirstError().description]

Detailed Description

A description of the problem, which can be the same or more extensive than the description field.

#[Batch::getFirstError().detailedDescription]

Type

A type that characterizes the problem and allows for routing within an error handler.

#[Batch::getFirstError().errorType]

Failing Component

The component where the error is generated.

#[Batch::getFirstError().failingComponent]

DSL Source

The DSL source of the component where the error is generated.

#[Batch::getFirstError().dslSource]

Error Message

An optional Mule message with error data (for example, HTTP response content for invalid status codes).

#[Batch::getFirstError().errorMessage]

Child Errors

An optional collection of inner errors, used by elements like Scatter-Gather to provide aggregated route errors.

#[Batch::getFirstError().childErrors]

Failure During Handling

Any error that occurs while handling this error.

#[Batch::getFirstError().failureDuringHandling]

Stack Trace

The Java stack trace of the exception.

#[Batch::getFirstError().stackTrace]

## Batch Error Types Batch errors follow the same error type hierarchy as standard Mule errors. A special `MULE:BATCH` error type exists for errors that arise during internal batch processing (rather than chain execution) and don’t belong to any specific type. ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/latest/mule-error-concept) - [Batch Processing](https://docs.mulesoft.com/mule-runtime/latest/batch-processing-concept) --- product: Mule Runtime version: 4.11 keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Job Instance ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Users of batch processing frequently need the ability to determine a Batch job’s instance ID during the execution phases of a Batch job. The Batch job instance ID is useful to: - Pass the local job instance ID to an external system for referencing and managing data - Improve the job’s custom logging - Send email or SMS notifications for meaningful events ## Example Mule exposes the batch job instance ID through a flow variable of key `batchJobInstanceId`. That flow variable is available at the beginning of the input phase. The flow variable is also available in every step and in the on-complete phase. ![A batch processing component showing a job instance ID in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/batch-job-instance-id-c4362.png) The log output produces the following: ```text com.mulesoft.mule.runtime.module.batch.internal.engine.DefaultBatchEngine: Created instance '7dc5cad0-ab09-11e8-a790-9801a7b055d3' for batch job 'CreateLeadsBatch' ``` ## Custom Batch Job Instance ID You can use a DataWeave expression to specify a unique identifier for each batch job by passing a **Job Instance Id** attribute that takes a DW expression. Note that constant values are not allowed for batch jobs and if the DW expression returns a previously seen value, Mule throws an exception and does not create the job instance. If you don’t set a job instance ID, Mule auto generates a UUID to assign to your instance. The UUID generated for the job instance described above is `ba01e1a0-f5c7-11e4-9414-10ddb1daeb6d`. As you can tell, it’s not a human readable identifier making it hard to correlate to an actual execution and considering you could be running multiple jobs at the same time, this ID is not meaningful at all. To guarantee uniqueness, you can define the Job Id as the server’s current date by using the following DataWeave expression: `#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}]`. This names the execution instance `Job From 15/01/16 05:23:12`. ```text com.mulesoft.module.batch.engine.DefaultBatchEngine: Created instance Job From 15/01/16 05:23:12 for batch job contacts-to-SFDCBatch com.mulesoft.module.batch.engine.DefaultBatchEngine: Starting input phase com.mulesoft.module.batch.engine.DefaultBatchEngine: Input phase completed com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Starting loading phase for instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Finished loading phase for instance Job From 15/01/16 05:23:12 of job contacts-to-SFDCBatch. 3 records were loaded com.mulesoft.module.batch.engine.DefaultBatchEngine: Started execution of instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' ``` The logs of a properly identified instance are easier to read. ```xml ... ... ... ``` ## See Also - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.11/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.12 keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Job Instance ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Users of batch processing frequently need the ability to determine a Batch job’s instance ID during the execution phases of a Batch job. The Batch job instance ID is useful to: - Pass the local job instance ID to an external system for referencing and managing data - Improve the job’s custom logging - Send email or SMS notifications for meaningful events ## Example Mule exposes the batch job instance ID through a flow variable of key `batchJobInstanceId`. That flow variable is available at the beginning of the input phase. The flow variable is also available in every step and in the on-complete phase. ![A batch processing component showing a job instance ID in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/batch-job-instance-id-c4362.png) The log output produces the following: ```text com.mulesoft.mule.runtime.module.batch.internal.engine.DefaultBatchEngine: Created instance '7dc5cad0-ab09-11e8-a790-9801a7b055d3' for batch job 'CreateLeadsBatch' ``` ## Custom Batch Job Instance ID You can use a DataWeave expression to specify a unique identifier for each batch job by passing a **Job Instance Id** attribute that takes a DW expression. Note that constant values are not allowed for batch jobs and if the DW expression returns a previously seen value, Mule throws an exception and does not create the job instance. If you don’t set a job instance ID, Mule auto generates a UUID to assign to your instance. The UUID generated for the job instance described above is `ba01e1a0-f5c7-11e4-9414-10ddb1daeb6d`. As you can tell, it’s not a human readable identifier making it hard to correlate to an actual execution and considering you could be running multiple jobs at the same time, this ID is not meaningful at all. To guarantee uniqueness, you can define the Job Id as the server’s current date by using the following DataWeave expression: `#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}]`. This names the execution instance `Job From 15/01/16 05:23:12`. ```text com.mulesoft.module.batch.engine.DefaultBatchEngine: Created instance Job From 15/01/16 05:23:12 for batch job contacts-to-SFDCBatch com.mulesoft.module.batch.engine.DefaultBatchEngine: Starting input phase com.mulesoft.module.batch.engine.DefaultBatchEngine: Input phase completed com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Starting loading phase for instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Finished loading phase for instance Job From 15/01/16 05:23:12 of job contacts-to-SFDCBatch. 3 records were loaded com.mulesoft.module.batch.engine.DefaultBatchEngine: Started execution of instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' ``` The logs of a properly identified instance are easier to read. ```xml ... ... ... ``` ## See Also - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.12/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.3 keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Job Instance ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Users of batch processing frequently need the ability to determine a Batch job’s instance ID during the execution phases of a Batch job. The Batch job instance ID is useful to: - Pass the local job instance ID to an external system for referencing and managing data - Improve the job’s custom logging - Send email or SMS notifications for meaningful events ## Example Mule exposes the batch job instance ID through a flow variable of key `batchJobInstanceId`. That flow variable is available at the beginning of the input phase. The flow variable is also available in every step and in the on-complete phase. ![batch job instance id c4362](/mulesoft/current/en-us/mule-runtime/4.3/_images/batch-job-instance-id-c4362.png) The log output produces the following: ```text com.mulesoft.mule.runtime.module.batch.internal.engine.DefaultBatchEngine: Created instance '7dc5cad0-ab09-11e8-a790-9801a7b055d3' for batch job 'CreateLeadsBatch' ``` ## Custom Batch Job Instance ID You can use a DataWeave expression to specify a unique identifier for each batch job by passing a **Job Instance Id** attribute that takes a DW expression. Note that constant values are not allowed for batch jobs and if the DW expression returns a previously seen value, Mule throws an exception and does not create the job instance. If you don’t set a job instance ID, Mule auto generates a UUID to assign to your instance. The UUID generated for the job instance described above is `ba01e1a0-f5c7-11e4-9414-10ddb1daeb6d`. As you can tell, it’s not a human readable identifier making it hard to correlate to an actual execution and considering you could be running multiple jobs at the same time, this ID is not meaningful at all. To guarantee uniqueness, you can define the Job Id as the server’s current date by using the following DataWeave expression: `#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}]`. This names the execution instance `Job From 15/01/16 05:23:12`. ```text com.mulesoft.module.batch.engine.DefaultBatchEngine: Created instance Job From 15/01/16 05:23:12 for batch job contacts-to-SFDCBatch com.mulesoft.module.batch.engine.DefaultBatchEngine: Starting input phase com.mulesoft.module.batch.engine.DefaultBatchEngine: Input phase completed com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Starting loading phase for instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Finished loading phase for instance Job From 15/01/16 05:23:12 of job contacts-to-SFDCBatch. 3 records were loaded com.mulesoft.module.batch.engine.DefaultBatchEngine: Started execution of instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' ``` The logs of a properly identified instance are easier to read. ```xml ... ... ... ``` ## See Also - [Refining Batch Steps Processing](https://docs.mulesoft.com/mule-runtime/4.3/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.4 keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Job Instance ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Users of batch processing frequently need the ability to determine a Batch job’s instance ID during the execution phases of a Batch job. The Batch job instance ID is useful to: - Pass the local job instance ID to an external system for referencing and managing data - Improve the job’s custom logging - Send email or SMS notifications for meaningful events ## Example Mule exposes the batch job instance ID through a flow variable of key `batchJobInstanceId`. That flow variable is available at the beginning of the input phase. The flow variable is also available in every step and in the on-complete phase. ![batch job instance id c4362](/mulesoft/current/en-us/mule-runtime/4.4/_images/batch-job-instance-id-c4362.png) The log output produces the following: ```text com.mulesoft.mule.runtime.module.batch.internal.engine.DefaultBatchEngine: Created instance '7dc5cad0-ab09-11e8-a790-9801a7b055d3' for batch job 'CreateLeadsBatch' ``` ## Custom Batch Job Instance ID You can use a DataWeave expression to specify a unique identifier for each batch job by passing a **Job Instance Id** attribute that takes a DW expression. Note that constant values are not allowed for batch jobs and if the DW expression returns a previously seen value, Mule throws an exception and does not create the job instance. If you don’t set a job instance ID, Mule auto generates a UUID to assign to your instance. The UUID generated for the job instance described above is `ba01e1a0-f5c7-11e4-9414-10ddb1daeb6d`. As you can tell, it’s not a human readable identifier making it hard to correlate to an actual execution and considering you could be running multiple jobs at the same time, this ID is not meaningful at all. To guarantee uniqueness, you can define the Job Id as the server’s current date by using the following DataWeave expression: `#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}]`. This names the execution instance `Job From 15/01/16 05:23:12`. ```text com.mulesoft.module.batch.engine.DefaultBatchEngine: Created instance Job From 15/01/16 05:23:12 for batch job contacts-to-SFDCBatch com.mulesoft.module.batch.engine.DefaultBatchEngine: Starting input phase com.mulesoft.module.batch.engine.DefaultBatchEngine: Input phase completed com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Starting loading phase for instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Finished loading phase for instance Job From 15/01/16 05:23:12 of job contacts-to-SFDCBatch. 3 records were loaded com.mulesoft.module.batch.engine.DefaultBatchEngine: Started execution of instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' ``` The logs of a properly identified instance are easier to read. ```xml ... ... ... ``` ## See Also - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.4/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.6 keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Job Instance ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Users of batch processing frequently need the ability to determine a Batch job’s instance ID during the execution phases of a Batch job. The Batch job instance ID is useful to: - Pass the local job instance ID to an external system for referencing and managing data - Improve the job’s custom logging - Send email or SMS notifications for meaningful events ## Example Mule exposes the batch job instance ID through a flow variable of key `batchJobInstanceId`. That flow variable is available at the beginning of the input phase. The flow variable is also available in every step and in the on-complete phase. ![batch job instance id c4362](/mulesoft/current/en-us/mule-runtime/4.6/_images/batch-job-instance-id-c4362.png) The log output produces the following: ```text com.mulesoft.mule.runtime.module.batch.internal.engine.DefaultBatchEngine: Created instance '7dc5cad0-ab09-11e8-a790-9801a7b055d3' for batch job 'CreateLeadsBatch' ``` ## Custom Batch Job Instance ID You can use a DataWeave expression to specify a unique identifier for each batch job by passing a **Job Instance Id** attribute that takes a DW expression. Note that constant values are not allowed for batch jobs and if the DW expression returns a previously seen value, Mule throws an exception and does not create the job instance. If you don’t set a job instance ID, Mule auto generates a UUID to assign to your instance. The UUID generated for the job instance described above is `ba01e1a0-f5c7-11e4-9414-10ddb1daeb6d`. As you can tell, it’s not a human readable identifier making it hard to correlate to an actual execution and considering you could be running multiple jobs at the same time, this ID is not meaningful at all. To guarantee uniqueness, you can define the Job Id as the server’s current date by using the following DataWeave expression: `#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}]`. This names the execution instance `Job From 15/01/16 05:23:12`. ```text com.mulesoft.module.batch.engine.DefaultBatchEngine: Created instance Job From 15/01/16 05:23:12 for batch job contacts-to-SFDCBatch com.mulesoft.module.batch.engine.DefaultBatchEngine: Starting input phase com.mulesoft.module.batch.engine.DefaultBatchEngine: Input phase completed com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Starting loading phase for instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Finished loading phase for instance Job From 15/01/16 05:23:12 of job contacts-to-SFDCBatch. 3 records were loaded com.mulesoft.module.batch.engine.DefaultBatchEngine: Started execution of instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' ``` The logs of a properly identified instance are easier to read. ```xml ... ... ... ``` ## See Also - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.6/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.9 keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Job Instance ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Users of batch processing frequently need the ability to determine a Batch job’s instance ID during the execution phases of a Batch job. The Batch job instance ID is useful to: - Pass the local job instance ID to an external system for referencing and managing data - Improve the job’s custom logging - Send email or SMS notifications for meaningful events ## Example Mule exposes the batch job instance ID through a flow variable of key `batchJobInstanceId`. That flow variable is available at the beginning of the input phase. The flow variable is also available in every step and in the on-complete phase. ![A batch processing component showing a job instance ID in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/batch-job-instance-id-c4362.png) The log output produces the following: ```text com.mulesoft.mule.runtime.module.batch.internal.engine.DefaultBatchEngine: Created instance '7dc5cad0-ab09-11e8-a790-9801a7b055d3' for batch job 'CreateLeadsBatch' ``` ## Custom Batch Job Instance ID You can use a DataWeave expression to specify a unique identifier for each batch job by passing a **Job Instance Id** attribute that takes a DW expression. Note that constant values are not allowed for batch jobs and if the DW expression returns a previously seen value, Mule throws an exception and does not create the job instance. If you don’t set a job instance ID, Mule auto generates a UUID to assign to your instance. The UUID generated for the job instance described above is `ba01e1a0-f5c7-11e4-9414-10ddb1daeb6d`. As you can tell, it’s not a human readable identifier making it hard to correlate to an actual execution and considering you could be running multiple jobs at the same time, this ID is not meaningful at all. To guarantee uniqueness, you can define the Job Id as the server’s current date by using the following DataWeave expression: `#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}]`. This names the execution instance `Job From 15/01/16 05:23:12`. ```text com.mulesoft.module.batch.engine.DefaultBatchEngine: Created instance Job From 15/01/16 05:23:12 for batch job contacts-to-SFDCBatch com.mulesoft.module.batch.engine.DefaultBatchEngine: Starting input phase com.mulesoft.module.batch.engine.DefaultBatchEngine: Input phase completed com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Starting loading phase for instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Finished loading phase for instance Job From 15/01/16 05:23:12 of job contacts-to-SFDCBatch. 3 records were loaded com.mulesoft.module.batch.engine.DefaultBatchEngine: Started execution of instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' ``` The logs of a properly identified instance are easier to read. ```xml ... ... ... ``` ## See Also - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.9/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Job Instance ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Users of batch processing frequently need the ability to determine a Batch job’s instance ID during the execution phases of a Batch job. The Batch job instance ID is useful to: - Pass the local job instance ID to an external system for referencing and managing data - Improve the job’s custom logging - Send email or SMS notifications for meaningful events ## Example Mule exposes the batch job instance ID through a flow variable of key `batchJobInstanceId`. That flow variable is available at the beginning of the input phase. The flow variable is also available in every step and in the on-complete phase. ![A batch processing component showing a job instance ID in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/batch-job-instance-id-c4362.png) The log output produces the following: ```text com.mulesoft.mule.runtime.module.batch.internal.engine.DefaultBatchEngine: Created instance '7dc5cad0-ab09-11e8-a790-9801a7b055d3' for batch job 'CreateLeadsBatch' ``` ## Custom Batch Job Instance ID You can use a DataWeave expression to specify a unique identifier for each batch job by passing a **Job Instance Id** attribute that takes a DW expression. Note that constant values are not allowed for batch jobs and if the DW expression returns a previously seen value, Mule throws an exception and does not create the job instance. If you don’t set a job instance ID, Mule auto generates a UUID to assign to your instance. The UUID generated for the job instance described above is `ba01e1a0-f5c7-11e4-9414-10ddb1daeb6d`. As you can tell, it’s not a human readable identifier making it hard to correlate to an actual execution and considering you could be running multiple jobs at the same time, this ID is not meaningful at all. To guarantee uniqueness, you can define the Job Id as the server’s current date by using the following DataWeave expression: `#['Job From ' ++ now() as String {format: 'dd/MM/yy hh:mm:ss'}]`. This names the execution instance `Job From 15/01/16 05:23:12`. ```text com.mulesoft.module.batch.engine.DefaultBatchEngine: Created instance Job From 15/01/16 05:23:12 for batch job contacts-to-SFDCBatch com.mulesoft.module.batch.engine.DefaultBatchEngine: Starting input phase com.mulesoft.module.batch.engine.DefaultBatchEngine: Input phase completed com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Starting loading phase for instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' com.mulesoft.module.batch.engine.queue.BatchQueueLoader: Finished loading phase for instance Job From 15/01/16 05:23:12 of job contacts-to-SFDCBatch. 3 records were loaded com.mulesoft.module.batch.engine.DefaultBatchEngine: Started execution of instance 'Job From 15/01/16 05:23:12' of job 'contacts-to-SFDCBatch' ``` The logs of a properly identified instance are easier to read. ```xml ... ... ... ``` ## See Also - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/latest/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.11 --- # Batch Job Performance Tuning > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) possesses the ability to process messages in batches. Within an application, you can initiate a batch job which is a block of code that splits large messages into individual records, performs actions upon each record, then reports on the results and potentially pushes the processed output to other systems or queues. Consider having 1 million records processed by a batch application with three steps. Several I/O operations occur as Mule processes each record as it moves through the job’s phases. The disk characteristics, along with the workload size, play a key role in the performance of the batch job, primarily because during the input phase, an in-disk queue is created of the list of records to be processed, which is constantly read and written by the flow, resulting in heavy I/O utilization. Additionally, batch processing requires having enough memory available to process the threads in parallel, which means moving the records from persistent storage into RAM in a fixed-size block. The larger your records and their quantity, the more available memory you need for batch processing. ## Batch Block Size By default, the batch block size is set to 100. It is a good balancing point between performance and working memory requirements based on analysis across a set of representative batch use cases with various record sizes. However, the optimal value for each application depends on its use case. You can configure this property for the batch job. If you believe that in your particular case, custom size is best suited, make sure to run comparative tests with different values to find the optimum size in your use case. The following example shows the batch block size: ```xml ``` ## Max Concurrency The maximum number of threads used for processing within a Batch scope defaults to 2 times the number of cores that the JVM detects. On fractional core deployments, such as CloudHub and Anypoint Runtime Fabric, the JVM detects a _non-fractional_ number of cores. You can manually increase or lower the automated concurrency setting. The Max Concurrency setting enables you to set an upper limit on the number of threads to use for a batch job instance that, for example, has insufficient records to warrant more threads. The following example overrides the automated `maxConcurrency` default to a setting that is loaded from a property: ```xml ``` ## Batch Aggregators One million round trips across a network impacts performance, whether on single or multiple threads. Communication with SaaS systems can easily consume the quota of API calls. Instead of processing records one by one, you can improve performance by using the Batch Aggregator scope to perform bulk operations on arrays of records. The scope uses an Aggregator Size setting to limit the number of records in each array. When determining the number of records to process in an array of records, you must take into account the maximum number of records permitted by operations on the system with which the communication takes place. It is important to conduct performance testing on your Aggregator Size setting _and on lower values_. Your logic must handle any number of records up to and including the value of your setting because the number of records that the system receives can be lower than your specified value. For example, if there are 120 records, and your Aggregator Size setting is 50, the last submission is 20 records. The following example shows a Batch Step scope with a Batch Aggregator scope that is set to a fixed size of `50`: ```xml ``` If the aggregator contains an operation that streams data, you can activate the scope’s Streaming option (`streaming="true"`) instead of using an Aggregator Size setting (`size="50"`). ## Multiple Concurrent Instances of a Batch Job Many use cases for Batch Job scopes process only one request (batch job instance) at a time, but some cases simultaneously execute two or more batch job instances. To tune the thread pool sharing in such cases, you can set one of these scheduling strategies, each of which is tracked separately by its batch instance ID: - `ORDERED_SEQUENTIAL`: Default scheduling strategy that limits the impact of concurrent instances by processing the instances in the order they are triggered. This strategy is useful if nonsequential processing of the same batch job can cause issues, such as data inconsistency, or when resource limitations are reached. - `ROUND_ROBIN`: Scheduling strategy that shares the threads with batch job instances that are "in flight". ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.11/batch-processing-concept) --- product: Mule Runtime version: 4.12 --- # Batch Job Performance Tuning > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) possesses the ability to process messages in batches. Within an application, you can initiate a batch job which is a block of code that splits large messages into individual records, performs actions upon each record, then reports on the results and potentially pushes the processed output to other systems or queues. Consider having 1 million records processed by a batch application with three steps. Several I/O operations occur as Mule processes each record as it moves through the job’s phases. The disk characteristics, along with the workload size, play a key role in the performance of the batch job, primarily because during the input phase, an in-disk queue is created of the list of records to be processed, which is constantly read and written by the flow, resulting in heavy I/O utilization. Additionally, batch processing requires having enough memory available to process the threads in parallel, which means moving the records from persistent storage into RAM in a fixed-size block. The larger your records and their quantity, the more available memory you need for batch processing. ## Batch Block Size By default, the batch block size is set to 100. It is a good balancing point between performance and working memory requirements based on analysis across a set of representative batch use cases with various record sizes. However, the optimal value for each application depends on its use case. You can configure this property for the batch job. If you believe that in your particular case, custom size is best suited, make sure to run comparative tests with different values to find the optimum size in your use case. The following example shows the batch block size: ```xml ``` ## Max Concurrency The maximum number of threads used for processing within a Batch scope defaults to 2 times the number of cores that the JVM detects. On fractional core deployments, such as CloudHub and Anypoint Runtime Fabric, the JVM detects a _non-fractional_ number of cores. You can manually increase or lower the automated concurrency setting. The Max Concurrency setting enables you to set an upper limit on the number of threads to use for a batch job instance that, for example, has insufficient records to warrant more threads. The following example overrides the automated `maxConcurrency` default to a setting that is loaded from a property: ```xml ``` ## Batch Aggregators One million round trips across a network impacts performance, whether on single or multiple threads. Communication with SaaS systems can easily consume the quota of API calls. Instead of processing records one by one, you can improve performance by using the Batch Aggregator scope to perform bulk operations on arrays of records. The scope uses an Aggregator Size setting to limit the number of records in each array. When determining the number of records to process in an array of records, you must take into account the maximum number of records permitted by operations on the system with which the communication takes place. It is important to conduct performance testing on your Aggregator Size setting _and on lower values_. Your logic must handle any number of records up to and including the value of your setting because the number of records that the system receives can be lower than your specified value. For example, if there are 120 records, and your Aggregator Size setting is 50, the last submission is 20 records. The following example shows a Batch Step scope with a Batch Aggregator scope that is set to a fixed size of `50`: ```xml ``` If the aggregator contains an operation that streams data, you can activate the scope’s Streaming option (`streaming="true"`) instead of using an Aggregator Size setting (`size="50"`). ## Multiple Concurrent Instances of a Batch Job Many use cases for Batch Job scopes process only one request (batch job instance) at a time, but some cases simultaneously execute two or more batch job instances. To tune the thread pool sharing in such cases, you can set one of these scheduling strategies, each of which is tracked separately by its batch instance ID: - `ORDERED_SEQUENTIAL`: Default scheduling strategy that limits the impact of concurrent instances by processing the instances in the order they are triggered. This strategy is useful if nonsequential processing of the same batch job can cause issues, such as data inconsistency, or when resource limitations are reached. - `ROUND_ROBIN`: Scheduling strategy that shares the threads with batch job instances that are "in flight". ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.12/batch-processing-concept) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Batch Job Performance Tuning > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) possesses the ability to process messages in batches. Within an application, you can initiate a batch job which is a block of code that splits large messages into individual records, performs actions upon each record, then reports on the results and potentially pushes the processed output to other systems or queues. Consider having 1 million records processed by a batch application with three steps. Several I/O operations occur as Mule processes each record as it moves through the job’s phases. The disk characteristics, along with the workload size, play a key role in the performance of the batch job, primarily because during the input phase, an in-disk queue is created of the list of records to be processed, which is constantly read and written by the flow, resulting in heavy I/O utilization. Additionally, batch processing requires having enough memory available to process the threads in parallel, which means moving the records from persistent storage into RAM in a fixed-size block. The larger your records and their quantity, the more available memory you need for batch processing. ## Batch Block Size By default, the batch block size is set to 100. It is a good balancing point between performance and working memory requirements based on analysis across a set of representative batch use cases with various record sizes. However, the optimal value for each application depends on its use case. You can configure this property for the batch job. If you believe that in your particular case, custom size is best suited, make sure to run comparative tests with different values to find the optimum size in your use case. The following example shows the batch block size: ```xml ``` ## Max Concurrency The maximum number of threads used for processing within a Batch scope defaults to 2 times the number of cores that the JVM detects. On fractional core deployments, such as CloudHub and Anypoint Runtime Fabric, the JVM detects a _non-fractional_ number of cores. You can manually increase or lower the automated concurrency setting. The Max Concurrency setting enables you to set an upper limit on the number of threads to use for a batch job instance that, for example, has insufficient records to warrant more threads. The following example overrides the automated `maxConcurrency` default to a setting that is loaded from a property: ```xml ``` ## Batch Aggregators One million round trips across a network impacts performance, whether on single or multiple threads. Communication with SaaS systems can easily consume the quota of API calls. Instead of processing records one by one, you can improve performance by using the Batch Aggregator scope to perform bulk operations on arrays of records. The scope uses an Aggregator Size setting to limit the number of records in each array. When determining the number of records to process in an array of records, you must take into account the maximum number of records permitted by operations on the system with which the communication takes place. It is important to conduct performance testing on your Aggregator Size setting _and on lower values_. Your logic must handle any number of records up to and including the value of your setting because the number of records that the system receives can be lower than your specified value. For example, if there are 120 records, and your Aggregator Size setting is 50, the last submission is 20 records. The following example shows a Batch Step scope with a Batch Aggregator scope that is set to a fixed size of `50`: ```xml ``` If the aggregator contains an operation that streams data, you can activate the scope’s Streaming option (`streaming="true"`) instead of using an Aggregator Size setting (`size="50"`). ## Multiple Concurrent Instances of a Batch Job Many use cases for Batch Job scopes process only one request (batch job instance) at a time, but some cases simultaneously execute two or more batch job instances. To tune the thread pool sharing in such cases, you can set one of these scheduling strategies, each of which is tracked separately by its batch instance ID: - `ORDERED_SEQUENTIAL`: Default scheduling strategy that limits the impact of concurrent instances by processing the instances in the order they are triggered. This strategy is useful if nonsequential processing of the same batch job can cause issues, such as data inconsistency, or when resource limitations are reached. - `ROUND_ROBIN`: Scheduling strategy that shares the threads with batch job instances that are "in flight". ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/latest/batch-processing-concept) --- product: Mule Runtime version: 4.11 --- # Batch Job Phases > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Each time a Batch Job component executes, it goes through these phases: 1. [Load and Dispatch Phase](#phase_load_dispatch): The Batch Job component splits [valid input](https://docs.mulesoft.com/mule-runtime/4.11/batch-processing-concept#valid_input) into records and prepares the records for processing. This phase takes place within the Batch Job component. 2. [Process Phase](#phase_process): Mule components and connector operations within one or more Batch Step components in the Batch Job process records within a given batch job instance. Processing within a Batch Aggregator component also occurs in the Process phase. 3. [On Complete Phase](#phase_on_complete): The Batch Job component issues a report object with the result of processing the batch job instance. For an example, see [batch phase XML](https://docs.mulesoft.com/mule-runtime/4.11/batch-processing-concept#batch_phases_xml). ## Load and Dispatch Phase When an upstream event in the flow triggers the Batch Job component, the Load and Dispatch phase begins. In this phase, these actions occur: 1. Mule creates a new batch job instance that persists through each phase of a batch job. Within the scope of the Batch Job component, Mule exposes the currently processing batch job instance ID through the `batchJobInstanceId` variable. You can use `vars.batchJobInstanceId` to access the identifier of the current instance in any batch processing phase. The auto-generated identifier is a UUID, but you can change it to a different value. For details, see [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/4.11/batch-job-instance-id). 2. The Batch Job component automatically splits the received message payload into records and stores the records in the stepping queue. The Batch Job component either successfully generates and queues a record for every item from the input, or the entire event fails with an error type, such as `MULE:EXPRESSION` message, and an error message, such as `"Expecting Array or Object but got String." evaluating expression: "payload".` In Anypoint Runtime Manager, the queue name is prefixed with `BSQ`, for example: ![A batch step queue transaction log in Anypoint Runtime Manager](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-batch-bsq.png) 3. The Batch Job component starts the execution of a batch job instance that processes the loaded records. ## Process Phase The Process phase begins after the Load and Dispatch phase finishes loading records to the queue and starts execution of a batch job instance. In this phase, Batch Step components concurrently pull record blocks of the configured size from the queue to process them. (The default batch block size is 100.) Within the Batch Step component, Mule processes multiple record blocks in parallel by using separate threads, while the records within each block process sequentially by default. Mule uses its auto-tuning capabilities to determine how many threads to use and the level of parallelism to apply (see [Execution Engine](https://docs.mulesoft.com/mule-runtime/4.11/execution-engine)). During this phase, processors within the components can access and modify records using the `payload` and `vars` Mule variables. The Batch Job component consumes records after all record processing finishes. So any transmission of _processed_ records to an external server or service must take place _within_ the Batch Step or Batch Aggregator components. For Mule variable propagation rules, see [Variable Propagation](https://docs.mulesoft.com/mule-runtime/4.11/batch-processing-concept#variable_propagation). After processing records in a block, the Batch Step sends the records back to the stepping queue, where they become available for the next Batch Step component. The next Batch Step doesn’t wait for the previous step to complete. It starts processing available records as soon as they return to the queue. Records are pulled from the queue in blocks, but the composition of these blocks can differ from the previous step because records from different parallel threads are mixed in the queue. At the end of this phase, all records are consumed and aren’t available for further processing by downstream processors in the Mule flow. Note that since changes to records that take place within a Batch Aggregator component _aren’t propagated_ outside of Batch Aggregator component, changes aren’t visible to subsequent Batch Step components in the flow. ![A batch job instance with a record stepping queue for multiple batch steps](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-batch-step-process.png) As processing takes place, each record keeps track of all Batch Step components that process it. By default, a batch job instance doesn’t wait for all its queued records to finish processing in one Batch Step component before making them available for processing by the next Batch Step component. Configuring a Batch Aggregator component changes this behavior: - Behavior when the Batch Aggregator component sets a fixed size: A processor within the Batch Aggregator must be able to receive the array of records as input. ![A batch job process with a fixed-size aggregator](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-batch-job-process-aggregator-fixed.png)
1Each Batch Step component within a Batch Job component receives one or more record blocks and starts processing them in parallel.
2After processing a record, the Batch Step component sends the record to the Batch Aggregator component for further processing.
3When set to process a fixed size (size), the Aggregator component arranges the records into one or more blocks containing the specified number of records. If fewer records are available than the configured size, the last block of records is smaller.
4After processing records in a given array, the Batch Aggregator component sends all the records back to the stepping queue.
- Behavior when the Batch Aggregator component is configured to stream records: When streaming, the Batch Aggregator component processes records as soon as it receives them instead of putting them into record blocks. No record is exposed to the _next_ Batch Step component in the flow until all the records in the Aggregator processes all records in the _current_ Batch Step. A processor within the component must be able to accept an array of records as input. ![A batch job process with a streaming aggregator](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-batch-job-process-aggregator-streaming.png)
1Each Batch Step component receives one or more record blocks and starts processing them in parallel.
2After the Batch Step processes a record, the Batch Step sends the record to Batch Aggregator for further processing.
3The Batch Aggregator component continues processing records until there are no more records in the stepping queue that are waiting to be processed by the current Batch Step.
4The Batch Aggregator component sends all the aggregated records to the stepping queue.
Mule retains a list of all records that succeed or fail to process through each Batch Step. If an event processor in a Batch Step fails to process a record, Mule continues processing the batch, skipping over the failed record in each subsequent Batch Step based on the `acceptPolicy`. The Batch Job component provides the `maxFailedRecords` property for setting the number records that can fail before the batch job stops. See [Batch Job Properties](https://docs.mulesoft.com/mule-runtime/4.11/batch-reference#ref_batch_job_general_fields). ## On Complete Phase During this phase, you can configure Mule runtime to create a report or summary of the records it processed in a given batch job instance. This phase provides system administrators and developers insight into which records failed or succeeded, but it doesn’t process or provide access to individual records, nor does it pass processed records to downstream processors in the flow. At the end of this phase, the batch job instance completes and ceases to exist. As a best practice, configure a mechanism for reporting on failed or successful records to facilitate further action where required. During the On Complete phase, you can perform either of these tasks: - Reference the result object of the batch job instance from elsewhere in the Mule application to capture and use batch job metadata, such as the number of records that failed to process in a particular batch job instance. - Log the result object for each batch job instance: ```xml ``` From the logger set to `payload as Object`, a report looks something like this: INFO 2022-07-06 11:39:02,921 \[\[MuleRuntime\].uber.06: \[w-batch-take6\].batch-management-work-manager @56978b97\] \[processor: w-batch-take6Flow/processors/3/route/1/processors/0; event: e835b2c0-fd5a-11ec-84a5-147ddaaf4f97\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: {onCompletePhaseException=null, loadingPhaseException=null, totalRecords=1000, onCompletePhaseError=null, elapsedTimeInMillis=117, failedOnCompletePhase=false, failedRecords=0, loadedRecords=1000, failedOnInputPhase=false, successfulRecords=1000, inputPhaseException=null, batchStepResults={firstError=com.mulesoft.mule.runtime.module.batch.privileged.ImmutableBatchStepResult@d9323a5}, processedRecords=10, loadingPhaseError=null, failedOnLoadingPhase=false, batchJobInstanceId=e84b5da0-fd5a-11ec-84a5-147ddaaf4f97, inputPhaseError=null} The fields in the batch job report object are accessible as keys when using DataWeave selectors, such as `payload.failedRecords` to return the number of failed records in the instance. If you leave the On Complete phase empty, the batch job instance silently completes, and the logs provide processing information about the instance, for example: Finished execution for instance 'e84b5da0-fd5a-11ec-84a5-147ddaaf4f97' of job 'w-batch-take6Batch\_Job'. Total Records processed: 1000. Successful records: 1000. Failed Records: 0 --- product: Mule Runtime version: 4.12 --- # Batch Job Phases > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Each time a Batch Job component executes, it goes through these phases: 1. [Load and Dispatch Phase](#phase_load_dispatch): The Batch Job component splits [valid input](https://docs.mulesoft.com/mule-runtime/4.12/batch-processing-concept#valid_input) into records and prepares the records for processing. This phase takes place within the Batch Job component. 2. [Process Phase](#phase_process): Mule components and connector operations within one or more Batch Step components in the Batch Job process records within a given batch job instance. Processing within a Batch Aggregator component also occurs in the Process phase. 3. [On Complete Phase](#phase_on_complete): The Batch Job component issues a report object with the result of processing the batch job instance. For an example, see [batch phase XML](https://docs.mulesoft.com/mule-runtime/4.12/batch-processing-concept#batch_phases_xml). ## Load and Dispatch Phase When an upstream event in the flow triggers the Batch Job component, the Load and Dispatch phase begins. In this phase, these actions occur: 1. Mule creates a new batch job instance that persists through each phase of a batch job. Within the scope of the Batch Job component, Mule exposes the currently processing batch job instance ID through the `batchJobInstanceId` variable. You can use `vars.batchJobInstanceId` to access the identifier of the current instance in any batch processing phase. The auto-generated identifier is a UUID, but you can change it to a different value. For details, see [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/4.12/batch-job-instance-id). 2. The Batch Job component automatically splits the received message payload into records and stores the records in the stepping queue. The Batch Job component either successfully generates and queues a record for every item from the input, or the entire event fails with an error type, such as `MULE:EXPRESSION` message, and an error message, such as `"Expecting Array or Object but got String." evaluating expression: "payload".` In Anypoint Runtime Manager, the queue name is prefixed with `BSQ`, for example: ![A batch step queue transaction log in Anypoint Runtime Manager](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-batch-bsq.png) 3. The Batch Job component starts the execution of a batch job instance that processes the loaded records. ## Process Phase The Process phase begins after the Load and Dispatch phase finishes loading records to the queue and starts execution of a batch job instance. In this phase, Batch Step components concurrently pull record blocks of the configured size from the queue to process them. (The default batch block size is 100.) Within the Batch Step component, Mule processes multiple record blocks in parallel by using separate threads, while the records within each block process sequentially by default. Mule uses its auto-tuning capabilities to determine how many threads to use and the level of parallelism to apply (see [Execution Engine](https://docs.mulesoft.com/mule-runtime/4.12/execution-engine)). During this phase, processors within the components can access and modify records using the `payload` and `vars` Mule variables. The Batch Job component consumes records after all record processing finishes. So any transmission of _processed_ records to an external server or service must take place _within_ the Batch Step or Batch Aggregator components. For Mule variable propagation rules, see [Variable Propagation](https://docs.mulesoft.com/mule-runtime/4.12/batch-processing-concept#variable_propagation). After processing records in a block, the Batch Step sends the records back to the stepping queue, where they become available for the next Batch Step component. The next Batch Step doesn’t wait for the previous step to complete. It starts processing available records as soon as they return to the queue. Records are pulled from the queue in blocks, but the composition of these blocks can differ from the previous step because records from different parallel threads are mixed in the queue. At the end of this phase, all records are consumed and aren’t available for further processing by downstream processors in the Mule flow. Note that since changes to records that take place within a Batch Aggregator component _aren’t propagated_ outside of Batch Aggregator component, changes aren’t visible to subsequent Batch Step components in the flow. ![A batch job instance with a record stepping queue for multiple batch steps](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-batch-step-process.png) As processing takes place, each record keeps track of all Batch Step components that process it. By default, a batch job instance doesn’t wait for all its queued records to finish processing in one Batch Step component before making them available for processing by the next Batch Step component. Configuring a Batch Aggregator component changes this behavior: - Behavior when the Batch Aggregator component sets a fixed size: A processor within the Batch Aggregator must be able to receive the array of records as input. ![A batch job process with a fixed-size aggregator](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-batch-job-process-aggregator-fixed.png)
1Each Batch Step component within a Batch Job component receives one or more record blocks and starts processing them in parallel.
2After processing a record, the Batch Step component sends the record to the Batch Aggregator component for further processing.
3When set to process a fixed size (size), the Aggregator component arranges the records into one or more blocks containing the specified number of records. If fewer records are available than the configured size, the last block of records is smaller.
4After processing records in a given array, the Batch Aggregator component sends all the records back to the stepping queue.
- Behavior when the Batch Aggregator component is configured to stream records: When streaming, the Batch Aggregator component processes records as soon as it receives them instead of putting them into record blocks. No record is exposed to the _next_ Batch Step component in the flow until all the records in the Aggregator processes all records in the _current_ Batch Step. A processor within the component must be able to accept an array of records as input. ![A batch job process with a streaming aggregator](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-batch-job-process-aggregator-streaming.png)
1Each Batch Step component receives one or more record blocks and starts processing them in parallel.
2After the Batch Step processes a record, the Batch Step sends the record to Batch Aggregator for further processing.
3The Batch Aggregator component continues processing records until there are no more records in the stepping queue that are waiting to be processed by the current Batch Step.
4The Batch Aggregator component sends all the aggregated records to the stepping queue.
Mule retains a list of all records that succeed or fail to process through each Batch Step. If an event processor in a Batch Step fails to process a record, Mule continues processing the batch, skipping over the failed record in each subsequent Batch Step based on the `acceptPolicy`. The Batch Job component provides the `maxFailedRecords` property for setting the number records that can fail before the batch job stops. See [Batch Job Properties](https://docs.mulesoft.com/mule-runtime/4.12/batch-reference#ref_batch_job_general_fields). ## On Complete Phase During this phase, you can configure Mule runtime to create a report or summary of the records it processed in a given batch job instance. This phase provides system administrators and developers insight into which records failed or succeeded, but it doesn’t process or provide access to individual records, nor does it pass processed records to downstream processors in the flow. At the end of this phase, the batch job instance completes and ceases to exist. As a best practice, configure a mechanism for reporting on failed or successful records to facilitate further action where required. During the On Complete phase, you can perform either of these tasks: - Reference the result object of the batch job instance from elsewhere in the Mule application to capture and use batch job metadata, such as the number of records that failed to process in a particular batch job instance. - Log the result object for each batch job instance: ```xml ``` From the logger set to `payload as Object`, a report looks something like this: INFO 2022-07-06 11:39:02,921 \[\[MuleRuntime\].uber.06: \[w-batch-take6\].batch-management-work-manager @56978b97\] \[processor: w-batch-take6Flow/processors/3/route/1/processors/0; event: e835b2c0-fd5a-11ec-84a5-147ddaaf4f97\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: {onCompletePhaseException=null, loadingPhaseException=null, totalRecords=1000, onCompletePhaseError=null, elapsedTimeInMillis=117, failedOnCompletePhase=false, failedRecords=0, loadedRecords=1000, failedOnInputPhase=false, successfulRecords=1000, inputPhaseException=null, batchStepResults={firstError=com.mulesoft.mule.runtime.module.batch.privileged.ImmutableBatchStepResult@d9323a5}, processedRecords=10, loadingPhaseError=null, failedOnLoadingPhase=false, batchJobInstanceId=e84b5da0-fd5a-11ec-84a5-147ddaaf4f97, inputPhaseError=null} The fields in the batch job report object are accessible as keys when using DataWeave selectors, such as `payload.failedRecords` to return the number of failed records in the instance. If you leave the On Complete phase empty, the batch job instance silently completes, and the logs provide processing information about the instance, for example: Finished execution for instance 'e84b5da0-fd5a-11ec-84a5-147ddaaf4f97' of job 'w-batch-take6Batch\_Job'. Total Records processed: 1000. Successful records: 1000. Failed Records: 0 --- product: Mule Runtime version: 4.4 --- # Batch Job Phases > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Each time a Batch Job component executes, the following phases take place: 1. [Load and Dispatch Phase](#phase_load_dispatch): The Batch Job component splits [valid input](https://docs.mulesoft.com/mule-runtime/4.4/batch-processing-concept#valid_input) into records and prepares the records for processing. This phase takes place within the Batch Job component. 2. [Process Phase](#phase_process): Mule components and connector operations within one or more Batch Step components in the Batch Job process records within a given batch job instance. Processing within a Batch Aggregator component also occurs in the Process phase. 3. [On Complete Phase](#phase_on_complete): The Batch Job component issues a report object with the result of processing the batch job instance. For an example, see [batch phase XML](https://docs.mulesoft.com/mule-runtime/4.4/batch-processing-concept#batch_phases_xml). ## Load and Dispatch Phase When an upstream event in the flow triggers the Batch Job component, the Load and Dispatch phase begins. In this phase, the following occurs: 1. Mule creates a new batch job instance that persists through each phase of a batch job. Within the scope of the Batch Job component, Mule exposes the currently processing batch job instance ID through the `batchJobInstanceId` variable. You can use `vars.batchJobInstanceId` to access the identifier of the current instance in any batch processing phase. The auto-generated identifier is a UUID, but you can change it to a different value. For details, see [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/4.4/batch-job-instance-id). 2. The Batch Job component automatically splits the received message payload into records and stores the records in the stepping queue. The Batch Job component either successfully generates and queues a record for every item from the input, or the entire event fails with an error type, such as `MULE:EXPRESSION` message, and an error message, such as `"Expecting Array or Object but got String." evaluating expression: "payload".` In Anypoint Runtime Manager, the queue name is prefixed with `BSQ`, for example: ![Batch step queue transaction log](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-batch-bsq.png) 3. The Batch Job component starts the execution of a batch job instance that processes the loaded records. ## Process Phase The Process phase begins after the Load and Dispatch phase finishes loading records to the queue and starts execution of a batch job instance. In this phase, Batch Step components concurrently pull record blocks of the configured size from the queue to process them. (The default batch block size is 100.) Within the Batch Step component, processing takes place in parallel at the block level, but records within each block process sequentially by default. Mule uses its auto-tuning capabilities to determine how many threads to use and the level of parallelism to apply (see [Execution Engine](https://docs.mulesoft.com/mule-runtime/4.4/execution-engine)). During this phase, processors within the components can access and modify records using the `payload` and `vars` Mule variables. The Batch Job component consumes records after all record processing finishes. So any transmission of _processed_ records to an external server or service must take place _within_ the Batch Step or Batch Aggregator components. For Mule variable propagation rules, see [Variable Propagation](https://docs.mulesoft.com/mule-runtime/4.4/batch-processing-concept#variable_propagation). After processing records in a block, the Batch Step sends the records back to the stepping queue where the records wait for the next Batch Step component. This process continues until every record passes through every Batch Step component within the same Batch Job component. At the end of this phase, all records are consumed. They are not available for further processing by downstream processors in the Mule flow. Note that since changes to records that take place within a Batch Aggregator component _are not propagated_ outside of Batch Aggregator component, changes are not visible to subsequent Batch Step components in the flow. ![Record Stepping Queue for Batch Steps](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-batch-step-process.png) As processing takes place, each record keeps track of all Batch Step components that process it. By default, a batch job instance does not wait for all its queued records to finish processing in one Batch Step component before making them available for processing by the next Batch Step component. Configuring a Batch Aggregator component changes this behavior: - Behavior when the Batch Aggregator component sets a fixed size: A processor within the Batch Aggregator must be able to receive the array of records as input. ![Batch job process with Aggregator with fixed size](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-batch-job-process-aggregator-fixed.png)
1Each Batch Step component within a Batch Job component receives one or more record blocks and starts processing them in parallel.
2After processing a record, the Batch Step component sends the record to the Batch Aggregator component for further processing.
3When set to process a fixed size (size), the Aggregator component arranges the records into one or more blocks containing the specified number of records. If fewer records are available than the configured size, the last block of records is smaller.
4After processing records in a given array, the Batch Aggregator component sends all the records back to the stepping queue.
- Behavior when the Batch Aggregator component is configured to stream records: When streaming, the Batch Aggregator component processes records as soon as it receives them instead of putting them into record blocks. No record is exposed to the _next_ Batch Step component in the flow until all the records in the Aggregator processes all records in the _current_ Batch Step. A processor within the component must be able to accept an array of records as input. ![Batch job process with Aggregator configured for Streaming](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-batch-job-process-aggregator-streaming.png)
1Each Batch Step component receives one or more record blocks and starts processing them in parallel.
2After the Batch Step processes a record, the Batch Step sends the record to Batch Aggregator for further processing.
3The Batch Aggregator component continues processing records until there are no more records in the stepping queue that are waiting to be processed by the current Batch Step.
4The Batch Aggregator component sends all the aggregated records to the stepping queue.
Mule retains a list of all records that succeed or fail to process through each Batch Step. If an event processor in a Batch Step fails to process a record, Mule continues processing the batch, skipping over the failed record in each subsequent Batch Step based on the `acceptPolicy`. The Batch Job component provides the `maxFailedRecords` property for setting the number records that can fail before the batch job stops. See [Batch Job Properties](https://docs.mulesoft.com/mule-runtime/4.4/batch-reference#ref_batch_job_general_fields). ## On Complete Phase During this phase, you can configure Mule runtime to create a report or summary of the records it processed in a given batch job instance. This phase provides system administrators and developers insight into which records failed or succeeded, but it does not process or provide access to individual records, nor does it pass processed records to downstream processors in the flow. At the end of this phase, the batch job instance completes and ceases to exist. As a best practice, configure a mechanism for reporting on failed or successful records to facilitate further action where required. During the On Complete phase, you can perform either of these tasks: - Reference the result object of the batch job instance from elsewhere in the Mule application to capture and use batch job metadata, such as the number of records that failed to process in a particular batch job instance. - Log the result object for each batch job instance: ```xml ``` From the logger set to `payload as Object`, a report looks something like this: INFO 2022-07-06 11:39:02,921 \[\[MuleRuntime\].uber.06: \[w-batch-take6\].batch-management-work-manager @56978b97\] \[processor: w-batch-take6Flow/processors/3/route/1/processors/0; event: e835b2c0-fd5a-11ec-84a5-147ddaaf4f97\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: {onCompletePhaseException=null, loadingPhaseException=null, totalRecords=1000, elapsedTimeInMillis=117, failedOnCompletePhase=false, failedRecords=0, loadedRecords=1000, failedOnInputPhase=false, successfulRecords=1000, inputPhaseException=null, processedRecords=10, failedOnLoadingPhase=false, batchJobInstanceId=e84b5da0-fd5a-11ec-84a5-147ddaaf4f97} The fields in the batch job report object are accessible as keys when using DataWeave selectors, such as `payload.failedRecords` to return the number of failed records in the instance. If you leave the On Complete phase empty, the batch job instance silently completes, and the logs provide processing information about the instance, for example: Finished execution for instance 'e84b5da0-fd5a-11ec-84a5-147ddaaf4f97' of job 'w-batch-take6Batch\_Job'. Total Records processed: 1000. Successful records: 1000. Failed Records: 0 --- product: Mule Runtime version: 4.6 --- # Batch Job Phases > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Each time a Batch Job component executes, the following phases take place: 1. [Load and Dispatch Phase](#phase_load_dispatch): The Batch Job component splits [valid input](https://docs.mulesoft.com/mule-runtime/4.6/batch-processing-concept#valid_input) into records and prepares the records for processing. This phase takes place within the Batch Job component. 2. [Process Phase](#phase_process): Mule components and connector operations within one or more Batch Step components in the Batch Job process records within a given batch job instance. Processing within a Batch Aggregator component also occurs in the Process phase. 3. [On Complete Phase](#phase_on_complete): The Batch Job component issues a report object with the result of processing the batch job instance. For an example, see [batch phase XML](https://docs.mulesoft.com/mule-runtime/4.6/batch-processing-concept#batch_phases_xml). ## Load and Dispatch Phase When an upstream event in the flow triggers the Batch Job component, the Load and Dispatch phase begins. In this phase, the following occurs: 1. Mule creates a new batch job instance that persists through each phase of a batch job. Within the scope of the Batch Job component, Mule exposes the currently processing batch job instance ID through the `batchJobInstanceId` variable. You can use `vars.batchJobInstanceId` to access the identifier of the current instance in any batch processing phase. The auto-generated identifier is a UUID, but you can change it to a different value. For details, see [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/4.6/batch-job-instance-id). 2. The Batch Job component automatically splits the received message payload into records and stores the records in the stepping queue. The Batch Job component either successfully generates and queues a record for every item from the input, or the entire event fails with an error type, such as `MULE:EXPRESSION` message, and an error message, such as `"Expecting Array or Object but got String." evaluating expression: "payload".` In Anypoint Runtime Manager, the queue name is prefixed with `BSQ`, for example: ![Batch step queue transaction log](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-batch-bsq.png) 3. The Batch Job component starts the execution of a batch job instance that processes the loaded records. ## Process Phase The Process phase begins after the Load and Dispatch phase finishes loading records to the queue and starts execution of a batch job instance. In this phase, Batch Step components concurrently pull record blocks of the configured size from the queue to process them. (The default batch block size is 100.) Within the Batch Step component, processing takes place in parallel at the block level, but records within each block process sequentially by default. Mule uses its auto-tuning capabilities to determine how many threads to use and the level of parallelism to apply (see [Execution Engine](https://docs.mulesoft.com/mule-runtime/4.6/execution-engine)). During this phase, processors within the components can access and modify records using the `payload` and `vars` Mule variables. The Batch Job component consumes records after all record processing finishes. So any transmission of _processed_ records to an external server or service must take place _within_ the Batch Step or Batch Aggregator components. For Mule variable propagation rules, see [Variable Propagation](https://docs.mulesoft.com/mule-runtime/4.6/batch-processing-concept#variable_propagation). After processing records in a block, the Batch Step sends the records back to the stepping queue where the records wait for the next Batch Step component. This process continues until every record passes through every Batch Step component within the same Batch Job component. At the end of this phase, all records are consumed. They are not available for further processing by downstream processors in the Mule flow. Note that since changes to records that take place within a Batch Aggregator component _are not propagated_ outside of Batch Aggregator component, changes are not visible to subsequent Batch Step components in the flow. ![Record Stepping Queue for Batch Steps](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-batch-step-process.png) As processing takes place, each record keeps track of all Batch Step components that process it. By default, a batch job instance does not wait for all its queued records to finish processing in one Batch Step component before making them available for processing by the next Batch Step component. Configuring a Batch Aggregator component changes this behavior: - Behavior when the Batch Aggregator component sets a fixed size: A processor within the Batch Aggregator must be able to receive the array of records as input. ![Batch job process with Aggregator with fixed size](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-batch-job-process-aggregator-fixed.png)
1Each Batch Step component within a Batch Job component receives one or more record blocks and starts processing them in parallel.
2After processing a record, the Batch Step component sends the record to the Batch Aggregator component for further processing.
3When set to process a fixed size (size), the Aggregator component arranges the records into one or more blocks containing the specified number of records. If fewer records are available than the configured size, the last block of records is smaller.
4After processing records in a given array, the Batch Aggregator component sends all the records back to the stepping queue.
- Behavior when the Batch Aggregator component is configured to stream records: When streaming, the Batch Aggregator component processes records as soon as it receives them instead of putting them into record blocks. No record is exposed to the _next_ Batch Step component in the flow until all the records in the Aggregator processes all records in the _current_ Batch Step. A processor within the component must be able to accept an array of records as input. ![Batch job process with Aggregator configured for Streaming](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-batch-job-process-aggregator-streaming.png)
1Each Batch Step component receives one or more record blocks and starts processing them in parallel.
2After the Batch Step processes a record, the Batch Step sends the record to Batch Aggregator for further processing.
3The Batch Aggregator component continues processing records until there are no more records in the stepping queue that are waiting to be processed by the current Batch Step.
4The Batch Aggregator component sends all the aggregated records to the stepping queue.
Mule retains a list of all records that succeed or fail to process through each Batch Step. If an event processor in a Batch Step fails to process a record, Mule continues processing the batch, skipping over the failed record in each subsequent Batch Step based on the `acceptPolicy`. The Batch Job component provides the `maxFailedRecords` property for setting the number records that can fail before the batch job stops. See [Batch Job Properties](https://docs.mulesoft.com/mule-runtime/4.6/batch-reference#ref_batch_job_general_fields). ## On Complete Phase During this phase, you can configure Mule runtime to create a report or summary of the records it processed in a given batch job instance. This phase provides system administrators and developers insight into which records failed or succeeded, but it does not process or provide access to individual records, nor does it pass processed records to downstream processors in the flow. At the end of this phase, the batch job instance completes and ceases to exist. As a best practice, configure a mechanism for reporting on failed or successful records to facilitate further action where required. During the On Complete phase, you can perform either of these tasks: - Reference the result object of the batch job instance from elsewhere in the Mule application to capture and use batch job metadata, such as the number of records that failed to process in a particular batch job instance. - Log the result object for each batch job instance: ```xml ``` From the logger set to `payload as Object`, a report looks something like this: INFO 2022-07-06 11:39:02,921 \[\[MuleRuntime\].uber.06: \[w-batch-take6\].batch-management-work-manager @56978b97\] \[processor: w-batch-take6Flow/processors/3/route/1/processors/0; event: e835b2c0-fd5a-11ec-84a5-147ddaaf4f97\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: {onCompletePhaseException=null, loadingPhaseException=null, totalRecords=1000, elapsedTimeInMillis=117, failedOnCompletePhase=false, failedRecords=0, loadedRecords=1000, failedOnInputPhase=false, successfulRecords=1000, inputPhaseException=null, processedRecords=10, failedOnLoadingPhase=false, batchJobInstanceId=e84b5da0-fd5a-11ec-84a5-147ddaaf4f97} The fields in the batch job report object are accessible as keys when using DataWeave selectors, such as `payload.failedRecords` to return the number of failed records in the instance. If you leave the On Complete phase empty, the batch job instance silently completes, and the logs provide processing information about the instance, for example: Finished execution for instance 'e84b5da0-fd5a-11ec-84a5-147ddaaf4f97' of job 'w-batch-take6Batch\_Job'. Total Records processed: 1000. Successful records: 1000. Failed Records: 0 --- product: Mule Runtime version: 4.9 --- # Batch Job Phases > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Each time a Batch Job component executes, the following phases take place: 1. [Load and Dispatch Phase](#phase_load_dispatch): The Batch Job component splits [valid input](https://docs.mulesoft.com/mule-runtime/4.9/batch-processing-concept#valid_input) into records and prepares the records for processing. This phase takes place within the Batch Job component. 2. [Process Phase](#phase_process): Mule components and connector operations within one or more Batch Step components in the Batch Job process records within a given batch job instance. Processing within a Batch Aggregator component also occurs in the Process phase. 3. [On Complete Phase](#phase_on_complete): The Batch Job component issues a report object with the result of processing the batch job instance. For an example, see [batch phase XML](https://docs.mulesoft.com/mule-runtime/4.9/batch-processing-concept#batch_phases_xml). ## Load and Dispatch Phase When an upstream event in the flow triggers the Batch Job component, the Load and Dispatch phase begins. In this phase, the following occurs: 1. Mule creates a new batch job instance that persists through each phase of a batch job. Within the scope of the Batch Job component, Mule exposes the currently processing batch job instance ID through the `batchJobInstanceId` variable. You can use `vars.batchJobInstanceId` to access the identifier of the current instance in any batch processing phase. The auto-generated identifier is a UUID, but you can change it to a different value. For details, see [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/4.9/batch-job-instance-id). 2. The Batch Job component automatically splits the received message payload into records and stores the records in the stepping queue. The Batch Job component either successfully generates and queues a record for every item from the input, or the entire event fails with an error type, such as `MULE:EXPRESSION` message, and an error message, such as `"Expecting Array or Object but got String." evaluating expression: "payload".` In Anypoint Runtime Manager, the queue name is prefixed with `BSQ`, for example: ![A batch step queue transaction log in Anypoint Runtime Manager](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-batch-bsq.png) 3. The Batch Job component starts the execution of a batch job instance that processes the loaded records. ## Process Phase The Process phase begins after the Load and Dispatch phase finishes loading records to the queue and starts execution of a batch job instance. In this phase, Batch Step components concurrently pull record blocks of the configured size from the queue to process them. (The default batch block size is 100.) Within the Batch Step component, processing takes place in parallel at the block level, but records within each block process sequentially by default. Mule uses its auto-tuning capabilities to determine how many threads to use and the level of parallelism to apply (see [Execution Engine](https://docs.mulesoft.com/mule-runtime/4.9/execution-engine)). During this phase, processors within the components can access and modify records using the `payload` and `vars` Mule variables. The Batch Job component consumes records after all record processing finishes. So any transmission of _processed_ records to an external server or service must take place _within_ the Batch Step or Batch Aggregator components. For Mule variable propagation rules, see [Variable Propagation](https://docs.mulesoft.com/mule-runtime/4.9/batch-processing-concept#variable_propagation). After processing records in a block, the Batch Step sends the records back to the stepping queue where the records wait for the next Batch Step component. This process continues until every record passes through every Batch Step component within the same Batch Job component. At the end of this phase, all records are consumed. They are not available for further processing by downstream processors in the Mule flow. Note that since changes to records that take place within a Batch Aggregator component _are not propagated_ outside of Batch Aggregator component, changes are not visible to subsequent Batch Step components in the flow. ![A batch job instance with a record stepping queue for multiple batch steps](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-batch-step-process.png) As processing takes place, each record keeps track of all Batch Step components that process it. By default, a batch job instance does not wait for all its queued records to finish processing in one Batch Step component before making them available for processing by the next Batch Step component. Configuring a Batch Aggregator component changes this behavior: - Behavior when the Batch Aggregator component sets a fixed size: A processor within the Batch Aggregator must be able to receive the array of records as input. ![A batch job process with a fixed-size aggregator](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-batch-job-process-aggregator-fixed.png)
1Each Batch Step component within a Batch Job component receives one or more record blocks and starts processing them in parallel.
2After processing a record, the Batch Step component sends the record to the Batch Aggregator component for further processing.
3When set to process a fixed size (size), the Aggregator component arranges the records into one or more blocks containing the specified number of records. If fewer records are available than the configured size, the last block of records is smaller.
4After processing records in a given array, the Batch Aggregator component sends all the records back to the stepping queue.
- Behavior when the Batch Aggregator component is configured to stream records: When streaming, the Batch Aggregator component processes records as soon as it receives them instead of putting them into record blocks. No record is exposed to the _next_ Batch Step component in the flow until all the records in the Aggregator processes all records in the _current_ Batch Step. A processor within the component must be able to accept an array of records as input. ![A batch job process with a streaming aggregator](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-batch-job-process-aggregator-streaming.png)
1Each Batch Step component receives one or more record blocks and starts processing them in parallel.
2After the Batch Step processes a record, the Batch Step sends the record to Batch Aggregator for further processing.
3The Batch Aggregator component continues processing records until there are no more records in the stepping queue that are waiting to be processed by the current Batch Step.
4The Batch Aggregator component sends all the aggregated records to the stepping queue.
Mule retains a list of all records that succeed or fail to process through each Batch Step. If an event processor in a Batch Step fails to process a record, Mule continues processing the batch, skipping over the failed record in each subsequent Batch Step based on the `acceptPolicy`. The Batch Job component provides the `maxFailedRecords` property for setting the number records that can fail before the batch job stops. See [Batch Job Properties](https://docs.mulesoft.com/mule-runtime/4.9/batch-reference#ref_batch_job_general_fields). ## On Complete Phase During this phase, you can configure Mule runtime to create a report or summary of the records it processed in a given batch job instance. This phase provides system administrators and developers insight into which records failed or succeeded, but it does not process or provide access to individual records, nor does it pass processed records to downstream processors in the flow. At the end of this phase, the batch job instance completes and ceases to exist. As a best practice, configure a mechanism for reporting on failed or successful records to facilitate further action where required. During the On Complete phase, you can perform either of these tasks: - Reference the result object of the batch job instance from elsewhere in the Mule application to capture and use batch job metadata, such as the number of records that failed to process in a particular batch job instance. - Log the result object for each batch job instance: ```xml ``` From the logger set to `payload as Object`, a report looks something like this: INFO 2022-07-06 11:39:02,921 \[\[MuleRuntime\].uber.06: \[w-batch-take6\].batch-management-work-manager @56978b97\] \[processor: w-batch-take6Flow/processors/3/route/1/processors/0; event: e835b2c0-fd5a-11ec-84a5-147ddaaf4f97\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: {onCompletePhaseException=null, loadingPhaseException=null, totalRecords=1000, elapsedTimeInMillis=117, failedOnCompletePhase=false, failedRecords=0, loadedRecords=1000, failedOnInputPhase=false, successfulRecords=1000, inputPhaseException=null, processedRecords=10, failedOnLoadingPhase=false, batchJobInstanceId=e84b5da0-fd5a-11ec-84a5-147ddaaf4f97} The fields in the batch job report object are accessible as keys when using DataWeave selectors, such as `payload.failedRecords` to return the number of failed records in the instance. If you leave the On Complete phase empty, the batch job instance silently completes, and the logs provide processing information about the instance, for example: Finished execution for instance 'e84b5da0-fd5a-11ec-84a5-147ddaaf4f97' of job 'w-batch-take6Batch\_Job'. Total Records processed: 1000. Successful records: 1000. Failed Records: 0 --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Batch Job Phases > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Each time a Batch Job component executes, it goes through these phases: 1. [Load and Dispatch Phase](#phase_load_dispatch): The Batch Job component splits [valid input](https://docs.mulesoft.com/mule-runtime/latest/batch-processing-concept#valid_input) into records and prepares the records for processing. This phase takes place within the Batch Job component. 2. [Process Phase](#phase_process): Mule components and connector operations within one or more Batch Step components in the Batch Job process records within a given batch job instance. Processing within a Batch Aggregator component also occurs in the Process phase. 3. [On Complete Phase](#phase_on_complete): The Batch Job component issues a report object with the result of processing the batch job instance. For an example, see [batch phase XML](https://docs.mulesoft.com/mule-runtime/latest/batch-processing-concept#batch_phases_xml). ## Load and Dispatch Phase When an upstream event in the flow triggers the Batch Job component, the Load and Dispatch phase begins. In this phase, these actions occur: 1. Mule creates a new batch job instance that persists through each phase of a batch job. Within the scope of the Batch Job component, Mule exposes the currently processing batch job instance ID through the `batchJobInstanceId` variable. You can use `vars.batchJobInstanceId` to access the identifier of the current instance in any batch processing phase. The auto-generated identifier is a UUID, but you can change it to a different value. For details, see [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/latest/batch-job-instance-id). 2. The Batch Job component automatically splits the received message payload into records and stores the records in the stepping queue. The Batch Job component either successfully generates and queues a record for every item from the input, or the entire event fails with an error type, such as `MULE:EXPRESSION` message, and an error message, such as `"Expecting Array or Object but got String." evaluating expression: "payload".` In Anypoint Runtime Manager, the queue name is prefixed with `BSQ`, for example: ![A batch step queue transaction log in Anypoint Runtime Manager](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-batch-bsq.png) 3. The Batch Job component starts the execution of a batch job instance that processes the loaded records. ## Process Phase The Process phase begins after the Load and Dispatch phase finishes loading records to the queue and starts execution of a batch job instance. In this phase, Batch Step components concurrently pull record blocks of the configured size from the queue to process them. (The default batch block size is 100.) Within the Batch Step component, Mule processes multiple record blocks in parallel by using separate threads, while the records within each block process sequentially by default. Mule uses its auto-tuning capabilities to determine how many threads to use and the level of parallelism to apply (see [Execution Engine](https://docs.mulesoft.com/mule-runtime/latest/execution-engine)). During this phase, processors within the components can access and modify records using the `payload` and `vars` Mule variables. The Batch Job component consumes records after all record processing finishes. So any transmission of _processed_ records to an external server or service must take place _within_ the Batch Step or Batch Aggregator components. For Mule variable propagation rules, see [Variable Propagation](https://docs.mulesoft.com/mule-runtime/latest/batch-processing-concept#variable_propagation). After processing records in a block, the Batch Step sends the records back to the stepping queue, where they become available for the next Batch Step component. The next Batch Step doesn’t wait for the previous step to complete. It starts processing available records as soon as they return to the queue. Records are pulled from the queue in blocks, but the composition of these blocks can differ from the previous step because records from different parallel threads are mixed in the queue. At the end of this phase, all records are consumed and aren’t available for further processing by downstream processors in the Mule flow. Note that since changes to records that take place within a Batch Aggregator component _aren’t propagated_ outside of Batch Aggregator component, changes aren’t visible to subsequent Batch Step components in the flow. ![A batch job instance with a record stepping queue for multiple batch steps](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-batch-step-process.png) As processing takes place, each record keeps track of all Batch Step components that process it. By default, a batch job instance doesn’t wait for all its queued records to finish processing in one Batch Step component before making them available for processing by the next Batch Step component. Configuring a Batch Aggregator component changes this behavior: - Behavior when the Batch Aggregator component sets a fixed size: A processor within the Batch Aggregator must be able to receive the array of records as input. ![A batch job process with a fixed-size aggregator](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-batch-job-process-aggregator-fixed.png)
1Each Batch Step component within a Batch Job component receives one or more record blocks and starts processing them in parallel.
2After processing a record, the Batch Step component sends the record to the Batch Aggregator component for further processing.
3When set to process a fixed size (size), the Aggregator component arranges the records into one or more blocks containing the specified number of records. If fewer records are available than the configured size, the last block of records is smaller.
4After processing records in a given array, the Batch Aggregator component sends all the records back to the stepping queue.
- Behavior when the Batch Aggregator component is configured to stream records: When streaming, the Batch Aggregator component processes records as soon as it receives them instead of putting them into record blocks. No record is exposed to the _next_ Batch Step component in the flow until all the records in the Aggregator processes all records in the _current_ Batch Step. A processor within the component must be able to accept an array of records as input. ![A batch job process with a streaming aggregator](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-batch-job-process-aggregator-streaming.png)
1Each Batch Step component receives one or more record blocks and starts processing them in parallel.
2After the Batch Step processes a record, the Batch Step sends the record to Batch Aggregator for further processing.
3The Batch Aggregator component continues processing records until there are no more records in the stepping queue that are waiting to be processed by the current Batch Step.
4The Batch Aggregator component sends all the aggregated records to the stepping queue.
Mule retains a list of all records that succeed or fail to process through each Batch Step. If an event processor in a Batch Step fails to process a record, Mule continues processing the batch, skipping over the failed record in each subsequent Batch Step based on the `acceptPolicy`. The Batch Job component provides the `maxFailedRecords` property for setting the number records that can fail before the batch job stops. See [Batch Job Properties](https://docs.mulesoft.com/mule-runtime/latest/batch-reference#ref_batch_job_general_fields). ## On Complete Phase During this phase, you can configure Mule runtime to create a report or summary of the records it processed in a given batch job instance. This phase provides system administrators and developers insight into which records failed or succeeded, but it doesn’t process or provide access to individual records, nor does it pass processed records to downstream processors in the flow. At the end of this phase, the batch job instance completes and ceases to exist. As a best practice, configure a mechanism for reporting on failed or successful records to facilitate further action where required. During the On Complete phase, you can perform either of these tasks: - Reference the result object of the batch job instance from elsewhere in the Mule application to capture and use batch job metadata, such as the number of records that failed to process in a particular batch job instance. - Log the result object for each batch job instance: ```xml ``` From the logger set to `payload as Object`, a report looks something like this: INFO 2022-07-06 11:39:02,921 \[\[MuleRuntime\].uber.06: \[w-batch-take6\].batch-management-work-manager @56978b97\] \[processor: w-batch-take6Flow/processors/3/route/1/processors/0; event: e835b2c0-fd5a-11ec-84a5-147ddaaf4f97\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: {onCompletePhaseException=null, loadingPhaseException=null, totalRecords=1000, onCompletePhaseError=null, elapsedTimeInMillis=117, failedOnCompletePhase=false, failedRecords=0, loadedRecords=1000, failedOnInputPhase=false, successfulRecords=1000, inputPhaseException=null, batchStepResults={firstError=com.mulesoft.mule.runtime.module.batch.privileged.ImmutableBatchStepResult@d9323a5}, processedRecords=10, loadingPhaseError=null, failedOnLoadingPhase=false, batchJobInstanceId=e84b5da0-fd5a-11ec-84a5-147ddaaf4f97, inputPhaseError=null} The fields in the batch job report object are accessible as keys when using DataWeave selectors, such as `payload.failedRecords` to return the number of failed records in the instance. If you leave the On Complete phase empty, the batch job instance silently completes, and the logs provide processing information about the instance, for example: Finished execution for instance 'e84b5da0-fd5a-11ec-84a5-147ddaaf4f97' of job 'w-batch-take6Batch\_Job'. Total Records processed: 1000. Successful records: 1000. Failed Records: 0 --- product: Mule Runtime version: 4.11 keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Processing > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch processing components are designed for reliable, asynchronous processing of larger-than-memory data sets. The components are the Batch Job, Batch Step, and Batch Aggregator. The Batch Job component automatically splits source data and stores it into persistent queues, which makes it possible to process large data sets while providing reliability. In the event that the application is redeployed or Mule crashes, the job execution is able to resume at the point it stopped. > [!NOTE] Mule batch processing components are exclusive to the Enterprise Edition (EE) version of > Mule. The components are not available through the open source Mule kernel. Common use cases for batch processing include: - Synchronizing data sets between business applications, such as syncing contacts between NetSuite and Salesforce. - Extracting, transforming and loading (ETL) information into a target system, such as uploading data from a flat file (CSV) to Hadoop. - Handling large quantities of incoming data from an API to a legacy system. See [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.11/batch-filters-and-batch-aggregator) and [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.11/batch-error-handling-faq) for examples. ## Architecture Mule batch processing components prepare records for processing in batches, run processors on those records, and issue a report on the results of the processing. Record preparation and reporting take place within the Batch Job component. Processing takes place within one or more Batch Step components and, optionally, a Batch Aggregator component within a Batch Step component. ![A Mule flow with batch components and processors](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-batch-job-overview.png) The processors you place within batch processing components act on records. Each record is similar to a Mule event: Processors can access, modify, and route each record payload using the `payload` keyword, and they can work on Mule variables using `vars`. However, they _cannot_ access or modify Mule attributes (`attributes`) from the input to the Batch Job component. The following example outlines the XML structure of a Mule flow that performs batch processing and returns a report with the results of that processing: ```xml (1) (2) (3) (4) (5) (6) (7) (8) ``` Note that the various `placeholder` entries in the example, such as ``, illustrate the location of real processors, such as connector operations, Mule core components, and so on, which process Mule messages, records, and the batch processing report. They are _not real processors_. 1. The Mule event source triggers the Mule flow. Common event sources are listeners, such as an HTTP listener from Anypoint Connector for HTTP (HTTP Connector), a Scheduler component, or a connector operation that polls for new files. 2. Processors located upstream of the Batch Job component typically retrieve and, if necessary, prepare a message for the Batch Job component to consume. For example, an HTTP request operation might retrieve the data to process, and a DataWeave script in a Transform Message component might transform the data into a [valid format](#valid_input) for the Batch Job component to receive. 3. When the Batch Job component receives a message from an upstream processor in the flow, the [Load and Dispatch phase](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases#phase_load_dispatch) begins. In this phase, the component prepares the input for processing as records, which includes creating a batch job instance in which processing takes place. 4. The batch job instance executes when the batch job instance reaches ``. At this point, the [Process phase](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases#phase_process) begins. All record processing takes place during this phase. 5. Each Batch Step component contains one or more processors that act upon a record to transform, route, enrich, or modify data in the records. For example, you might configure a connector operation to pass processed records one-by-one to an external server. 6. A Batch Aggregator component is optional. You can add only one to a Batch Step component. The initial processor within a Batch Aggregator must be able to accept an array of records as input. Batch aggregation is useful for loading an array of processed records to an external server. It is also possible to use components, such as For Each, that iterate over the array so that other processors can process the records individually. The Batch Aggregator component requires a [`streaming` or `size`](https://docs.mulesoft.com/mule-runtime/4.11/batch-reference#ref_batch_aggregator_component) setting to indicate how to process records. 7. Additional Batch Step components are optional. This example does not contain a Batch Aggregator component. 8. After records pass through all Batch Step components, Mule completes the batch job instance and reports the results in an object that indicates which records succeed and which failed during processing. You can retrieve or log the result with a Logger or other processor within ``. The Batch Job component consumes records in the [On Complete phase](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases#phase_on_complete), which occurs after all record processing in a batch job instance finishes, and does not propagate the processed records to external components, outside of the Batch Job component. However, like many Mule components, the Batch Job component provides a way to set a [target variable](https://docs.mulesoft.com/mule-runtime/4.11/batch-reference#ref_batch_job_component) (`target`) property that a downstream component, outside Batch Job use to gain access to the _pre-processed payload_ that the Batch Job component receives. For more detail, see [Batch Job Phases](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases). ## Valid Input to the Batch Job Component When triggered by an upstream event in the flow, the Batch Job component performs an implicit split operation on the Mule message input. The operation accepts any Java Iterables, Iterators, or Arrays, as well as JSON and XML payloads. The component cannot split any other data format. If you are working with a data format that is not compatible with the splitting process, transform the payload to a supported format before it enters the Batch Job component. ## Mule Variable Propagation Each record in a batch job instance inherits Mule event variables from the input to the Batch Job component. You can access and change the value of these variables in the Batch Step and Batch Aggregator components, which run during the Process phase, and you can create new variables within these components. For each record within this phase, the variables (and modifications to them) are propagated through each Batch Step and Aggregator component within a Batch Job component. For example, if record R1 sets the Mule variable `varName` to `"hello"`, record R2 sets `varName` to `"world"`, and record R3 does not set this variable, then in the next Batch Step component, R1 has the value `"hello"`, R2 the value `"world"`, and R3 returns `null` for that variable. In a similar scenario, if `varName` is set in the flow _before_ the Batch Job component and record 3 (R3) does not change the value of `varName`, R3 inherits that value. To illustrate this point, assume a Mule flow that sends the Batch Job component a `payload` of the array `[1,2,3,4]` and a Mule variable `varName` with the value `"my variable before batch job"`. The following example uses the Choice router (`choice`) to set a new value for `varName` in the first and second records but not the third. Subsequent records also set a new `varName` value. ```xml ``` The logs print the following messages for a batch job instance (edited for readability): ```logs ... INFO ...PRINT VARIABLE BEFORE BATCH: "my variable before batch job" ... INFO ...PRINT VARIABLE VALUES AFTER BATCH JOB: "my variable before batch job" INFO ...PRINT RECORD NUMBER: 1 INFO ...R1: PRINT VARIABLE for PAYLOAD is 1: "hello" INFO ...PRINT RECORD NUMBER: 2 INFO ...R2: PRINT VARIABLE for PAYLOAD is 2: "world" INFO ...PRINT RECORD NUMBER: 3 INFO ...R3: PRINT VARIABLE for PAYLOAD is 3: "my variable before batch job" INFO ...PRINT RECORD NUMBER: 4 INFO ...Rn: PRINT DEFAULT VARIABLE: "some other value" ... INFO ...PRINT VARIABLES IN SECOND STEP: {payload 1="hello"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 2="world"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 3="my variable before batch job"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 4="some other value"} ... ``` Notice that the third record (R3) inherits the value of the `varName` set before the Batch Job component. Any records after R3 set the variable to `"some other value"`. Records logged in the second Batch Step inherit the values of the variables from the first Batch Step. The Logger _after_ the Batch Job component, which is processed asynchronously, _before_ the batch job instance finishes processing, also receives the value of `varName` _before_ the Batch Job executes, `"my variable before batch job"`. Changes and additions to Mule variables during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases#phase_process) do not propagate to the [On Complete phase](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases#phase_on_complete). Only variables inherited from the triggering event to the Batch Job component propagate to the On Complete phase, and standard variables that are part of the batch job report, such as `batchJobInstanceId`, are also present in this phase. It is possible to create a variable in the On Complete phase that persists through the phase but not after the On Complete ends. For example, assume that the On Complete phase sets a new variable (`myOnCompleteVar`) and logs all variables (`vars`) found in this phase. ```xml ``` In the On Complete report, you find the final set variables for a batch job instance, for example: INFO ... PRINT ON COMPLETE VARIABLES: { varName=TypedValue\[value: '"my variable before batch job"', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*; charset=UTF-8'}'\], batchJobInstanceId=TypedValue\[value: '869ae510-5c84-11ed-bc38-147ddaaf4f97', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*'}'\], myOnCompleteVar=TypedValue\[value: 'Hello On Complete Variable', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*; charset=UTF-8'}'\]} Variables in the report object example follow: - `varName` is an example of a variable created before reaching the Batch Job component. This variable retains the value it had when it entered the component. Any changes to the value during the Process phase are not retained in the On Complete phase. - `batchJobInstanceId` is a standard variable that identifies a batch job instance. - `myOnCompleteVar` is an example of a variable created within the On Complete phase. It appears in the report but does not persist after the On Complete phase ends. Downstream from the Batch Job component, only `varName` persists. Like the records and their attributes, the variables of the records are completely consumed within the Batch Job component. The batch job instance executes asynchronously from the rest of the flow, so no variable created within the Process or On Complete phases persists outside of the Batch Job component. ## Error Handling To prevent the failure of an entire batch job, the Batch Job component can handle any record-level failure that occurs. Further, you can set or remove variables on individual records so that during batch processing, Mule can route or otherwise act upon records in a batch job instance according to a variable. See [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.11/batch-error-handling-faq) for more information. ## See Also - [Batch Job Phases](https://docs.mulesoft.com/mule-runtime/4.11/batch-phases) - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.11/batch-filters-and-batch-aggregator) - [Batch Process Tuning](https://docs.mulesoft.com/mule-runtime/4.11/tuning-batch-processing) - [How Transactions Affect Components and Routers](https://docs.mulesoft.com/mule-runtime/4.11/transaction-management#tx_components_routers) - [Persistent Queues for Applications Containing Batch Jobs](https://docs.mulesoft.com/cloudhub/cloudhub-fabric#persistent-queues-for-applications-containing-batch-jobs.adoc) --- product: Mule Runtime version: 4.12 keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Processing > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch processing components are designed for reliable, asynchronous processing of larger-than-memory data sets. The components are the Batch Job, Batch Step, and Batch Aggregator. The Batch Job component automatically splits source data and stores it into persistent queues, which makes it possible to process large data sets while providing reliability. In the event that the application is redeployed or Mule crashes, the job execution is able to resume at the point it stopped. > [!NOTE] Mule batch processing components are exclusive to the Enterprise Edition (EE) version of > Mule. The components are not available through the open source Mule kernel. Common use cases for batch processing include: - Synchronizing data sets between business applications, such as syncing contacts between NetSuite and Salesforce. - Extracting, transforming and loading (ETL) information into a target system, such as uploading data from a flat file (CSV) to Hadoop. - Handling large quantities of incoming data from an API to a legacy system. See [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.12/batch-filters-and-batch-aggregator) and [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.12/batch-error-handling-faq) for examples. ## Architecture Mule batch processing components prepare records for processing in batches, run processors on those records, and issue a report on the results of the processing. Record preparation and reporting take place within the Batch Job component. Processing takes place within one or more Batch Step components and, optionally, a Batch Aggregator component within a Batch Step component. ![A Mule flow with batch components and processors](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-batch-job-overview.png) The processors you place within batch processing components act on records. Each record is similar to a Mule event: Processors can access, modify, and route each record payload using the `payload` keyword, and they can work on Mule variables using `vars`. However, they _cannot_ access or modify Mule attributes (`attributes`) from the input to the Batch Job component. The following example outlines the XML structure of a Mule flow that performs batch processing and returns a report with the results of that processing: ```xml (1) (2) (3) (4) (5) (6) (7) (8) ``` Note that the various `placeholder` entries in the example, such as ``, illustrate the location of real processors, such as connector operations, Mule core components, and so on, which process Mule messages, records, and the batch processing report. They are _not real processors_. 1. The Mule event source triggers the Mule flow. Common event sources are listeners, such as an HTTP listener from Anypoint Connector for HTTP (HTTP Connector), a Scheduler component, or a connector operation that polls for new files. 2. Processors located upstream of the Batch Job component typically retrieve and, if necessary, prepare a message for the Batch Job component to consume. For example, an HTTP request operation might retrieve the data to process, and a DataWeave script in a Transform Message component might transform the data into a [valid format](#valid_input) for the Batch Job component to receive. 3. When the Batch Job component receives a message from an upstream processor in the flow, the [Load and Dispatch phase](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases#phase_load_dispatch) begins. In this phase, the component prepares the input for processing as records, which includes creating a batch job instance in which processing takes place. 4. The batch job instance executes when the batch job instance reaches ``. At this point, the [Process phase](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases#phase_process) begins. All record processing takes place during this phase. 5. Each Batch Step component contains one or more processors that act upon a record to transform, route, enrich, or modify data in the records. For example, you might configure a connector operation to pass processed records one-by-one to an external server. 6. A Batch Aggregator component is optional. You can add only one to a Batch Step component. The initial processor within a Batch Aggregator must be able to accept an array of records as input. Batch aggregation is useful for loading an array of processed records to an external server. It is also possible to use components, such as For Each, that iterate over the array so that other processors can process the records individually. The Batch Aggregator component requires a [`streaming` or `size`](https://docs.mulesoft.com/mule-runtime/4.12/batch-reference#ref_batch_aggregator_component) setting to indicate how to process records. 7. Additional Batch Step components are optional. This example does not contain a Batch Aggregator component. 8. After records pass through all Batch Step components, Mule completes the batch job instance and reports the results in an object that indicates which records succeed and which failed during processing. You can retrieve or log the result with a Logger or other processor within ``. The Batch Job component consumes records in the [On Complete phase](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases#phase_on_complete), which occurs after all record processing in a batch job instance finishes, and does not propagate the processed records to external components, outside of the Batch Job component. However, like many Mule components, the Batch Job component provides a way to set a [target variable](https://docs.mulesoft.com/mule-runtime/4.12/batch-reference#ref_batch_job_component) (`target`) property that a downstream component, outside Batch Job use to gain access to the _pre-processed payload_ that the Batch Job component receives. For more detail, see [Batch Job Phases](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases). ## Valid Input to the Batch Job Component When triggered by an upstream event in the flow, the Batch Job component performs an implicit split operation on the Mule message input. The operation accepts any Java Iterables, Iterators, or Arrays, as well as JSON and XML payloads. The component cannot split any other data format. If you are working with a data format that is not compatible with the splitting process, transform the payload to a supported format before it enters the Batch Job component. ## Mule Variable Propagation Each record in a batch job instance inherits Mule event variables from the input to the Batch Job component. You can access and change the value of these variables in the Batch Step and Batch Aggregator components, which run during the Process phase, and you can create new variables within these components. For each record within this phase, the variables (and modifications to them) are propagated through each Batch Step and Aggregator component within a Batch Job component. For example, if record R1 sets the Mule variable `varName` to `"hello"`, record R2 sets `varName` to `"world"`, and record R3 does not set this variable, then in the next Batch Step component, R1 has the value `"hello"`, R2 the value `"world"`, and R3 returns `null` for that variable. In a similar scenario, if `varName` is set in the flow _before_ the Batch Job component and record 3 (R3) does not change the value of `varName`, R3 inherits that value. To illustrate this point, assume a Mule flow that sends the Batch Job component a `payload` of the array `[1,2,3,4]` and a Mule variable `varName` with the value `"my variable before batch job"`. The following example uses the Choice router (`choice`) to set a new value for `varName` in the first and second records but not the third. Subsequent records also set a new `varName` value. ```xml ``` The logs print the following messages for a batch job instance (edited for readability): ```logs ... INFO ...PRINT VARIABLE BEFORE BATCH: "my variable before batch job" ... INFO ...PRINT VARIABLE VALUES AFTER BATCH JOB: "my variable before batch job" INFO ...PRINT RECORD NUMBER: 1 INFO ...R1: PRINT VARIABLE for PAYLOAD is 1: "hello" INFO ...PRINT RECORD NUMBER: 2 INFO ...R2: PRINT VARIABLE for PAYLOAD is 2: "world" INFO ...PRINT RECORD NUMBER: 3 INFO ...R3: PRINT VARIABLE for PAYLOAD is 3: "my variable before batch job" INFO ...PRINT RECORD NUMBER: 4 INFO ...Rn: PRINT DEFAULT VARIABLE: "some other value" ... INFO ...PRINT VARIABLES IN SECOND STEP: {payload 1="hello"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 2="world"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 3="my variable before batch job"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 4="some other value"} ... ``` Notice that the third record (R3) inherits the value of the `varName` set before the Batch Job component. Any records after R3 set the variable to `"some other value"`. Records logged in the second Batch Step inherit the values of the variables from the first Batch Step. The Logger _after_ the Batch Job component, which is processed asynchronously, _before_ the batch job instance finishes processing, also receives the value of `varName` _before_ the Batch Job executes, `"my variable before batch job"`. Changes and additions to Mule variables during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases#phase_process) do not propagate to the [On Complete phase](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases#phase_on_complete). Only variables inherited from the triggering event to the Batch Job component propagate to the On Complete phase, and standard variables that are part of the batch job report, such as `batchJobInstanceId`, are also present in this phase. It is possible to create a variable in the On Complete phase that persists through the phase but not after the On Complete ends. For example, assume that the On Complete phase sets a new variable (`myOnCompleteVar`) and logs all variables (`vars`) found in this phase. ```xml ``` In the On Complete report, you find the final set variables for a batch job instance, for example: INFO ... PRINT ON COMPLETE VARIABLES: { varName=TypedValue\[value: '"my variable before batch job"', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*; charset=UTF-8'}'\], batchJobInstanceId=TypedValue\[value: '869ae510-5c84-11ed-bc38-147ddaaf4f97', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*'}'\], myOnCompleteVar=TypedValue\[value: 'Hello On Complete Variable', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*; charset=UTF-8'}'\]} Variables in the report object example follow: - `varName` is an example of a variable created before reaching the Batch Job component. This variable retains the value it had when it entered the component. Any changes to the value during the Process phase are not retained in the On Complete phase. - `batchJobInstanceId` is a standard variable that identifies a batch job instance. - `myOnCompleteVar` is an example of a variable created within the On Complete phase. It appears in the report but does not persist after the On Complete phase ends. Downstream from the Batch Job component, only `varName` persists. Like the records and their attributes, the variables of the records are completely consumed within the Batch Job component. The batch job instance executes asynchronously from the rest of the flow, so no variable created within the Process or On Complete phases persists outside of the Batch Job component. ## Error Handling To prevent the failure of an entire batch job, the Batch Job component can handle any record-level failure that occurs. Further, you can set or remove variables on individual records so that during batch processing, Mule can route or otherwise act upon records in a batch job instance according to a variable. See [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.12/batch-error-handling-faq) for more information. ## See Also - [Batch Job Phases](https://docs.mulesoft.com/mule-runtime/4.12/batch-phases) - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.12/batch-filters-and-batch-aggregator) - [Batch Process Tuning](https://docs.mulesoft.com/mule-runtime/4.12/tuning-batch-processing) - [How Transactions Affect Components and Routers](https://docs.mulesoft.com/mule-runtime/4.12/transaction-management#tx_components_routers) - [Persistent Queues for Applications Containing Batch Jobs](https://docs.mulesoft.com/cloudhub/cloudhub-fabric#persistent-queues-for-applications-containing-batch-jobs.adoc) --- product: Mule Runtime version: 4.3 keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Processing > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!NOTE] Batch processing is exclusive to Mule Enterprise runtimes. Mule allows you to process messages in batches. Within an application, you can initiate a Batch Job scope, which splits messages into individual records, performs actions upon each record, and then reports on the results and potentially pushes the processed output to other systems or queues. For example, you can use batch processing when: - Synchronizing data sets between business applications, such as syncing contacts between NetSuite and Salesforce. - Extracting, transforming and loading (ETL) information into a target system, such as uploading data from a flat file (CSV) to Hadoop. - Handling large quantities of incoming data from an API into a legacy system. If you are already familiar with batch processing in Mule 3.x, you can get an overview of the differences with batch in Mule 4.x in the [Migrating the Batch Module](https://docs.mulesoft.com/mule-runtime/4.3/migration-core-batch) article. ## Overview Within a Mule application, batch processing provides a construct for asynchronously processing larger-than-memory data sets that are split into individual records. Batch jobs allow for the description of a reliable process that automatically splits up source data and stores it into persistent queues, which makes it possible to process large data sets while providing reliability. In the event that the application is redeployed or Mule crashes, the job execution is able to resume at the point it stopped. ![batch main3](/mulesoft/current/en-us/mule-runtime/4.3/_images/batch-main3.png) The job is then expressed in terms of processing individual records, providing semantics for record level variables, aggregation, and error handling. ## Basic Architecture The heart of Mule’s batch processing lies within the batch job. A batch job is a scope that splits large messages into records that Mule processes asynchronously. In the same way flows process messages, batch jobs process records. ![batch processing concept d1bdd](/mulesoft/current/en-us/mule-runtime/4.3/_images/batch-processing-concept-d1bdd.png) The Batch XML structure was modified on Mule 4.0. The example below shows abbreviated details to highlight batch elements. ```xml ``` A batch job contains one or more batch steps that act upon records as they move through the batch job. Each batch step in a batch job contains processors that act upon a record to transform, route, enrich, or otherwise process data contained within it. By leveraging the functionality of existing Mule processors, the batch step offers a lot of flexibility regarding how a batch job processes records. See [Refining Batch Steps Processing](https://docs.mulesoft.com/mule-runtime/4.3/batch-filters-and-batch-aggregator) for more information. A batch job executes when the flow reaches the process-records section of the batch job. When triggered, Mule creates a new batch job instance. When the job instance becomes executable, the batch engine submits a task for each record block to the I/O pool to process each record. Parallelism occurs automatically, at the record block level. The Mule runtime engine uses its autotuning capabilities to determine how many threads to use and the level of parallelism to apply (see [Execution Engine](https://docs.mulesoft.com/mule-runtime/4.3/execution-engine)). When the batch job starts executing, Mule splits the incoming message into records, stores them in a persistent queue, and queries and schedules those records in blocks of records to process. By default, the runtime stores 100 records in each batch step. You can customize this size according to the performance you require. See [Refining Batch Steps Processing](https://docs.mulesoft.com/mule-runtime/4.3/batch-filters-and-batch-aggregator) for more information. After all the records have passed through all batch steps, the runtime ends the batch job instance and reports the batch job result indicating which records succeeded and which failed during processing. ### Mule Message Splitting Process The batch job performs an implicit split operation on the Mule message that recognizes any Java Iterables, Iterators, and Arrays, as well as JSON and XML payloads. The batch job cannot split any other data format. If you are working with a data format that is not compatible with the splitting process, transform the payload to a supported format before it enters the batch job. ### Error Handling Batch jobs can handle any record-level failure that might occur in processing to prevent the failure of a complete batch job. Further, you can set or remove variables on individual records so that during batch processing, Mule can route or otherwise act upon records in a batch job according to a variable (assigned above). See [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.3/batch-error-handling-faq) for more information. ### Batch Job vs. Batch Job Instance Though defined in context the above, it’s worth elaborating upon the terms _batch job_ and _batch job instance_ as they relate to each other. - A batch job is the scope element in an application in which Mule processes a message payload as a batch of records. The term batch job is inclusive of all three phases of processing: Load and Dispatch, Process, and On Complete. - A batch job instance is an occurrence in a Mule application whenever a Mule flow executes a batch job. Mule creates the batch job instance in the Load and Dispatch phase. Every batch job instance is identified internally using a unique String known as batch _job instance id_. This identifier is useful if you want, for example, to pass the local job instance ID to an external system for referencing and managing data, improve the job’s custom logging, or even send an email or SMS notifications for meaningful events around that specific batch job instance. See [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/4.3/batch-job-instance-id) to learn more about this identifier and how to customize it. ## Batch Job Processing Phases Each batch job contains three different phases: 1. Load and Dispatch. 2. Process. 3. On Complete. ### Load and Dispatch This first phase is implicit. During this phase, the runtime performs all the "behind the scenes" work to create a batch job instance. Essentially, this is the phase during which Mule turns a serialized message payload into a collection of records for processing as a batch. You don’t need to configure anything for this activity to occur, though it is useful to understand the tasks Mule completes during this phase. 1. Mule splits the message using Dataweave. This first step creates a new _batch job instance_. Mule exposes the batch job instance ID through the `batchJobInstanceId` variable. This variable is available in every step and the on-complete phase. 2. Mule creates a persistent queue and associates it with the new batch job instance. The queue name is prefixed with `BSQ`, and you can see it in Anypoint Runtime Manager: ![Batch step queue transaction log](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-batch-bsq.png) 3. For each item generated by the splitter, Mule creates a record and stores it in the queue. This activity is "all or nothing" – Mule either successfully generates and queues a record for every item, or the whole message fails during this phase. 4. Mule presents the batch job instance, with all its queued-up records, to the first batch step for processing. After this phase completes, the flow continues its execution without waiting for the batch job to finish processing all records. This behavior occurs because the next phase, _Process_, is asynchronous. ### Process During the _Process_ phase, Mule starts pulling records from the stepping queue to build record blocks of the configured batch block size. Then, Mule sends the record blocks to their corresponding batch step and processes them asynchronously. Each batch step starts processing multiple record blocks in parallel, however, batch steps process the records inside each block sequentially. After a batch step processes all the records in a block, the batch step sends those records to the stepping queue, where the records await to be processed by the next batch step (each record keeps track of the steps it completed). This process continues until every record has passed through every batch step of the batch job instance. ![batch+diagram](/mulesoft/current/en-us/mule-runtime/4.3/_images/batch-diagram.jpg) Note that a batch job instance does not wait for all its queued records to finish processing in one batch step before pushing any of them to the next batch step. However, if you configure an aggregator, the batch job step changes its behavior while processing records, depending on how the aggregator is configured: - Behavior with aggregator configured with fixed size In this scenario, the batch step sends the processed records to an aggregator, which starts processing the records and buffering them until the configured aggregator’s size is reached. After that, the aggregator sends the aggregated records to the stepping queue. ![Batch job process with Aggregator with fixed size](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-batch-job-process-aggregator-fixed.png)
1The batch job builds record blocks of the configured block size and sends them to their corresponding batch step for processing.
2Each batch step receives one or more record blocks and starts processing them in parallel.
3After the batch step processes a record, the batch step sends the record to the aggregator for further processing.
4The aggregator continues processing records until the number of aggregated records reaches the configured aggregator’s size.
5The aggregator sends all the aggregated records to the stepping queue.
- Behavior with aggregator configured for streaming In this scenario, the batch step sends the processed records to an aggregator, which keeps processing records until all records from the current batch step are processed and aggregated. ![Batch job process with Aggregator configured for Streaming](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-batch-job-process-aggregator-streaming.png)
1The batch job builds record blocks of the configured block size and sends them to their corresponding batch step for processing.
2Each batch step receives one or more record blocks and starts processing them in parallel.
3After the batch step processes a record, the batch step sends the record to the aggregator for further processing.
4The aggregator continues processing records until there are no more records in the stepping queue that are waiting to be processed by the current batch step.
5The aggregator sends all the aggregated records to the stepping queue.
Mule persists a list of all records that succeed or fail to process through each batch step. If an event processor in a batch step fails to process a record, Mule continues processing the batch, skipping over the failed record in each subsequent batch step. At the end of this phase, the batch job instance completes and, therefore, ceases to exist. #### Refine Batch Steps Processing Beyond simple processing of records, there are several things you can do with records within a batch step. - You can apply filters by adding acceptExpressions within each batch step to prevent the step from processing certain records. For example, you can set a filter to prevent a step from processing any records which failed to process in the preceding step. - You can use a batch aggregator processor to aggregate records in groups, sending them as bulk upserts to external sources or services. For example, rather than upserting each contact (that is, a record) in a batch to Google Contacts, you can configure a batch aggregator to accumulate, say, 100 records, then upsert all of them to Google Contacts in one chunk. See [Refining Batch Steps Processing](https://docs.mulesoft.com/mule-runtime/4.3/batch-filters-and-batch-aggregator) for more information. ### On Complete During this phase, you can optionally configure the runtime to create a report or summary of the records it processed for the particular batch job instance. This phase exists to give system administrators and developers some insight into which records failed to address any issues that might exist with the input data. ```xml ``` After Mule executes the entire batch job, the output becomes a batch job result object (`BatchJobResult`). Because Mule processes a batch job as an asynchronous, one-way flow, the results of batch processing do not feed back into the flow which may have triggered it, nor do the results return as a response to a caller. Any event source that feeds data into a batch job must be one-way, not request-response. You have two options for working with the output: - Create a report in the On Complete phase, using DataWeave using information such as the number of failed records and successfully processed records, and in which step any errors might have occurred. - Reference the batch job result object elsewhere in the Mule application to capture and use batch metadata, such as the number of records which failed to process in a particular batch job instance. If you leave the On Complete phase empty and do not reference the batch job result object elsewhere in your application, the batch job simply completes, whether failed or successful. > [!TIP] As a good practice, you should configure some mechanism for reporting on failed or > successful records to facilitate further action where required. ### Variable Propagation Every processed record of the Batch Job Instance starts with the same variables and values present before the execution of the block. Every record has its own set of variables, so new variables or modifications of already-existing variables during the processing of a given record will not be visible while processing another record. For each record, those variables (and modifications) are propagated through the different Batch Steps. For example, if record R1 sets a variable `varName: "hello"`, record R2 sets `varName: "world"`, and record R3 does not set this variable, then in the next step, R1 will see the value `"hello"`, R2 the value `"world"` and R3 will not see any value for that variable. In the On Complete phase, none of these variables (not even the original ones) are visible. Only the final result is available in this phase. Moreover, since the Batch Job Instance executes asynchronously from the rest of the flow, no variable set in either a Batch Step or the On Complete phase will be visible outside the Batch Scope. ### Scheduling Strategy A Mule application can contain several batch job definitions. Each definition has its own scheduling strategy. A **Scheduling Strategy** enables you to control how instances of a given batch job are executed: - `ORDERED_SQUENTIAL` (the default): If several job instances are in an executable state at the same time, the instances execute one at a time based on their creation timestamp. - `ROUND_ROBIN`: This setting attempts to execute all available instances of a batch job using a round-robin algorithm to assign the available resources. The `ROUND_ROBIN` option is useful when you can guarantee that no job execution can have a side effect on another job execution. Therefore, this option is not a good choice for data synchronization jobs, which can update the same record in two concurrent jobs. Because the order of the job execution is not guaranteed, your result might be a prior version of the data. However, you can safely use this strategy to parallelize the job’s execution if your batch job retrieves only new records from a database or lifts individual files from an SFTP server, and you are certain that all records are completely independent. Note that none of these strategies guarantee that records will be executed in order. The strategies do not control the execution order of records in the batch job, nor do they depend on the number of records each instance contains. ## See Also - [Refining Batch Steps Processing](https://docs.mulesoft.com/mule-runtime/4.3/batch-filters-and-batch-aggregator) - [Migrating the Batch Element](https://docs.mulesoft.com/mule-runtime/4.3/migration-core-batch) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.3/transaction-management#tx_scopes_routers) --- product: Mule Runtime version: 4.3 --- # Batch Processing > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) possesses the ability to process messages in batches. Within an application, you can initiate a batch job which is a block of code that splits large messages into individual records, performs actions upon each record, then reports on the results and potentially pushes the processed output to other systems or queues. Consider having 1 million records processed by a batch application with three steps. Several I/O operations occur as Mule processes each record as it moves through the job’s phases. The disk characteristics, along with the workload size, play a key role in the performance of the batch job, primarily because during the input phase, an in-disk queue is created of the list of records to be processed, which is constantly read and written by the flow, resulting in heavy I/O utilization. Additionally, batch processing requires having enough memory available to process the threads in parallel, which means moving the records from persistent storage into RAM in a fixed-size block. The larger your records and their quantity, the more available memory you need for batch processing. ## Batch Block Size By default, the batch block size is set to 100. It is a good balancing point between performance and working memory requirements based on analysis across a set of representative batch use cases with various record sizes. However, the optimal value for each application depends on its use case. You can configure this property for the batch job. If you believe that in your particular case, custom size is best suited, make sure to run comparative tests with different values to find the optimum size in your use case. The following example shows the batch block size: ```xml ``` ## Max Concurrency The maximum number of threads used for processing within a Batch scope defaults to 2 times the number of cores that the JVM detects. On fractional core deployments, such as CloudHub and Anypoint Runtime Fabric, the JVM detects a _non-fractional_ number of cores. You can manually increase or lower the automated concurrency setting. The Max Concurrency setting enables you to set an upper limit on the number of threads to use for a batch job instance that, for example, has insufficient records to warrant more threads. The following example overrides the automated `maxConcurrency` default to a setting that is loaded from a property: ```xml ``` ## Batch Aggregators One million round trips across a network impacts performance, whether on single or multiple threads. Communication with SaaS systems can easily consume the quota of API calls. Instead of processing records one by one, you can improve performance by using the Batch Aggregator scope to perform bulk operations on arrays of records. The scope uses an Aggregator Size setting to limit the number of records in each array. When determining the number of records to process in an array of records, you must take into account the maximum number of records permitted by operations on the system with which the communication takes place. It is important to conduct performance testing on your Aggregator Size setting _and on lower values_. Your logic must handle any number of records up to and including the value of your setting because the number of records that the system receives can be lower than your specified value. For example, if there are 120 records, and your Aggregator Size setting is 50, the last submission is 20 records. The following example shows a Batch Step scope with a Batch Aggregator scope that is set to a fixed size of `50`: ```xml ``` If the aggregator contains an operation that streams data, you can activate the scope’s Streaming option (`streaming="true"`) instead of using an Aggregator Size setting (`size="50"`). ## Multiple Concurrent Instances of a Batch Job Many use cases for Batch Job scopes process only one request (batch job instance) at a time, but some cases simultaneously execute two or more batch job instances. To tune the thread pool sharing in such cases, you can set one of the following scheduling strategies, each of which is tracked separately by its batch instance ID: - `ORDERED_SEQUENTIAL`: Default scheduling strategy that limits the impact of concurrent instances by processing the instances in the order they are triggered. This strategy is useful when nonsequential processing of the same batch job can cause issues, such as data inconsistency, or reach resource limitations. - `ROUND_ROBIN`: Scheduling strategy that shares the threads with batch job instances that are "in flight". ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.3/batch-processing-concept) --- product: Mule Runtime version: 4.4 keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Processing > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch processing components are designed for reliable, asynchronous processing of larger-than-memory data sets. The components are the Batch Job, Batch Step, and Batch Aggregator. The Batch Job component automatically splits source data and stores it into persistent queues, which makes it possible to process large data sets while providing reliability. In the event that the application is redeployed or Mule crashes, the job execution is able to resume at the point it stopped. > [!NOTE] Mule batch processing components are exclusive to the Enterprise Edition (EE) version of > Mule. The components are not available through the open source Mule kernel. > > If you are familiar with batch processing in Mule 3.x, see > [Migrating the Batch Module](https://docs.mulesoft.com/mule-runtime/4.4/migration-core-batch) for an overview of batch processing differences > in Mule 4.x. Common use cases for batch processing include: - Synchronizing data sets between business applications, such as syncing contacts between NetSuite and Salesforce. - Extracting, transforming and loading (ETL) information into a target system, such as uploading data from a flat file (CSV) to Hadoop. - Handling large quantities of incoming data from an API to a legacy system. See [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.4/batch-filters-and-batch-aggregator) and [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.4/batch-error-handling-faq) for examples. ## Architecture Mule batch processing components prepare records for processing in batches, run processors on those records, and issue a report on the results of the processing. Record preparation and reporting take place within the Batch Job component. Processing takes place within one or more Batch Step components and, optionally, a Batch Aggregator component within a Batch Step component. ![Flow with Batch Components and Processors](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-batch-job-overview.png) The processors you place within batch processing components act on records. Each record is similar to a Mule event: Processors can access, modify, and route each record payload using the `payload` keyword, and they can work on Mule variables using `vars`. However, they _cannot_ access or modify Mule attributes (`attributes`) from the input to the Batch Job component. The following example outlines the XML structure of a Mule flow that performs batch processing and returns a report with the results of that processing: ```xml (1) (2) (3) (4) (5) (6) (7) (8) ``` Note that the various `placeholder` entries in the example, such as ``, illustrate the location of real processors, such as connector operations, Mule core components, and so on, which process Mule messages, records, and the batch processing report. They are _not real processors_. 1. The Mule event source triggers the Mule flow. Common event sources are listeners, such as an HTTP listener from Anypoint Connector for HTTP (HTTP Connector), a Scheduler component, or a connector operation that polls for new files. 2. Processors located upstream of the Batch Job component typically retrieve and, if necessary, prepare a message for the Batch Job component to consume. For example, an HTTP request operation might retrieve the data to process, and a DataWeave script in a Transform Message component might transform the data into a [valid format](#valid_input) for the Batch Job component to receive. 3. When the Batch Job component receives a message from an upstream processor in the flow, the [Load and Dispatch phase](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases#phase_load_dispatch) begins. In this phase, the component prepares the input for processing as records, which includes creating a batch job instance in which processing takes place. 4. The batch job instance executes when the batch job instance reaches ``. At this point, the [Process phase](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases#phase_process) begins. All record processing takes place during this phase. 5. Each Batch Step component contains one or more processors that act upon a record to transform, route, enrich, or modify data in the records. For example, you might configure a connector operation to pass processed records one-by-one to an external server. 6. A Batch Aggregator component is optional. You can add only one to a Batch Step component. The initial processor within a Batch Aggregator must be able to accept an array of records as input. Batch aggregation is useful for loading an array of processed records to an external server. It is also possible to use components, such as For Each, that iterate over the array so that other processors can process the records individually. The Batch Aggregator component requires a [`streaming` or `size`](https://docs.mulesoft.com/mule-runtime/4.4/batch-reference#ref_batch_aggregator_component) setting to indicate how to process records. 7. Additional Batch Step components are optional. This example does not contain a Batch Aggregator component. 8. After records pass through all Batch Step components, Mule completes the batch job instance and reports the results in an object that indicates which records succeed and which failed during processing. You can retrieve or log the result with a Logger or other processor within ``. The Batch Job component consumes records in the [On Complete phase](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases#phase_on_complete), which occurs after all record processing in a batch job instance finishes, and does not propagate the processed records to external components, outside of the Batch Job component. However, like many Mule components, the Batch Job component provides a way to set a [target variable](https://docs.mulesoft.com/mule-runtime/4.4/batch-reference#ref_batch_job_component) (`target`) property that a downstream component, outside Batch Job use to gain access to the _pre-processed payload_ that the Batch Job component receives. For more detail, see [Batch Job Phases](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases). ## Valid Input to the Batch Job Component When triggered by an upstream event in the flow, the Batch Job component performs an implicit split operation on the Mule message input. The operation accepts any Java Iterables, Iterators, or Arrays, as well as JSON and XML payloads. The component cannot split any other data format. If you are working with a data format that is not compatible with the splitting process, transform the payload to a supported format before it enters the Batch Job component. ## Mule Variable Propagation Each record in a batch job instance inherits Mule event variables from the input to the Batch Job component. You can access and change the value of these variables in the Batch Step and Batch Aggregator components, which run during the Process phase, and you can create new variables within these components. For each record within this phase, the variables (and modifications to them) are propagated through each Batch Step and Aggregator component within a Batch Job component. For example, if record R1 sets the Mule variable `varName` to `"hello"`, record R2 sets `varName` to `"world"`, and record R3 does not set this variable, then in the next Batch Step component, R1 has the value `"hello"`, R2 the value `"world"`, and R3 returns `null` for that variable. In a similar scenario, if `varName` is set in the flow _before_ the Batch Job component and record 3 (R3) does not change the value of `varName`, R3 inherits that value. To illustrate this point, assume a Mule flow that sends the Batch Job component a `payload` of the array `[1,2,3,4]` and a Mule variable `varName` with the value `"my variable before batch job"`. The following example uses the Choice router (`choice`) to set a new value for `varName` in the first and second records but not the third. Subsequent records also set a new `varName` value. ```xml ``` The logs print the following messages for a batch job instance (edited for readability): ```logs ... INFO ...PRINT VARIABLE BEFORE BATCH: "my variable before batch job" ... INFO ...PRINT VARIABLE VALUES AFTER BATCH JOB: "my variable before batch job" INFO ...PRINT RECORD NUMBER: 1 INFO ...R1: PRINT VARIABLE for PAYLOAD is 1: "hello" INFO ...PRINT RECORD NUMBER: 2 INFO ...R2: PRINT VARIABLE for PAYLOAD is 2: "world" INFO ...PRINT RECORD NUMBER: 3 INFO ...R3: PRINT VARIABLE for PAYLOAD is 3: "my variable before batch job" INFO ...PRINT RECORD NUMBER: 4 INFO ...Rn: PRINT DEFAULT VARIABLE: "some other value" ... INFO ...PRINT VARIABLES IN SECOND STEP: {payload 1="hello"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 2="world"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 3="my variable before batch job"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 4="some other value"} ... ``` Notice that the third record (R3) inherits the value of the `varName` set before the Batch Job component. Any records after R3 set the variable to `"some other value"`. Records logged in the second Batch Step inherit the values of the variables from the first Batch Step. The Logger _after_ the Batch Job component, which is processed asynchronously, _before_ the batch job instance finishes processing, also receives the value of `varName` _before_ the Batch Job executes, `"my variable before batch job"`. Changes and additions to Mule variables during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases#phase_process) do not propagate to the [On Complete phase](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases#phase_on_complete). Only variables inherited from the triggering event to the Batch Job component propagate to the On Complete phase, and standard variables that are part of the batch job report, such as `batchJobInstanceId`, are also present in this phase. It is possible to create a variable in the On Complete phase that persists through the phase but not after the On Complete ends. For example, assume that the On Complete phase sets a new variable (`myOnCompleteVar`) and logs all variables (`vars`) found in this phase. ```xml ``` In the On Complete report, you find the final set variables for a batch job instance, for example: INFO ... PRINT ON COMPLETE VARIABLES: { varName=TypedValue\[value: '"my variable before batch job"', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*; charset=UTF-8'}'\], batchJobInstanceId=TypedValue\[value: '869ae510-5c84-11ed-bc38-147ddaaf4f97', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*'}'\], myOnCompleteVar=TypedValue\[value: 'Hello On Complete Variable', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*; charset=UTF-8'}'\]} Variables in the report object example follow: - `varName` is an example of a variable created before reaching the Batch Job component. This variable retains the value it had when it entered the component. Any changes to the value during the Process phase are not retained in the On Complete phase. - `batchJobInstanceId` is a standard variable that identifies a batch job instance. - `myOnCompleteVar` is an example of a variable created within the On Complete phase. It appears in the report but does not persist after the On Complete phase ends. Downstream from the Batch Job component, only `varName` persists. Like the records and their attributes, the variables of the records are completely consumed within the Batch Job component. The batch job instance executes asynchronously from the rest of the flow, so no variable created within the Process or On Complete phases persists outside of the Batch Job component. ## Error Handling To prevent the failure of an entire batch job, the Batch Job component can handle any record-level failure that occurs. Further, you can set or remove variables on individual records so that during batch processing, Mule can route or otherwise act upon records in a batch job instance according to a variable. See [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.4/batch-error-handling-faq) for more information. ## See Also - [Batch Job Phases](https://docs.mulesoft.com/mule-runtime/4.4/batch-phases) - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.4/batch-filters-and-batch-aggregator) - [Batch Process Tuning](https://docs.mulesoft.com/mule-runtime/4.4/tuning-batch-processing) - [How Transactions Affect Components and Routers](https://docs.mulesoft.com/mule-runtime/4.4/transaction-management#tx_components_routers) - [Migrating the Batch Module](https://docs.mulesoft.com/mule-runtime/4.4/migration-core-batch) - [Persistent Queues for Applications Containing Batch Jobs](https://docs.mulesoft.com/cloudhub/cloudhub-fabric#persistent-queues-for-applications-containing-batch-jobs.adoc) --- product: Mule Runtime version: 4.4 --- # Batch Processing > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) possesses the ability to process messages in batches. Within an application, you can initiate a batch job which is a block of code that splits large messages into individual records, performs actions upon each record, then reports on the results and potentially pushes the processed output to other systems or queues. Consider having 1 million records processed by a batch application with three steps. Several I/O operations occur as Mule processes each record as it moves through the job’s phases. The disk characteristics, along with the workload size, play a key role in the performance of the batch job, primarily because during the input phase, an in-disk queue is created of the list of records to be processed, which is constantly read and written by the flow, resulting in heavy I/O utilization. Additionally, batch processing requires having enough memory available to process the threads in parallel, which means moving the records from persistent storage into RAM in a fixed-size block. The larger your records and their quantity, the more available memory you need for batch processing. ## Batch Block Size By default, the batch block size is set to 100. It is a good balancing point between performance and working memory requirements based on analysis across a set of representative batch use cases with various record sizes. However, the optimal value for each application depends on its use case. You can configure this property for the batch job. If you believe that in your particular case, custom size is best suited, make sure to run comparative tests with different values to find the optimum size in your use case. The following example shows the batch block size: ```xml ``` ## Max Concurrency The maximum number of threads used for processing within a Batch scope defaults to 2 times the number of cores that the JVM detects. On fractional core deployments, such as CloudHub and Anypoint Runtime Fabric, the JVM detects a _non-fractional_ number of cores. You can manually increase or lower the automated concurrency setting. The Max Concurrency setting enables you to set an upper limit on the number of threads to use for a batch job instance that, for example, has insufficient records to warrant more threads. The following example overrides the automated `maxConcurrency` default to a setting that is loaded from a property: ```xml ``` ## Batch Aggregators One million round trips across a network impacts performance, whether on single or multiple threads. Communication with SaaS systems can easily consume the quota of API calls. Instead of processing records one by one, you can improve performance by using the Batch Aggregator scope to perform bulk operations on arrays of records. The scope uses an Aggregator Size setting to limit the number of records in each array. When determining the number of records to process in an array of records, you must take into account the maximum number of records permitted by operations on the system with which the communication takes place. It is important to conduct performance testing on your Aggregator Size setting _and on lower values_. Your logic must handle any number of records up to and including the value of your setting because the number of records that the system receives can be lower than your specified value. For example, if there are 120 records, and your Aggregator Size setting is 50, the last submission is 20 records. The following example shows a Batch Step scope with a Batch Aggregator scope that is set to a fixed size of `50`: ```xml ``` If the aggregator contains an operation that streams data, you can activate the scope’s Streaming option (`streaming="true"`) instead of using an Aggregator Size setting (`size="50"`). ## Multiple Concurrent Instances of a Batch Job Many use cases for Batch Job scopes process only one request (batch job instance) at a time, but some cases simultaneously execute two or more batch job instances. To tune the thread pool sharing in such cases, you can set one of the following scheduling strategies, each of which is tracked separately by its batch instance ID: - `ORDERED_SEQUENTIAL`: Default scheduling strategy that limits the impact of concurrent instances by processing the instances in the order they are triggered. This strategy is useful when nonsequential processing of the same batch job can cause issues, such as data inconsistency, or reach resource limitations. - `ROUND_ROBIN`: Scheduling strategy that shares the threads with batch job instances that are "in flight". ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.4/batch-processing-concept) --- product: Mule Runtime version: 4.6 keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Processing > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch processing components are designed for reliable, asynchronous processing of larger-than-memory data sets. The components are the Batch Job, Batch Step, and Batch Aggregator. The Batch Job component automatically splits source data and stores it into persistent queues, which makes it possible to process large data sets while providing reliability. In the event that the application is redeployed or Mule crashes, the job execution is able to resume at the point it stopped. > [!NOTE] Mule batch processing components are exclusive to the Enterprise Edition (EE) version of > Mule. The components are not available through the open source Mule kernel. Common use cases for batch processing include: - Synchronizing data sets between business applications, such as syncing contacts between NetSuite and Salesforce. - Extracting, transforming and loading (ETL) information into a target system, such as uploading data from a flat file (CSV) to Hadoop. - Handling large quantities of incoming data from an API to a legacy system. See [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.6/batch-filters-and-batch-aggregator) and [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.6/batch-error-handling-faq) for examples. ## Architecture Mule batch processing components prepare records for processing in batches, run processors on those records, and issue a report on the results of the processing. Record preparation and reporting take place within the Batch Job component. Processing takes place within one or more Batch Step components and, optionally, a Batch Aggregator component within a Batch Step component. ![Flow with Batch Components and Processors](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-batch-job-overview.png) The processors you place within batch processing components act on records. Each record is similar to a Mule event: Processors can access, modify, and route each record payload using the `payload` keyword, and they can work on Mule variables using `vars`. However, they _cannot_ access or modify Mule attributes (`attributes`) from the input to the Batch Job component. The following example outlines the XML structure of a Mule flow that performs batch processing and returns a report with the results of that processing: ```xml (1) (2) (3) (4) (5) (6) (7) (8) ``` Note that the various `placeholder` entries in the example, such as ``, illustrate the location of real processors, such as connector operations, Mule core components, and so on, which process Mule messages, records, and the batch processing report. They are _not real processors_. 1. The Mule event source triggers the Mule flow. Common event sources are listeners, such as an HTTP listener from Anypoint Connector for HTTP (HTTP Connector), a Scheduler component, or a connector operation that polls for new files. 2. Processors located upstream of the Batch Job component typically retrieve and, if necessary, prepare a message for the Batch Job component to consume. For example, an HTTP request operation might retrieve the data to process, and a DataWeave script in a Transform Message component might transform the data into a [valid format](#valid_input) for the Batch Job component to receive. 3. When the Batch Job component receives a message from an upstream processor in the flow, the [Load and Dispatch phase](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases#phase_load_dispatch) begins. In this phase, the component prepares the input for processing as records, which includes creating a batch job instance in which processing takes place. 4. The batch job instance executes when the batch job instance reaches ``. At this point, the [Process phase](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases#phase_process) begins. All record processing takes place during this phase. 5. Each Batch Step component contains one or more processors that act upon a record to transform, route, enrich, or modify data in the records. For example, you might configure a connector operation to pass processed records one-by-one to an external server. 6. A Batch Aggregator component is optional. You can add only one to a Batch Step component. The initial processor within a Batch Aggregator must be able to accept an array of records as input. Batch aggregation is useful for loading an array of processed records to an external server. It is also possible to use components, such as For Each, that iterate over the array so that other processors can process the records individually. The Batch Aggregator component requires a [`streaming` or `size`](https://docs.mulesoft.com/mule-runtime/4.6/batch-reference#ref_batch_aggregator_component) setting to indicate how to process records. 7. Additional Batch Step components are optional. This example does not contain a Batch Aggregator component. 8. After records pass through all Batch Step components, Mule completes the batch job instance and reports the results in an object that indicates which records succeed and which failed during processing. You can retrieve or log the result with a Logger or other processor within ``. The Batch Job component consumes records in the [On Complete phase](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases#phase_on_complete), which occurs after all record processing in a batch job instance finishes, and does not propagate the processed records to external components, outside of the Batch Job component. However, like many Mule components, the Batch Job component provides a way to set a [target variable](https://docs.mulesoft.com/mule-runtime/4.6/batch-reference#ref_batch_job_component) (`target`) property that a downstream component, outside Batch Job use to gain access to the _pre-processed payload_ that the Batch Job component receives. For more detail, see [Batch Job Phases](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases). ## Valid Input to the Batch Job Component When triggered by an upstream event in the flow, the Batch Job component performs an implicit split operation on the Mule message input. The operation accepts any Java Iterables, Iterators, or Arrays, as well as JSON and XML payloads. The component cannot split any other data format. If you are working with a data format that is not compatible with the splitting process, transform the payload to a supported format before it enters the Batch Job component. ## Mule Variable Propagation Each record in a batch job instance inherits Mule event variables from the input to the Batch Job component. You can access and change the value of these variables in the Batch Step and Batch Aggregator components, which run during the Process phase, and you can create new variables within these components. For each record within this phase, the variables (and modifications to them) are propagated through each Batch Step and Aggregator component within a Batch Job component. For example, if record R1 sets the Mule variable `varName` to `"hello"`, record R2 sets `varName` to `"world"`, and record R3 does not set this variable, then in the next Batch Step component, R1 has the value `"hello"`, R2 the value `"world"`, and R3 returns `null` for that variable. In a similar scenario, if `varName` is set in the flow _before_ the Batch Job component and record 3 (R3) does not change the value of `varName`, R3 inherits that value. To illustrate this point, assume a Mule flow that sends the Batch Job component a `payload` of the array `[1,2,3,4]` and a Mule variable `varName` with the value `"my variable before batch job"`. The following example uses the Choice router (`choice`) to set a new value for `varName` in the first and second records but not the third. Subsequent records also set a new `varName` value. ```xml ``` The logs print the following messages for a batch job instance (edited for readability): ```logs ... INFO ...PRINT VARIABLE BEFORE BATCH: "my variable before batch job" ... INFO ...PRINT VARIABLE VALUES AFTER BATCH JOB: "my variable before batch job" INFO ...PRINT RECORD NUMBER: 1 INFO ...R1: PRINT VARIABLE for PAYLOAD is 1: "hello" INFO ...PRINT RECORD NUMBER: 2 INFO ...R2: PRINT VARIABLE for PAYLOAD is 2: "world" INFO ...PRINT RECORD NUMBER: 3 INFO ...R3: PRINT VARIABLE for PAYLOAD is 3: "my variable before batch job" INFO ...PRINT RECORD NUMBER: 4 INFO ...Rn: PRINT DEFAULT VARIABLE: "some other value" ... INFO ...PRINT VARIABLES IN SECOND STEP: {payload 1="hello"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 2="world"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 3="my variable before batch job"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 4="some other value"} ... ``` Notice that the third record (R3) inherits the value of the `varName` set before the Batch Job component. Any records after R3 set the variable to `"some other value"`. Records logged in the second Batch Step inherit the values of the variables from the first Batch Step. The Logger _after_ the Batch Job component, which is processed asynchronously, _before_ the batch job instance finishes processing, also receives the value of `varName` _before_ the Batch Job executes, `"my variable before batch job"`. Changes and additions to Mule variables during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases#phase_process) do not propagate to the [On Complete phase](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases#phase_on_complete). Only variables inherited from the triggering event to the Batch Job component propagate to the On Complete phase, and standard variables that are part of the batch job report, such as `batchJobInstanceId`, are also present in this phase. It is possible to create a variable in the On Complete phase that persists through the phase but not after the On Complete ends. For example, assume that the On Complete phase sets a new variable (`myOnCompleteVar`) and logs all variables (`vars`) found in this phase. ```xml ``` In the On Complete report, you find the final set variables for a batch job instance, for example: INFO ... PRINT ON COMPLETE VARIABLES: { varName=TypedValue\[value: '"my variable before batch job"', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*; charset=UTF-8'}'\], batchJobInstanceId=TypedValue\[value: '869ae510-5c84-11ed-bc38-147ddaaf4f97', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*'}'\], myOnCompleteVar=TypedValue\[value: 'Hello On Complete Variable', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*; charset=UTF-8'}'\]} Variables in the report object example follow: - `varName` is an example of a variable created before reaching the Batch Job component. This variable retains the value it had when it entered the component. Any changes to the value during the Process phase are not retained in the On Complete phase. - `batchJobInstanceId` is a standard variable that identifies a batch job instance. - `myOnCompleteVar` is an example of a variable created within the On Complete phase. It appears in the report but does not persist after the On Complete phase ends. Downstream from the Batch Job component, only `varName` persists. Like the records and their attributes, the variables of the records are completely consumed within the Batch Job component. The batch job instance executes asynchronously from the rest of the flow, so no variable created within the Process or On Complete phases persists outside of the Batch Job component. ## Error Handling To prevent the failure of an entire batch job, the Batch Job component can handle any record-level failure that occurs. Further, you can set or remove variables on individual records so that during batch processing, Mule can route or otherwise act upon records in a batch job instance according to a variable. See [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.6/batch-error-handling-faq) for more information. ## See Also - [Batch Job Phases](https://docs.mulesoft.com/mule-runtime/4.6/batch-phases) - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.6/batch-filters-and-batch-aggregator) - [Batch Process Tuning](https://docs.mulesoft.com/mule-runtime/4.6/tuning-batch-processing) - [How Transactions Affect Components and Routers](https://docs.mulesoft.com/mule-runtime/4.6/transaction-management#tx_components_routers) - [Persistent Queues for Applications Containing Batch Jobs](https://docs.mulesoft.com/cloudhub/cloudhub-fabric#persistent-queues-for-applications-containing-batch-jobs.adoc) --- product: Mule Runtime version: 4.6 --- # Batch Processing > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) possesses the ability to process messages in batches. Within an application, you can initiate a batch job which is a block of code that splits large messages into individual records, performs actions upon each record, then reports on the results and potentially pushes the processed output to other systems or queues. Consider having 1 million records processed by a batch application with three steps. Several I/O operations occur as Mule processes each record as it moves through the job’s phases. The disk characteristics, along with the workload size, play a key role in the performance of the batch job, primarily because during the input phase, an in-disk queue is created of the list of records to be processed, which is constantly read and written by the flow, resulting in heavy I/O utilization. Additionally, batch processing requires having enough memory available to process the threads in parallel, which means moving the records from persistent storage into RAM in a fixed-size block. The larger your records and their quantity, the more available memory you need for batch processing. ## Batch Block Size By default, the batch block size is set to 100. It is a good balancing point between performance and working memory requirements based on analysis across a set of representative batch use cases with various record sizes. However, the optimal value for each application depends on its use case. You can configure this property for the batch job. If you believe that in your particular case, custom size is best suited, make sure to run comparative tests with different values to find the optimum size in your use case. The following example shows the batch block size: ```xml ``` ## Max Concurrency The maximum number of threads used for processing within a Batch scope defaults to 2 times the number of cores that the JVM detects. On fractional core deployments, such as CloudHub and Anypoint Runtime Fabric, the JVM detects a _non-fractional_ number of cores. You can manually increase or lower the automated concurrency setting. The Max Concurrency setting enables you to set an upper limit on the number of threads to use for a batch job instance that, for example, has insufficient records to warrant more threads. The following example overrides the automated `maxConcurrency` default to a setting that is loaded from a property: ```xml ``` ## Batch Aggregators One million round trips across a network impacts performance, whether on single or multiple threads. Communication with SaaS systems can easily consume the quota of API calls. Instead of processing records one by one, you can improve performance by using the Batch Aggregator scope to perform bulk operations on arrays of records. The scope uses an Aggregator Size setting to limit the number of records in each array. When determining the number of records to process in an array of records, you must take into account the maximum number of records permitted by operations on the system with which the communication takes place. It is important to conduct performance testing on your Aggregator Size setting _and on lower values_. Your logic must handle any number of records up to and including the value of your setting because the number of records that the system receives can be lower than your specified value. For example, if there are 120 records, and your Aggregator Size setting is 50, the last submission is 20 records. The following example shows a Batch Step scope with a Batch Aggregator scope that is set to a fixed size of `50`: ```xml ``` If the aggregator contains an operation that streams data, you can activate the scope’s Streaming option (`streaming="true"`) instead of using an Aggregator Size setting (`size="50"`). ## Multiple Concurrent Instances of a Batch Job Many use cases for Batch Job scopes process only one request (batch job instance) at a time, but some cases simultaneously execute two or more batch job instances. To tune the thread pool sharing in such cases, you can set one of the following scheduling strategies, each of which is tracked separately by its batch instance ID: - `ORDERED_SEQUENTIAL`: Default scheduling strategy that limits the impact of concurrent instances by processing the instances in the order they are triggered. This strategy is useful when nonsequential processing of the same batch job can cause issues, such as data inconsistency, or reach resource limitations. - `ROUND_ROBIN`: Scheduling strategy that shares the threads with batch job instances that are "in flight". ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.6/batch-processing-concept) --- product: Mule Runtime version: 4.9 keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Processing > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch processing components are designed for reliable, asynchronous processing of larger-than-memory data sets. The components are the Batch Job, Batch Step, and Batch Aggregator. The Batch Job component automatically splits source data and stores it into persistent queues, which makes it possible to process large data sets while providing reliability. In the event that the application is redeployed or Mule crashes, the job execution is able to resume at the point it stopped. > [!NOTE] Mule batch processing components are exclusive to the Enterprise Edition (EE) version of > Mule. The components are not available through the open source Mule kernel. Common use cases for batch processing include: - Synchronizing data sets between business applications, such as syncing contacts between NetSuite and Salesforce. - Extracting, transforming and loading (ETL) information into a target system, such as uploading data from a flat file (CSV) to Hadoop. - Handling large quantities of incoming data from an API to a legacy system. See [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.9/batch-filters-and-batch-aggregator) and [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.9/batch-error-handling-faq) for examples. ## Architecture Mule batch processing components prepare records for processing in batches, run processors on those records, and issue a report on the results of the processing. Record preparation and reporting take place within the Batch Job component. Processing takes place within one or more Batch Step components and, optionally, a Batch Aggregator component within a Batch Step component. ![A Mule flow with batch components and processors](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-batch-job-overview.png) The processors you place within batch processing components act on records. Each record is similar to a Mule event: Processors can access, modify, and route each record payload using the `payload` keyword, and they can work on Mule variables using `vars`. However, they _cannot_ access or modify Mule attributes (`attributes`) from the input to the Batch Job component. The following example outlines the XML structure of a Mule flow that performs batch processing and returns a report with the results of that processing: ```xml (1) (2) (3) (4) (5) (6) (7) (8) ``` Note that the various `placeholder` entries in the example, such as ``, illustrate the location of real processors, such as connector operations, Mule core components, and so on, which process Mule messages, records, and the batch processing report. They are _not real processors_. 1. The Mule event source triggers the Mule flow. Common event sources are listeners, such as an HTTP listener from Anypoint Connector for HTTP (HTTP Connector), a Scheduler component, or a connector operation that polls for new files. 2. Processors located upstream of the Batch Job component typically retrieve and, if necessary, prepare a message for the Batch Job component to consume. For example, an HTTP request operation might retrieve the data to process, and a DataWeave script in a Transform Message component might transform the data into a [valid format](#valid_input) for the Batch Job component to receive. 3. When the Batch Job component receives a message from an upstream processor in the flow, the [Load and Dispatch phase](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases#phase_load_dispatch) begins. In this phase, the component prepares the input for processing as records, which includes creating a batch job instance in which processing takes place. 4. The batch job instance executes when the batch job instance reaches ``. At this point, the [Process phase](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases#phase_process) begins. All record processing takes place during this phase. 5. Each Batch Step component contains one or more processors that act upon a record to transform, route, enrich, or modify data in the records. For example, you might configure a connector operation to pass processed records one-by-one to an external server. 6. A Batch Aggregator component is optional. You can add only one to a Batch Step component. The initial processor within a Batch Aggregator must be able to accept an array of records as input. Batch aggregation is useful for loading an array of processed records to an external server. It is also possible to use components, such as For Each, that iterate over the array so that other processors can process the records individually. The Batch Aggregator component requires a [`streaming` or `size`](https://docs.mulesoft.com/mule-runtime/4.9/batch-reference#ref_batch_aggregator_component) setting to indicate how to process records. 7. Additional Batch Step components are optional. This example does not contain a Batch Aggregator component. 8. After records pass through all Batch Step components, Mule completes the batch job instance and reports the results in an object that indicates which records succeed and which failed during processing. You can retrieve or log the result with a Logger or other processor within ``. The Batch Job component consumes records in the [On Complete phase](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases#phase_on_complete), which occurs after all record processing in a batch job instance finishes, and does not propagate the processed records to external components, outside of the Batch Job component. However, like many Mule components, the Batch Job component provides a way to set a [target variable](https://docs.mulesoft.com/mule-runtime/4.9/batch-reference#ref_batch_job_component) (`target`) property that a downstream component, outside Batch Job use to gain access to the _pre-processed payload_ that the Batch Job component receives. For more detail, see [Batch Job Phases](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases). ## Valid Input to the Batch Job Component When triggered by an upstream event in the flow, the Batch Job component performs an implicit split operation on the Mule message input. The operation accepts any Java Iterables, Iterators, or Arrays, as well as JSON and XML payloads. The component cannot split any other data format. If you are working with a data format that is not compatible with the splitting process, transform the payload to a supported format before it enters the Batch Job component. ## Mule Variable Propagation Each record in a batch job instance inherits Mule event variables from the input to the Batch Job component. You can access and change the value of these variables in the Batch Step and Batch Aggregator components, which run during the Process phase, and you can create new variables within these components. For each record within this phase, the variables (and modifications to them) are propagated through each Batch Step and Aggregator component within a Batch Job component. For example, if record R1 sets the Mule variable `varName` to `"hello"`, record R2 sets `varName` to `"world"`, and record R3 does not set this variable, then in the next Batch Step component, R1 has the value `"hello"`, R2 the value `"world"`, and R3 returns `null` for that variable. In a similar scenario, if `varName` is set in the flow _before_ the Batch Job component and record 3 (R3) does not change the value of `varName`, R3 inherits that value. To illustrate this point, assume a Mule flow that sends the Batch Job component a `payload` of the array `[1,2,3,4]` and a Mule variable `varName` with the value `"my variable before batch job"`. The following example uses the Choice router (`choice`) to set a new value for `varName` in the first and second records but not the third. Subsequent records also set a new `varName` value. ```xml ``` The logs print the following messages for a batch job instance (edited for readability): ```logs ... INFO ...PRINT VARIABLE BEFORE BATCH: "my variable before batch job" ... INFO ...PRINT VARIABLE VALUES AFTER BATCH JOB: "my variable before batch job" INFO ...PRINT RECORD NUMBER: 1 INFO ...R1: PRINT VARIABLE for PAYLOAD is 1: "hello" INFO ...PRINT RECORD NUMBER: 2 INFO ...R2: PRINT VARIABLE for PAYLOAD is 2: "world" INFO ...PRINT RECORD NUMBER: 3 INFO ...R3: PRINT VARIABLE for PAYLOAD is 3: "my variable before batch job" INFO ...PRINT RECORD NUMBER: 4 INFO ...Rn: PRINT DEFAULT VARIABLE: "some other value" ... INFO ...PRINT VARIABLES IN SECOND STEP: {payload 1="hello"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 2="world"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 3="my variable before batch job"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 4="some other value"} ... ``` Notice that the third record (R3) inherits the value of the `varName` set before the Batch Job component. Any records after R3 set the variable to `"some other value"`. Records logged in the second Batch Step inherit the values of the variables from the first Batch Step. The Logger _after_ the Batch Job component, which is processed asynchronously, _before_ the batch job instance finishes processing, also receives the value of `varName` _before_ the Batch Job executes, `"my variable before batch job"`. Changes and additions to Mule variables during the [Process phase](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases#phase_process) do not propagate to the [On Complete phase](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases#phase_on_complete). Only variables inherited from the triggering event to the Batch Job component propagate to the On Complete phase, and standard variables that are part of the batch job report, such as `batchJobInstanceId`, are also present in this phase. It is possible to create a variable in the On Complete phase that persists through the phase but not after the On Complete ends. For example, assume that the On Complete phase sets a new variable (`myOnCompleteVar`) and logs all variables (`vars`) found in this phase. ```xml ``` In the On Complete report, you find the final set variables for a batch job instance, for example: INFO ... PRINT ON COMPLETE VARIABLES: { varName=TypedValue\[value: '"my variable before batch job"', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*; charset=UTF-8'}'\], batchJobInstanceId=TypedValue\[value: '869ae510-5c84-11ed-bc38-147ddaaf4f97', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*'}'\], myOnCompleteVar=TypedValue\[value: 'Hello On Complete Variable', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*; charset=UTF-8'}'\]} Variables in the report object example follow: - `varName` is an example of a variable created before reaching the Batch Job component. This variable retains the value it had when it entered the component. Any changes to the value during the Process phase are not retained in the On Complete phase. - `batchJobInstanceId` is a standard variable that identifies a batch job instance. - `myOnCompleteVar` is an example of a variable created within the On Complete phase. It appears in the report but does not persist after the On Complete phase ends. Downstream from the Batch Job component, only `varName` persists. Like the records and their attributes, the variables of the records are completely consumed within the Batch Job component. The batch job instance executes asynchronously from the rest of the flow, so no variable created within the Process or On Complete phases persists outside of the Batch Job component. ## Error Handling To prevent the failure of an entire batch job, the Batch Job component can handle any record-level failure that occurs. Further, you can set or remove variables on individual records so that during batch processing, Mule can route or otherwise act upon records in a batch job instance according to a variable. See [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.9/batch-error-handling-faq) for more information. ## See Also - [Batch Job Phases](https://docs.mulesoft.com/mule-runtime/4.9/batch-phases) - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.9/batch-filters-and-batch-aggregator) - [Batch Process Tuning](https://docs.mulesoft.com/mule-runtime/4.9/tuning-batch-processing) - [How Transactions Affect Components and Routers](https://docs.mulesoft.com/mule-runtime/4.9/transaction-management#tx_components_routers) - [Persistent Queues for Applications Containing Batch Jobs](https://docs.mulesoft.com/cloudhub/cloudhub-fabric#persistent-queues-for-applications-containing-batch-jobs.adoc) --- product: Mule Runtime version: 4.9 --- # Batch Processing > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) possesses the ability to process messages in batches. Within an application, you can initiate a batch job which is a block of code that splits large messages into individual records, performs actions upon each record, then reports on the results and potentially pushes the processed output to other systems or queues. Consider having 1 million records processed by a batch application with three steps. Several I/O operations occur as Mule processes each record as it moves through the job’s phases. The disk characteristics, along with the workload size, play a key role in the performance of the batch job, primarily because during the input phase, an in-disk queue is created of the list of records to be processed, which is constantly read and written by the flow, resulting in heavy I/O utilization. Additionally, batch processing requires having enough memory available to process the threads in parallel, which means moving the records from persistent storage into RAM in a fixed-size block. The larger your records and their quantity, the more available memory you need for batch processing. ## Batch Block Size By default, the batch block size is set to 100. It is a good balancing point between performance and working memory requirements based on analysis across a set of representative batch use cases with various record sizes. However, the optimal value for each application depends on its use case. You can configure this property for the batch job. If you believe that in your particular case, custom size is best suited, make sure to run comparative tests with different values to find the optimum size in your use case. The following example shows the batch block size: ```xml ``` ## Max Concurrency The maximum number of threads used for processing within a Batch scope defaults to 2 times the number of cores that the JVM detects. On fractional core deployments, such as CloudHub and Anypoint Runtime Fabric, the JVM detects a _non-fractional_ number of cores. You can manually increase or lower the automated concurrency setting. The Max Concurrency setting enables you to set an upper limit on the number of threads to use for a batch job instance that, for example, has insufficient records to warrant more threads. The following example overrides the automated `maxConcurrency` default to a setting that is loaded from a property: ```xml ``` ## Batch Aggregators One million round trips across a network impacts performance, whether on single or multiple threads. Communication with SaaS systems can easily consume the quota of API calls. Instead of processing records one by one, you can improve performance by using the Batch Aggregator scope to perform bulk operations on arrays of records. The scope uses an Aggregator Size setting to limit the number of records in each array. When determining the number of records to process in an array of records, you must take into account the maximum number of records permitted by operations on the system with which the communication takes place. It is important to conduct performance testing on your Aggregator Size setting _and on lower values_. Your logic must handle any number of records up to and including the value of your setting because the number of records that the system receives can be lower than your specified value. For example, if there are 120 records, and your Aggregator Size setting is 50, the last submission is 20 records. The following example shows a Batch Step scope with a Batch Aggregator scope that is set to a fixed size of `50`: ```xml ``` If the aggregator contains an operation that streams data, you can activate the scope’s Streaming option (`streaming="true"`) instead of using an Aggregator Size setting (`size="50"`). ## Multiple Concurrent Instances of a Batch Job Many use cases for Batch Job scopes process only one request (batch job instance) at a time, but some cases simultaneously execute two or more batch job instances. To tune the thread pool sharing in such cases, you can set one of the following scheduling strategies, each of which is tracked separately by its batch instance ID: - `ORDERED_SEQUENTIAL`: Default scheduling strategy that limits the impact of concurrent instances by processing the instances in the order they are triggered. This strategy is useful when nonsequential processing of the same batch job can cause issues, such as data inconsistency, or reach resource limitations. - `ROUND_ROBIN`: Scheduling strategy that shares the threads with batch job instances that are "in flight". ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.9/batch-processing-concept) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: connectors, anypoint, studio, batch, batch processing --- # Batch Processing > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch processing components are designed for reliable, asynchronous processing of larger-than-memory data sets. The components are the Batch Job, Batch Step, and Batch Aggregator. The Batch Job component automatically splits source data and stores it into persistent queues, which makes it possible to process large data sets while providing reliability. In the event that the application is redeployed or Mule crashes, the job execution is able to resume at the point it stopped. > [!NOTE] Mule batch processing components are exclusive to the Enterprise Edition (EE) version of > Mule. The components are not available through the open source Mule kernel. Common use cases for batch processing include: - Synchronizing data sets between business applications, such as syncing contacts between NetSuite and Salesforce. - Extracting, transforming and loading (ETL) information into a target system, such as uploading data from a flat file (CSV) to Hadoop. - Handling large quantities of incoming data from an API to a legacy system. See [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/latest/batch-filters-and-batch-aggregator) and [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/latest/batch-error-handling-faq) for examples. ## Architecture Mule batch processing components prepare records for processing in batches, run processors on those records, and issue a report on the results of the processing. Record preparation and reporting take place within the Batch Job component. Processing takes place within one or more Batch Step components and, optionally, a Batch Aggregator component within a Batch Step component. ![A Mule flow with batch components and processors](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-batch-job-overview.png) The processors you place within batch processing components act on records. Each record is similar to a Mule event: Processors can access, modify, and route each record payload using the `payload` keyword, and they can work on Mule variables using `vars`. However, they _cannot_ access or modify Mule attributes (`attributes`) from the input to the Batch Job component. The following example outlines the XML structure of a Mule flow that performs batch processing and returns a report with the results of that processing: ```xml (1) (2) (3) (4) (5) (6) (7) (8) ``` Note that the various `placeholder` entries in the example, such as ``, illustrate the location of real processors, such as connector operations, Mule core components, and so on, which process Mule messages, records, and the batch processing report. They are _not real processors_. 1. The Mule event source triggers the Mule flow. Common event sources are listeners, such as an HTTP listener from Anypoint Connector for HTTP (HTTP Connector), a Scheduler component, or a connector operation that polls for new files. 2. Processors located upstream of the Batch Job component typically retrieve and, if necessary, prepare a message for the Batch Job component to consume. For example, an HTTP request operation might retrieve the data to process, and a DataWeave script in a Transform Message component might transform the data into a [valid format](#valid_input) for the Batch Job component to receive. 3. When the Batch Job component receives a message from an upstream processor in the flow, the [Load and Dispatch phase](https://docs.mulesoft.com/mule-runtime/latest/batch-phases#phase_load_dispatch) begins. In this phase, the component prepares the input for processing as records, which includes creating a batch job instance in which processing takes place. 4. The batch job instance executes when the batch job instance reaches ``. At this point, the [Process phase](https://docs.mulesoft.com/mule-runtime/latest/batch-phases#phase_process) begins. All record processing takes place during this phase. 5. Each Batch Step component contains one or more processors that act upon a record to transform, route, enrich, or modify data in the records. For example, you might configure a connector operation to pass processed records one-by-one to an external server. 6. A Batch Aggregator component is optional. You can add only one to a Batch Step component. The initial processor within a Batch Aggregator must be able to accept an array of records as input. Batch aggregation is useful for loading an array of processed records to an external server. It is also possible to use components, such as For Each, that iterate over the array so that other processors can process the records individually. The Batch Aggregator component requires a [`streaming` or `size`](https://docs.mulesoft.com/mule-runtime/latest/batch-reference#ref_batch_aggregator_component) setting to indicate how to process records. 7. Additional Batch Step components are optional. This example does not contain a Batch Aggregator component. 8. After records pass through all Batch Step components, Mule completes the batch job instance and reports the results in an object that indicates which records succeed and which failed during processing. You can retrieve or log the result with a Logger or other processor within ``. The Batch Job component consumes records in the [On Complete phase](https://docs.mulesoft.com/mule-runtime/latest/batch-phases#phase_on_complete), which occurs after all record processing in a batch job instance finishes, and does not propagate the processed records to external components, outside of the Batch Job component. However, like many Mule components, the Batch Job component provides a way to set a [target variable](https://docs.mulesoft.com/mule-runtime/latest/batch-reference#ref_batch_job_component) (`target`) property that a downstream component, outside Batch Job use to gain access to the _pre-processed payload_ that the Batch Job component receives. For more detail, see [Batch Job Phases](https://docs.mulesoft.com/mule-runtime/latest/batch-phases). ## Valid Input to the Batch Job Component When triggered by an upstream event in the flow, the Batch Job component performs an implicit split operation on the Mule message input. The operation accepts any Java Iterables, Iterators, or Arrays, as well as JSON and XML payloads. The component cannot split any other data format. If you are working with a data format that is not compatible with the splitting process, transform the payload to a supported format before it enters the Batch Job component. ## Mule Variable Propagation Each record in a batch job instance inherits Mule event variables from the input to the Batch Job component. You can access and change the value of these variables in the Batch Step and Batch Aggregator components, which run during the Process phase, and you can create new variables within these components. For each record within this phase, the variables (and modifications to them) are propagated through each Batch Step and Aggregator component within a Batch Job component. For example, if record R1 sets the Mule variable `varName` to `"hello"`, record R2 sets `varName` to `"world"`, and record R3 does not set this variable, then in the next Batch Step component, R1 has the value `"hello"`, R2 the value `"world"`, and R3 returns `null` for that variable. In a similar scenario, if `varName` is set in the flow _before_ the Batch Job component and record 3 (R3) does not change the value of `varName`, R3 inherits that value. To illustrate this point, assume a Mule flow that sends the Batch Job component a `payload` of the array `[1,2,3,4]` and a Mule variable `varName` with the value `"my variable before batch job"`. The following example uses the Choice router (`choice`) to set a new value for `varName` in the first and second records but not the third. Subsequent records also set a new `varName` value. ```xml ``` The logs print the following messages for a batch job instance (edited for readability): ```logs ... INFO ...PRINT VARIABLE BEFORE BATCH: "my variable before batch job" ... INFO ...PRINT VARIABLE VALUES AFTER BATCH JOB: "my variable before batch job" INFO ...PRINT RECORD NUMBER: 1 INFO ...R1: PRINT VARIABLE for PAYLOAD is 1: "hello" INFO ...PRINT RECORD NUMBER: 2 INFO ...R2: PRINT VARIABLE for PAYLOAD is 2: "world" INFO ...PRINT RECORD NUMBER: 3 INFO ...R3: PRINT VARIABLE for PAYLOAD is 3: "my variable before batch job" INFO ...PRINT RECORD NUMBER: 4 INFO ...Rn: PRINT DEFAULT VARIABLE: "some other value" ... INFO ...PRINT VARIABLES IN SECOND STEP: {payload 1="hello"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 2="world"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 3="my variable before batch job"} INFO ...PRINT VARIABLES IN SECOND STEP: {payload 4="some other value"} ... ``` Notice that the third record (R3) inherits the value of the `varName` set before the Batch Job component. Any records after R3 set the variable to `"some other value"`. Records logged in the second Batch Step inherit the values of the variables from the first Batch Step. The Logger _after_ the Batch Job component, which is processed asynchronously, _before_ the batch job instance finishes processing, also receives the value of `varName` _before_ the Batch Job executes, `"my variable before batch job"`. Changes and additions to Mule variables during the [Process phase](https://docs.mulesoft.com/mule-runtime/latest/batch-phases#phase_process) do not propagate to the [On Complete phase](https://docs.mulesoft.com/mule-runtime/latest/batch-phases#phase_on_complete). Only variables inherited from the triggering event to the Batch Job component propagate to the On Complete phase, and standard variables that are part of the batch job report, such as `batchJobInstanceId`, are also present in this phase. It is possible to create a variable in the On Complete phase that persists through the phase but not after the On Complete ends. For example, assume that the On Complete phase sets a new variable (`myOnCompleteVar`) and logs all variables (`vars`) found in this phase. ```xml ``` In the On Complete report, you find the final set variables for a batch job instance, for example: INFO ... PRINT ON COMPLETE VARIABLES: { varName=TypedValue\[value: '"my variable before batch job"', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*; charset=UTF-8'}'\], batchJobInstanceId=TypedValue\[value: '869ae510-5c84-11ed-bc38-147ddaaf4f97', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*'}'\], myOnCompleteVar=TypedValue\[value: 'Hello On Complete Variable', dataType: 'SimpleDataType{type=java.lang.String, mimeType='\*/\*; charset=UTF-8'}'\]} Variables in the report object example follow: - `varName` is an example of a variable created before reaching the Batch Job component. This variable retains the value it had when it entered the component. Any changes to the value during the Process phase are not retained in the On Complete phase. - `batchJobInstanceId` is a standard variable that identifies a batch job instance. - `myOnCompleteVar` is an example of a variable created within the On Complete phase. It appears in the report but does not persist after the On Complete phase ends. Downstream from the Batch Job component, only `varName` persists. Like the records and their attributes, the variables of the records are completely consumed within the Batch Job component. The batch job instance executes asynchronously from the rest of the flow, so no variable created within the Process or On Complete phases persists outside of the Batch Job component. ## Error Handling To prevent the failure of an entire batch job, the Batch Job component can handle any record-level failure that occurs. Further, you can set or remove variables on individual records so that during batch processing, Mule can route or otherwise act upon records in a batch job instance according to a variable. See [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/latest/batch-error-handling-faq) for more information. ## See Also - [Batch Job Phases](https://docs.mulesoft.com/mule-runtime/latest/batch-phases) - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/latest/batch-filters-and-batch-aggregator) - [Batch Process Tuning](https://docs.mulesoft.com/mule-runtime/latest/tuning-batch-processing) - [How Transactions Affect Components and Routers](https://docs.mulesoft.com/mule-runtime/latest/transaction-management#tx_components_routers) - [Persistent Queues for Applications Containing Batch Jobs](https://docs.mulesoft.com/cloudhub/cloudhub-fabric#persistent-queues-for-applications-containing-batch-jobs.adoc) --- product: Mule Runtime version: 4.11 --- # Best Practices to Build Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. ## Anypoint Studio Best Practices If you use Anypoint Studio to build Mule apps, consider the following practices: - Update to the latest version of Anypoint Studio. - Use the recommended Java version (OpenJDK) for the specific Studio version. - Include the Mule Maven plugin for automated deployment (executed by CI/CD processes). ### Define a Project Structure To help maintain a clean, structured, and readable project in Anypoint Studio, consider the following recommendations: - Create a separate XML file for global elements, for example, configuration elements. - Create a separate XML file for each use case or resource implementation. - Create separate XML files for common structures or logic. - Create different packages for resources such as DataWeave, WSDLs, examples, and so on. #### Add Indentation and Formatting As you build your app project in Anypoint Studio, consider the following points: - Add indentation and format to all your XML files (Mule XMLs, `pom.xml`, `log4j2.xml`, and so on) before committing to the source code repository. - Define a line width in your Anypoint Studio XML editor preferences, for example `140.d`. - Define a naming convention. #### Manage Properties per Environment To avoid creating a separate set of variables for each environment, Mule 4 contains a built-in mechanism that enables you to set default values, which you manage by using Anypoint Runtime Manager. For details, see [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-configuration) and [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.11/configuring-properties). ## App-Building Best Practice As you build your Mule app, avoid packaging the configuration files for all the environments inside the application. Instead, use a `.yaml` file to provide default properties, and use Anypoint Runtime Manager to override each of these properties at deployment time. ## Components and Connectors Best Practices When building your apps using Mule components and connectors, consider the following recommendations. ### APIkit When using APIkit, consider these practices: - Use APIkit features to generate flows automatically using your API specification. - Use APIkit Exception Strategy to catch connector-related exceptions. ### DataWeave When using DataWeave for building your app, consider these recommendations: - Use inline scripts during the development phase. - To have a clean XML and reusable scripts, pass the inline scripts to an external file. ### Flows When creating flows for your app, consider the following practices: - Have a clear flow diagram showing the steps of the use case. - Use a Flow Reference to separate and reuse common logic. ### File Connector If you use Anypoint Connector for File (File Connector) and share part of the path on numerous reads or any other file operations, extract the base path into a file configuration to reuse it: ```xml ``` ### HTTP and HTTPS For HTTP and HTTPS ports in on-premises deployments, MuleSoft recommends using the names for property placeholders that are reserved for CloudHub deployments. The shared load balancer in CloudHub uses the defaults for these properties. - In CloudHub, `${http.port}` maps to the setting `port=8081`, and `${https.port}` maps to `port=8082`. - For internal ports to HTTP services in CloudHub deployments, `${http.private.port}` maps to the setting `port=8091`, and `${https.private.port}` maps to `port=8092`. For details about these settings in CloudHub, see [CloudHub Reserved Properties](https://docs.mulesoft.com/cloudhub/cloudhub-manage-props#cloudhub-reserved-properties) and [CloudHub Networking Guide](https://docs.mulesoft.com/cloudhub/cloudhub-networking-guide). ### Apache Kafka Connector If you use Anypoint Connector for Apache Kafka (Apache Kafka Connector) perform the following actions: - Use the `.properties` file to add bootstrap server configuration. - Add property placeholders, either in a `.yaml` or a `.properties` file, and use the file in the configuration: ```xml config.bootstrapServers={your Kafka Server address} config.consumerPropertiesFile=consumer.properties config.producerPropertiesFile=producer.properties # Consumer specific information consumer.topic=one-replica consumer.topic.partitions=1 ``` - Apache Kafka Connector provides various settings for producer and consumer properties, add your own settings in `consumer.properties` and `producer.properties` under `src/main/resource`: ```xml ``` ## See Also - [Apache Kafka Connector](https://docs.mulesoft.com/kafka-connector/latest/) - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) --- product: Mule Runtime version: 4.12 --- # Best Practices to Build Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. ## Anypoint Studio Best Practices If you use Anypoint Studio to build Mule apps, consider the following practices: - Update to the latest version of Anypoint Studio. - Use the recommended Java version (OpenJDK) for the specific Studio version. - Include the Mule Maven plugin for automated deployment (executed by CI/CD processes). ### Define a Project Structure To help maintain a clean, structured, and readable project in Anypoint Studio, consider the following recommendations: - Create a separate XML file for global elements, for example, configuration elements. - Create a separate XML file for each use case or resource implementation. - Create separate XML files for common structures or logic. - Create different packages for resources such as DataWeave, WSDLs, examples, and so on. #### Add Indentation and Formatting As you build your app project in Anypoint Studio, consider the following points: - Add indentation and format to all your XML files (Mule XMLs, `pom.xml`, `log4j2.xml`, and so on) before committing to the source code repository. - Define a line width in your Anypoint Studio XML editor preferences, for example `140.d`. - Define a naming convention. #### Manage Properties per Environment To avoid creating a separate set of variables for each environment, Mule 4 contains a built-in mechanism that enables you to set default values, which you manage by using Anypoint Runtime Manager. For details, see [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-configuration) and [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.12/configuring-properties). ## App-Building Best Practice As you build your Mule app, avoid packaging the configuration files for all the environments inside the application. Instead, use a `.yaml` file to provide default properties, and use Anypoint Runtime Manager to override each of these properties at deployment time. ## Components and Connectors Best Practices When building your apps using Mule components and connectors, consider the following recommendations. ### APIkit When using APIkit, consider these practices: - Use APIkit features to generate flows automatically using your API specification. - Use APIkit Exception Strategy to catch connector-related exceptions. ### DataWeave When using DataWeave for building your app, consider these recommendations: - Use inline scripts during the development phase. - To have a clean XML and reusable scripts, pass the inline scripts to an external file. ### Flows When creating flows for your app, consider the following practices: - Have a clear flow diagram showing the steps of the use case. - Use a Flow Reference to separate and reuse common logic. ### File Connector If you use Anypoint Connector for File (File Connector) and share part of the path on numerous reads or any other file operations, extract the base path into a file configuration to reuse it: ```xml ``` ### HTTP and HTTPS For HTTP and HTTPS ports in on-premises deployments, MuleSoft recommends using the names for property placeholders that are reserved for CloudHub deployments. The shared load balancer in CloudHub uses the defaults for these properties. - In CloudHub, `${http.port}` maps to the setting `port=8081`, and `${https.port}` maps to `port=8082`. - For internal ports to HTTP services in CloudHub deployments, `${http.private.port}` maps to the setting `port=8091`, and `${https.private.port}` maps to `port=8092`. For details about these settings in CloudHub, see [CloudHub Reserved Properties](https://docs.mulesoft.com/cloudhub/cloudhub-manage-props#cloudhub-reserved-properties) and [CloudHub Networking Guide](https://docs.mulesoft.com/cloudhub/cloudhub-networking-guide). ### Apache Kafka Connector If you use Anypoint Connector for Apache Kafka (Apache Kafka Connector) perform the following actions: - Use the `.properties` file to add bootstrap server configuration. - Add property placeholders, either in a `.yaml` or a `.properties` file, and use the file in the configuration: ```xml config.bootstrapServers={your Kafka Server address} config.consumerPropertiesFile=consumer.properties config.producerPropertiesFile=producer.properties # Consumer specific information consumer.topic=one-replica consumer.topic.partitions=1 ``` - Apache Kafka Connector provides various settings for producer and consumer properties, add your own settings in `consumer.properties` and `producer.properties` under `src/main/resource`: ```xml ``` ## See Also - [Apache Kafka Connector](https://docs.mulesoft.com/kafka-connector/latest/) - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) --- product: Mule Runtime version: 4.3 --- # Best Practices to Build Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. ## Anypoint Studio Best Practices If you use Anypoint Studio to build Mule apps, consider the following practices: - Update to the latest version of Anypoint Studio. - Use the recommended Java version (OpenJDK) for the specific Studio version. - Include the Mule Maven plugin for automated deployment (executed by CI/CD processes). ### Define a Project Structure To help maintain a clean, structured, and readable project in Anypoint Studio, consider the following recommendations: - Create a separate XML file for global elements, for example, configuration elements. - Create a separate XML file for each use case or resource implementation. - Create separate XML files for common structures or logic. - Create different packages for resources such as DataWeave, WSDLs, examples, and so on. #### Add Indentation and Formatting As you build your app project in Anypoint Studio, consider the following points: - Add indentation and format to all your XML files (Mule XMLs, `pom.xml`, `log4j2.xml`, and so on) before committing to the source code repository. - Define a line width in your Anypoint Studio XML editor preferences, for example `140.d`. - Define a naming convention. #### Manage Properties per Environment To avoid creating a separate set of variables for each environment, Mule 4 contains a built-in mechanism that enables you to set default values, which you manage by using Anypoint Runtime Manager. For details, see [Introduction to Mule 4: Configuring Mule Apps](https://docs.mulesoft.com/mule-runtime/4.3/intro-configuration) and [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.3/configuring-properties). ## App-Building Best Practice As you build your Mule app, avoid packaging the configuration files for all the environments inside the application. Instead, use a `.yaml` file to provide default properties, and use Anypoint Runtime Manager to override each of these properties at deployment time. ## Components and Connectors Best Practices When building your apps using Mule components and connectors, consider the following recommendations. ### APIkit When using APIkit, consider these practices: - Use APIkit features to generate flows automatically using your API specification. - Use APIkit Exception Strategy to catch connector-related exceptions. ### DataWeave When using DataWeave for building your app, consider these recommendations: - Use inline scripts during the development phase. - To have a clean XML and reusable scripts, pass the inline scripts to an external file. ### Flows When creating flows for your app, consider the following practices: - Have a clear flow diagram showing the steps of the use case. - Use a Flow Reference to separate and reuse common logic. ### File Connector If you use Anypoint Connector for File (File Connector) and share part of the path on numerous reads or any other file operations, extract the base path into a file configuration to reuse it: ```xml ``` ### HTTP and HTTPS For HTTP and HTTPS ports in on-premises deployments, MuleSoft recommends using the names for property placeholders that are reserved for CloudHub deployments. The shared load balancer in CloudHub uses the defaults for these properties. - In CloudHub, `${http.port}` maps to the setting `port=8081`, and `${https.port}` maps to `port=8082`. - For internal ports to HTTP services in CloudHub deployments, `${http.private.port}` maps to the setting `port=8091`, and `${https.private.port}` maps to `port=8092`. For details about these settings in CloudHub, see [CloudHub Reserved Properties](https://docs.mulesoft.com/cloudhub/cloudhub-manage-props#cloudhub-reserved-properties) and [CloudHub Networking Guide](https://docs.mulesoft.com/cloudhub/cloudhub-networking-guide). ### Apache Kafka Connector If you use Anypoint Connector for Apache Kafka (Apache Kafka Connector) perform the following actions: - Use the `.properties` file to add bootstrap server configuration. - Add property placeholders, either in a `.yaml` or a `.properties` file, and use the file in the configuration: ```xml config.bootstrapServers={your Kafka Server address} config.consumerPropertiesFile=consumer.properties config.producerPropertiesFile=producer.properties # Consumer specific information consumer.topic=one-replica consumer.topic.partitions=1 ``` - Apache Kafka Connector provides various settings for producer and consumer properties, add your own settings in `consumer.properties` and `producer.properties` under `src/main/resource`: ```xml ``` ## See Also - [Apache Kafka Connector](https://docs.mulesoft.com/kafka-connector/latest/) - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) --- product: Mule Runtime version: 4.4 --- # Best Practices to Build Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. ## Anypoint Studio Best Practices If you use Anypoint Studio to build Mule apps, consider the following practices: - Update to the latest version of Anypoint Studio. - Use the recommended Java version (OpenJDK) for the specific Studio version. - Include the Mule Maven plugin for automated deployment (executed by CI/CD processes). ### Define a Project Structure To help maintain a clean, structured, and readable project in Anypoint Studio, consider the following recommendations: - Create a separate XML file for global elements, for example, configuration elements. - Create a separate XML file for each use case or resource implementation. - Create separate XML files for common structures or logic. - Create different packages for resources such as DataWeave, WSDLs, examples, and so on. #### Add Indentation and Formatting As you build your app project in Anypoint Studio, consider the following points: - Add indentation and format to all your XML files (Mule XMLs, `pom.xml`, `log4j2.xml`, and so on) before committing to the source code repository. - Define a line width in your Anypoint Studio XML editor preferences, for example `140.d`. - Define a naming convention. #### Manage Properties per Environment To avoid creating a separate set of variables for each environment, Mule 4 contains a built-in mechanism that enables you to set default values, which you manage by using Anypoint Runtime Manager. For details, see [Introduction to Mule 4: Configuring Mule Apps](https://docs.mulesoft.com/mule-runtime/4.4/intro-configuration) and [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.4/configuring-properties). ## App-Building Best Practice As you build your Mule app, avoid packaging the configuration files for all the environments inside the application. Instead, use a `.yaml` file to provide default properties, and use Anypoint Runtime Manager to override each of these properties at deployment time. ## Components and Connectors Best Practices When building your apps using Mule components and connectors, consider the following recommendations. ### APIkit When using APIkit, consider these practices: - Use APIkit features to generate flows automatically using your API specification. - Use APIkit Exception Strategy to catch connector-related exceptions. ### DataWeave When using DataWeave for building your app, consider these recommendations: - Use inline scripts during the development phase. - To have a clean XML and reusable scripts, pass the inline scripts to an external file. ### Flows When creating flows for your app, consider the following practices: - Have a clear flow diagram showing the steps of the use case. - Use a Flow Reference to separate and reuse common logic. ### File Connector If you use Anypoint Connector for File (File Connector) and share part of the path on numerous reads or any other file operations, extract the base path into a file configuration to reuse it: ```xml ``` ### HTTP and HTTPS For HTTP and HTTPS ports in on-premises deployments, MuleSoft recommends using the names for property placeholders that are reserved for CloudHub deployments. The shared load balancer in CloudHub uses the defaults for these properties. - In CloudHub, `${http.port}` maps to the setting `port=8081`, and `${https.port}` maps to `port=8082`. - For internal ports to HTTP services in CloudHub deployments, `${http.private.port}` maps to the setting `port=8091`, and `${https.private.port}` maps to `port=8092`. For details about these settings in CloudHub, see [CloudHub Reserved Properties](https://docs.mulesoft.com/cloudhub/cloudhub-manage-props#cloudhub-reserved-properties) and [CloudHub Networking Guide](https://docs.mulesoft.com/cloudhub/cloudhub-networking-guide). ### Apache Kafka Connector If you use Anypoint Connector for Apache Kafka (Apache Kafka Connector) perform the following actions: - Use the `.properties` file to add bootstrap server configuration. - Add property placeholders, either in a `.yaml` or a `.properties` file, and use the file in the configuration: ```xml config.bootstrapServers={your Kafka Server address} config.consumerPropertiesFile=consumer.properties config.producerPropertiesFile=producer.properties # Consumer specific information consumer.topic=one-replica consumer.topic.partitions=1 ``` - Apache Kafka Connector provides various settings for producer and consumer properties, add your own settings in `consumer.properties` and `producer.properties` under `src/main/resource`: ```xml ``` ## See Also - [Apache Kafka Connector](https://docs.mulesoft.com/kafka-connector/latest/) - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) --- product: Mule Runtime version: 4.6 --- # Best Practices to Build Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. ## Anypoint Studio Best Practices If you use Anypoint Studio to build Mule apps, consider the following practices: - Update to the latest version of Anypoint Studio. - Use the recommended Java version (OpenJDK) for the specific Studio version. - Include the Mule Maven plugin for automated deployment (executed by CI/CD processes). ### Define a Project Structure To help maintain a clean, structured, and readable project in Anypoint Studio, consider the following recommendations: - Create a separate XML file for global elements, for example, configuration elements. - Create a separate XML file for each use case or resource implementation. - Create separate XML files for common structures or logic. - Create different packages for resources such as DataWeave, WSDLs, examples, and so on. #### Add Indentation and Formatting As you build your app project in Anypoint Studio, consider the following points: - Add indentation and format to all your XML files (Mule XMLs, `pom.xml`, `log4j2.xml`, and so on) before committing to the source code repository. - Define a line width in your Anypoint Studio XML editor preferences, for example `140.d`. - Define a naming convention. #### Manage Properties per Environment To avoid creating a separate set of variables for each environment, Mule 4 contains a built-in mechanism that enables you to set default values, which you manage by using Anypoint Runtime Manager. For details, see [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-configuration) and [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.6/configuring-properties). ## App-Building Best Practice As you build your Mule app, avoid packaging the configuration files for all the environments inside the application. Instead, use a `.yaml` file to provide default properties, and use Anypoint Runtime Manager to override each of these properties at deployment time. ## Components and Connectors Best Practices When building your apps using Mule components and connectors, consider the following recommendations. ### APIkit When using APIkit, consider these practices: - Use APIkit features to generate flows automatically using your API specification. - Use APIkit Exception Strategy to catch connector-related exceptions. ### DataWeave When using DataWeave for building your app, consider these recommendations: - Use inline scripts during the development phase. - To have a clean XML and reusable scripts, pass the inline scripts to an external file. ### Flows When creating flows for your app, consider the following practices: - Have a clear flow diagram showing the steps of the use case. - Use a Flow Reference to separate and reuse common logic. ### File Connector If you use Anypoint Connector for File (File Connector) and share part of the path on numerous reads or any other file operations, extract the base path into a file configuration to reuse it: ```xml ``` ### HTTP and HTTPS For HTTP and HTTPS ports in on-premises deployments, MuleSoft recommends using the names for property placeholders that are reserved for CloudHub deployments. The shared load balancer in CloudHub uses the defaults for these properties. - In CloudHub, `${http.port}` maps to the setting `port=8081`, and `${https.port}` maps to `port=8082`. - For internal ports to HTTP services in CloudHub deployments, `${http.private.port}` maps to the setting `port=8091`, and `${https.private.port}` maps to `port=8092`. For details about these settings in CloudHub, see [CloudHub Reserved Properties](https://docs.mulesoft.com/cloudhub/cloudhub-manage-props#cloudhub-reserved-properties) and [CloudHub Networking Guide](https://docs.mulesoft.com/cloudhub/cloudhub-networking-guide). ### Apache Kafka Connector If you use Anypoint Connector for Apache Kafka (Apache Kafka Connector) perform the following actions: - Use the `.properties` file to add bootstrap server configuration. - Add property placeholders, either in a `.yaml` or a `.properties` file, and use the file in the configuration: ```xml config.bootstrapServers={your Kafka Server address} config.consumerPropertiesFile=consumer.properties config.producerPropertiesFile=producer.properties # Consumer specific information consumer.topic=one-replica consumer.topic.partitions=1 ``` - Apache Kafka Connector provides various settings for producer and consumer properties, add your own settings in `consumer.properties` and `producer.properties` under `src/main/resource`: ```xml ``` ## See Also - [Apache Kafka Connector](https://docs.mulesoft.com/kafka-connector/latest/) - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) --- product: Mule Runtime version: 4.9 --- # Best Practices to Build Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. ## Anypoint Studio Best Practices If you use Anypoint Studio to build Mule apps, consider the following practices: - Update to the latest version of Anypoint Studio. - Use the recommended Java version (OpenJDK) for the specific Studio version. - Include the Mule Maven plugin for automated deployment (executed by CI/CD processes). ### Define a Project Structure To help maintain a clean, structured, and readable project in Anypoint Studio, consider the following recommendations: - Create a separate XML file for global elements, for example, configuration elements. - Create a separate XML file for each use case or resource implementation. - Create separate XML files for common structures or logic. - Create different packages for resources such as DataWeave, WSDLs, examples, and so on. #### Add Indentation and Formatting As you build your app project in Anypoint Studio, consider the following points: - Add indentation and format to all your XML files (Mule XMLs, `pom.xml`, `log4j2.xml`, and so on) before committing to the source code repository. - Define a line width in your Anypoint Studio XML editor preferences, for example `140.d`. - Define a naming convention. #### Manage Properties per Environment To avoid creating a separate set of variables for each environment, Mule 4 contains a built-in mechanism that enables you to set default values, which you manage by using Anypoint Runtime Manager. For details, see [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-configuration) and [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.9/configuring-properties). ## App-Building Best Practice As you build your Mule app, avoid packaging the configuration files for all the environments inside the application. Instead, use a `.yaml` file to provide default properties, and use Anypoint Runtime Manager to override each of these properties at deployment time. ## Components and Connectors Best Practices When building your apps using Mule components and connectors, consider the following recommendations. ### APIkit When using APIkit, consider these practices: - Use APIkit features to generate flows automatically using your API specification. - Use APIkit Exception Strategy to catch connector-related exceptions. ### DataWeave When using DataWeave for building your app, consider these recommendations: - Use inline scripts during the development phase. - To have a clean XML and reusable scripts, pass the inline scripts to an external file. ### Flows When creating flows for your app, consider the following practices: - Have a clear flow diagram showing the steps of the use case. - Use a Flow Reference to separate and reuse common logic. ### File Connector If you use Anypoint Connector for File (File Connector) and share part of the path on numerous reads or any other file operations, extract the base path into a file configuration to reuse it: ```xml ``` ### HTTP and HTTPS For HTTP and HTTPS ports in on-premises deployments, MuleSoft recommends using the names for property placeholders that are reserved for CloudHub deployments. The shared load balancer in CloudHub uses the defaults for these properties. - In CloudHub, `${http.port}` maps to the setting `port=8081`, and `${https.port}` maps to `port=8082`. - For internal ports to HTTP services in CloudHub deployments, `${http.private.port}` maps to the setting `port=8091`, and `${https.private.port}` maps to `port=8092`. For details about these settings in CloudHub, see [CloudHub Reserved Properties](https://docs.mulesoft.com/cloudhub/cloudhub-manage-props#cloudhub-reserved-properties) and [CloudHub Networking Guide](https://docs.mulesoft.com/cloudhub/cloudhub-networking-guide). ### Apache Kafka Connector If you use Anypoint Connector for Apache Kafka (Apache Kafka Connector) perform the following actions: - Use the `.properties` file to add bootstrap server configuration. - Add property placeholders, either in a `.yaml` or a `.properties` file, and use the file in the configuration: ```xml config.bootstrapServers={your Kafka Server address} config.consumerPropertiesFile=consumer.properties config.producerPropertiesFile=producer.properties # Consumer specific information consumer.topic=one-replica consumer.topic.partitions=1 ``` - Apache Kafka Connector provides various settings for producer and consumer properties, add your own settings in `consumer.properties` and `producer.properties` under `src/main/resource`: ```xml ``` ## See Also - [Apache Kafka Connector](https://docs.mulesoft.com/kafka-connector/latest/) - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Best Practices to Build Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. ## Anypoint Studio Best Practices If you use Anypoint Studio to build Mule apps, consider the following practices: - Update to the latest version of Anypoint Studio. - Use the recommended Java version (OpenJDK) for the specific Studio version. - Include the Mule Maven plugin for automated deployment (executed by CI/CD processes). ### Define a Project Structure To help maintain a clean, structured, and readable project in Anypoint Studio, consider the following recommendations: - Create a separate XML file for global elements, for example, configuration elements. - Create a separate XML file for each use case or resource implementation. - Create separate XML files for common structures or logic. - Create different packages for resources such as DataWeave, WSDLs, examples, and so on. #### Add Indentation and Formatting As you build your app project in Anypoint Studio, consider the following points: - Add indentation and format to all your XML files (Mule XMLs, `pom.xml`, `log4j2.xml`, and so on) before committing to the source code repository. - Define a line width in your Anypoint Studio XML editor preferences, for example `140.d`. - Define a naming convention. #### Manage Properties per Environment To avoid creating a separate set of variables for each environment, Mule 4 contains a built-in mechanism that enables you to set default values, which you manage by using Anypoint Runtime Manager. For details, see [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/latest/about-mule-configuration) and [Configuring Properties](https://docs.mulesoft.com/mule-runtime/latest/configuring-properties). ## App-Building Best Practice As you build your Mule app, avoid packaging the configuration files for all the environments inside the application. Instead, use a `.yaml` file to provide default properties, and use Anypoint Runtime Manager to override each of these properties at deployment time. ## Components and Connectors Best Practices When building your apps using Mule components and connectors, consider the following recommendations. ### APIkit When using APIkit, consider these practices: - Use APIkit features to generate flows automatically using your API specification. - Use APIkit Exception Strategy to catch connector-related exceptions. ### DataWeave When using DataWeave for building your app, consider these recommendations: - Use inline scripts during the development phase. - To have a clean XML and reusable scripts, pass the inline scripts to an external file. ### Flows When creating flows for your app, consider the following practices: - Have a clear flow diagram showing the steps of the use case. - Use a Flow Reference to separate and reuse common logic. ### File Connector If you use Anypoint Connector for File (File Connector) and share part of the path on numerous reads or any other file operations, extract the base path into a file configuration to reuse it: ```xml ``` ### HTTP and HTTPS For HTTP and HTTPS ports in on-premises deployments, MuleSoft recommends using the names for property placeholders that are reserved for CloudHub deployments. The shared load balancer in CloudHub uses the defaults for these properties. - In CloudHub, `${http.port}` maps to the setting `port=8081`, and `${https.port}` maps to `port=8082`. - For internal ports to HTTP services in CloudHub deployments, `${http.private.port}` maps to the setting `port=8091`, and `${https.private.port}` maps to `port=8092`. For details about these settings in CloudHub, see [CloudHub Reserved Properties](https://docs.mulesoft.com/cloudhub/cloudhub-manage-props#cloudhub-reserved-properties) and [CloudHub Networking Guide](https://docs.mulesoft.com/cloudhub/cloudhub-networking-guide). ### Apache Kafka Connector If you use Anypoint Connector for Apache Kafka (Apache Kafka Connector) perform the following actions: - Use the `.properties` file to add bootstrap server configuration. - Add property placeholders, either in a `.yaml` or a `.properties` file, and use the file in the configuration: ```xml config.bootstrapServers={your Kafka Server address} config.consumerPropertiesFile=consumer.properties config.producerPropertiesFile=producer.properties # Consumer specific information consumer.topic=one-replica consumer.topic.partitions=1 ``` - Apache Kafka Connector provides various settings for producer and consumer properties, add your own settings in `consumer.properties` and `producer.properties` under `src/main/resource`: ```xml ``` ## See Also - [Apache Kafka Connector](https://docs.mulesoft.com/kafka-connector/latest/) - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) --- product: Mule Runtime version: 4.11 keywords: build, application, api, specification --- # Build an Application from an API Specification > For the full documentation index, see: https://docs.mulesoft.com/llms.txt During your app development lifecycle, you can build Mule REST or SOAP APIs from an API specification using APIkit. You develop APIs based on the following modeling languages: - RAML (RESTful API Modeling Language) - WSDL (Web Service Description Language) - OData (OData-Enabled APIs using APIkit OData Extension) - OAS (Open API Specification) By using APIkit in Anypoint Studio, you can simplify the design and implementation of APIs by automating Mule flow creation based on importing either a RAML or a WSDL specification file. After generating the API, you can perform calls to test the API and then finalize its implementation. Additionally, APIkit helps you build applications using Apache Maven, and also provides a CLI tool to generate flows for an already existing application. However, before you perform any of these tasks, you must learn the basic APIkit anatomy and understand the scaffolding technique that generates Mule flows when you start APIkit projects. ## APIkit Anatomy A REST or SOAP Studio project that uses APIkit has the following parts: - A REST or SOAP interface - A main flow - Backend flows ![A REST Studio project showing components including APIkit Router and API console](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-rest-studio-project.png) Figure 1. REST Studio Project. ![A SOAP Studio project showing components including SOAP Router and Transform Message](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-soap-studio-project.png) Figure 2. SOAP Studio Project. ### REST Interface The relationship between REST resources and actions is called _resource-action_ pairing. The interface exposes internal data assets requested by the REST service. Also, the interface defines the API, designating resources that contain or access data and specify actions, such as GET and PUT, on the example data. ### SOAP Interface The interface defined by a WSDL file exposes a number of services. Each service has a set of operations. The underlying type of data is XML defined by schemas within the WSDL file or by an imported XSD file. ### Main Flow The main flow for the API manages these functions: - Exposes the API using Anypoint Connector for HTTP (HTTP Connector). - Routes requests between the interface and the backend flows based on the HTTP request. - Accepts requests, sends responses, and facilitates communication between the interface and API processes. The main flow consists of HTTP Listener and APIkit (REST or SOAP) Router components. The APIkit Router is a key message processor that validates requests against the provided definition, enriches messages (for example by adding default values to the messages) and routes requests to a particular flow. Also, the Router raises errors messages if errors occurs while routing, validating or processing the user request. ![A REST API main flow with components including Listener and APIkit Router](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-rest-main-flow.png) Figure 3. REST API Main Flow. ![A SOAP API main flow with components including Listener and SOAP Router](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-soap-main-flow.png) Figure 4. SOAP API Main Flow. ### Backend Flows APIkit for REST generates a backend flow for each resource-action pairing in a RAML file. APIkit for SOAP generates a backend flow for each operation in a WSDL. In the following example, the RAML interface receives the GET request users. The backend flow accesses a database to look up users by ID. ![REST API backend flows](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-rest-backend-flows.png) Figure 5. REST API Backend Flows. ### Perform Calls For REST APIs, use API Console to perform calls to the API. For SOAP APIs, use a SOAP testing tool such as SoapUI to perform calls to the API. ## Start APIkit Project and Generate Mule Flows When you start a new APIkit project in Studio, you have the option to import an API definition file. When you import the file, the APIkit scaffolding mechanism generates different flows for the API. There are three ways to start an APIkit project in Anypoint Studio: ### Start a New APIkit Project Using an API Definition File Use this method if you want to start a project by either importing an existing RAML or WSDL file or by referencing the file URL: 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, select **Specify API Definition File Location or URL**. 5. In **Location**, do one of the following: - If you created an `api.raml` file in Design Center, select **Design Center** . Login to Anypoint Platform if necessary, and select `api.raml`. - If you didn’t create a RAML file in Design Center, select **Browse Files** and select the RAML or WSDL file that you created in a text editor. For a WSDL file, select a service and port from the drop-down menus or accept the defaults. 6. Accept the Location default options, and click **Finish**. ![A new Mule project with an API specification selected](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-start-apikit-project-1.png) Figure 6. New Mule Project window selecting API specification . Using this method the APIkit scaffolding technique generates: - An archetype that contains basic configuration files plus a Mule XML configuration file - An implementation of the API For RAML-based APIs, the RAML file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A main flow with an HTTP Listener - APIkit Router component - Error handlers - RAML dependencies (push or pull changes from one location, such as Studio, to the other, such as Design Center) - Backend flows containing REST resource-action mappings For WSDL-based APIs, the WSDL file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A SOAP Router - A SOAP fault response template - Backend flows containing SOAP message templates The following graphics illustrate the APIkit scaffolding: ![XML configuration for RAML scaffolding including Listener, APIkit Router, and Error handling components.](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-raml-scaffolding.png) Figure 7. RAML Scaffolding. ![XML configuration for WSDL scaffolding including Listener, SOAP Router, and Error handling components](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-wsdl-scaffolding.png) Figure 8. WSDL Scaffolding. In Studio, the REST API APIkit project looks like this: ![An APIkit project with files and configurations for handling REST API requests.](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-rest-api-studio-apikit.png) Figure 9. REST API in Anypoint Studio UI with the Package Explorer and Canvas sections. The five items illustrated here show: 1. The project files in the Package Explorer of Studio with the `api.raml` file under `src/main/resources/api` folder. 2. The main flow, with the APIkit Router. 3. APIkit Console 4. Error Handling 5. Generated flows for each resource method. The generated minimal flows meets the communication operations required by a REST contract. In Studio, the SOAP API APIkit project looks like this: ![A REST API APIkit project setup showing the Package Explorer and canvas in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-soap-api-studio-apikit.png) Figure 10. SOAP API in Anypoint Studio UI with the Package Explorer and Canvas sections. The four items illustrated here show: 1. The project files in the Package Explorer of Studio with the `example.wsdl` file under `src/main/resources/api` folder. 2. The main flow, with the SOAP Router. 3. SOAP fault response template 4. Generated backend flows containing SOAP message templates. After you create your APIkit project, you can continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project Use this method if you start an APIkit project without an API specification file and you can later add it into the project. APIkit generates a skeletal RAML file and XML configuration file. 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE . Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, do _not_ select **Specify API Definition File Location or URL**. This creates the backend-first APIkit design. 5. Accept the other default options, and click **Finish**. ![A new Mule project without an API specification](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-start-apikit-project-2.png) Figure 11. New Mule Project window. Using this method the APIkit scaffolding generates a skeletal RAML file and XML configuration file that includes the following components: - A main flow `` - HTTP Listener configuration in the main flow - APIkit Router component - Error handlers You can later add an API specification to the backend-first APIkit design and generate backend flows to continue building the application. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project by Generating Backend Flows To perform this task, you must have met the following prerequisites: - Created a RAML file in Studio (RAML editor) - Created a main flow with an HTTP Listener and APIkit Router components When you create a RAML file in Studio, generating backend flows is optional. Error handling is generated automatically for a RAML-based API. To start the APIkit project, you need to generate the backend flows from the main flow. Follow the next steps: 1. In Package Explorer, right-click the project name. 2. Select **Mule > Generate Flows From REST API**. ![A Package Explorer view showing options for generating backend flows from Mule project](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-start-apikit-project-3.png) Figure 12. Generating backend flows from Mule Project. The APIkit scaffolding technique generates the backend flows following the main flow. You can then continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ## Build Applications Workflows After you are familiar with the basic APIkit anatomy and the scaffolding technique, examine the following workflows to help you build your desired application by creating the APIkit project, generating Mule flows, performing calls to the API, and finalizing its implementation: - [Build a REST API using APIKit for REST](https://docs.mulesoft.com/apikit/latest/apikit-4-for-rest) - [Build a SOAP API using APKit for SOAP](https://docs.mulesoft.com/apikit/latest/apikit-4-for-soap) Additionally, you can: - [Convert an Existing Mule Project to an APIkit Project](https://docs.mulesoft.com/apikit/latest/apikit-workflow-convert-existing) Add an API specification to an existing APIkit backend-first design, define API definition files, create main flow, generate backend REST API flows, map RAML resources to actions. - [Perform APIkit 4.x Tasks](https://docs.mulesoft.com/apikit/latest/key-configurations) Change APIkit project, customize API console, configure headers, retrieve RAML files, execute nonfunctional requirements, configure load balancers. - [Create an Enable O-Data API using the APIkit OData Extension](https://docs.mulesoft.com/apikit/latest/creating-an-odatav4-api-with-apikit) Generate Mule flows to handle OData requests. - [Create an APIkit project with Maven](https://docs.mulesoft.com/apikit/latest/apikit-4-scaffolding-reference) Add APIkit components to an existing Apache Maven project. ## Consume Data from an API After you build your application, you can start consuming data from the API. Review the [Consume Data from an API documentation](https://docs.mulesoft.com/mule-runtime/4.11/consume-data-from-an-api) for guidelines. ## See Also - [APIkit](https://docs.mulesoft.com/apikit/latest/) - [APIKit Handling Errors](https://docs.mulesoft.com/apikit/latest/apikit-error-handling-reference) --- product: Mule Runtime version: 4.12 keywords: build, application, api, specification --- # Build an Application from an API Specification > For the full documentation index, see: https://docs.mulesoft.com/llms.txt During your app development lifecycle, you can build Mule REST or SOAP APIs from an API specification using APIkit. You develop APIs based on the following modeling languages: - RAML (RESTful API Modeling Language) - WSDL (Web Service Description Language) - OData (OData-Enabled APIs using APIkit OData Extension) - OAS (Open API Specification) By using APIkit in Anypoint Studio, you can simplify the design and implementation of APIs by automating Mule flow creation based on importing either a RAML or a WSDL specification file. After generating the API, you can perform calls to test the API and then finalize its implementation. Additionally, APIkit helps you build applications using Apache Maven, and also provides a CLI tool to generate flows for an already existing application. However, before you perform any of these tasks, you must learn the basic APIkit anatomy and understand the scaffolding technique that generates Mule flows when you start APIkit projects. ## APIkit Anatomy A REST or SOAP Studio project that uses APIkit has the following parts: - A REST or SOAP interface - A main flow - Backend flows ![A REST Studio project showing components including APIkit Router and API console](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-rest-studio-project.png) Figure 1. REST Studio Project. ![A SOAP Studio project showing components including SOAP Router and Transform Message](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-soap-studio-project.png) Figure 2. SOAP Studio Project. ### REST Interface The relationship between REST resources and actions is called _resource-action_ pairing. The interface exposes internal data assets requested by the REST service. Also, the interface defines the API, designating resources that contain or access data and specify actions, such as GET and PUT, on the example data. ### SOAP Interface The interface defined by a WSDL file exposes a number of services. Each service has a set of operations. The underlying type of data is XML defined by schemas within the WSDL file or by an imported XSD file. ### Main Flow The main flow for the API manages these functions: - Exposes the API using Anypoint Connector for HTTP (HTTP Connector). - Routes requests between the interface and the backend flows based on the HTTP request. - Accepts requests, sends responses, and facilitates communication between the interface and API processes. The main flow consists of HTTP Listener and APIkit (REST or SOAP) Router components. The APIkit Router is a key message processor that validates requests against the provided definition, enriches messages (for example by adding default values to the messages) and routes requests to a particular flow. Also, the Router raises errors messages if errors occurs while routing, validating or processing the user request. ![A REST API main flow with components including Listener and APIkit Router](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-rest-main-flow.png) Figure 3. REST API Main Flow. ![A SOAP API main flow with components including Listener and SOAP Router](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-soap-main-flow.png) Figure 4. SOAP API Main Flow. ### Backend Flows APIkit for REST generates a backend flow for each resource-action pairing in a RAML file. APIkit for SOAP generates a backend flow for each operation in a WSDL. In the following example, the RAML interface receives the GET request users. The backend flow accesses a database to look up users by ID. ![REST API backend flows](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-rest-backend-flows.png) Figure 5. REST API Backend Flows. ### Perform Calls For REST APIs, use API Console to perform calls to the API. For SOAP APIs, use a SOAP testing tool such as SoapUI to perform calls to the API. ## Start APIkit Project and Generate Mule Flows When you start a new APIkit project in Studio, you have the option to import an API definition file. When you import the file, the APIkit scaffolding mechanism generates different flows for the API. There are three ways to start an APIkit project in Anypoint Studio: ### Start a New APIkit Project Using an API Definition File Use this method if you want to start a project by either importing an existing RAML or WSDL file or by referencing the file URL: 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, select **Specify API Definition File Location or URL**. 5. In **Location**, do one of the following: - If you created an `api.raml` file in Design Center, select **Design Center** . Login to Anypoint Platform if necessary, and select `api.raml`. - If you didn’t create a RAML file in Design Center, select **Browse Files** and select the RAML or WSDL file that you created in a text editor. For a WSDL file, select a service and port from the drop-down menus or accept the defaults. 6. Accept the Location default options, and click **Finish**. ![A new Mule project with an API specification selected](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-start-apikit-project-1.png) Figure 6. New Mule Project window selecting API specification . Using this method the APIkit scaffolding technique generates: - An archetype that contains basic configuration files plus a Mule XML configuration file - An implementation of the API For RAML-based APIs, the RAML file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A main flow with an HTTP Listener - APIkit Router component - Error handlers - RAML dependencies (push or pull changes from one location, such as Studio, to the other, such as Design Center) - Backend flows containing REST resource-action mappings For WSDL-based APIs, the WSDL file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A SOAP Router - A SOAP fault response template - Backend flows containing SOAP message templates The following graphics illustrate the APIkit scaffolding: ![XML configuration for RAML scaffolding including Listener, APIkit Router, and Error handling components.](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-raml-scaffolding.png) Figure 7. RAML Scaffolding. ![XML configuration for WSDL scaffolding including Listener, SOAP Router, and Error handling components](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-wsdl-scaffolding.png) Figure 8. WSDL Scaffolding. In Studio, the REST API APIkit project looks like this: ![An APIkit project with files and configurations for handling REST API requests.](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-rest-api-studio-apikit.png) Figure 9. REST API in Anypoint Studio UI with the Package Explorer and Canvas sections. The five items illustrated here show: 1. The project files in the Package Explorer of Studio with the `api.raml` file under `src/main/resources/api` folder. 2. The main flow, with the APIkit Router. 3. APIkit Console 4. Error Handling 5. Generated flows for each resource method. The generated minimal flows meets the communication operations required by a REST contract. In Studio, the SOAP API APIkit project looks like this: ![A REST API APIkit project setup showing the Package Explorer and canvas in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-soap-api-studio-apikit.png) Figure 10. SOAP API in Anypoint Studio UI with the Package Explorer and Canvas sections. The four items illustrated here show: 1. The project files in the Package Explorer of Studio with the `example.wsdl` file under `src/main/resources/api` folder. 2. The main flow, with the SOAP Router. 3. SOAP fault response template 4. Generated backend flows containing SOAP message templates. After you create your APIkit project, you can continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project Use this method if you start an APIkit project without an API specification file and you can later add it into the project. APIkit generates a skeletal RAML file and XML configuration file. 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE . Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, do _not_ select **Specify API Definition File Location or URL**. This creates the backend-first APIkit design. 5. Accept the other default options, and click **Finish**. ![A new Mule project without an API specification](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-start-apikit-project-2.png) Figure 11. New Mule Project window. Using this method the APIkit scaffolding generates a skeletal RAML file and XML configuration file that includes the following components: - A main flow `` - HTTP Listener configuration in the main flow - APIkit Router component - Error handlers You can later add an API specification to the backend-first APIkit design and generate backend flows to continue building the application. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project by Generating Backend Flows To perform this task, you must have met the following prerequisites: - Created a RAML file in Studio (RAML editor) - Created a main flow with an HTTP Listener and APIkit Router components When you create a RAML file in Studio, generating backend flows is optional. Error handling is generated automatically for a RAML-based API. To start the APIkit project, you need to generate the backend flows from the main flow. Follow the next steps: 1. In Package Explorer, right-click the project name. 2. Select **Mule > Generate Flows From REST API**. ![A Package Explorer view showing options for generating backend flows from Mule project](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-start-apikit-project-3.png) Figure 12. Generating backend flows from Mule Project. The APIkit scaffolding technique generates the backend flows following the main flow. You can then continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ## Build Applications Workflows After you are familiar with the basic APIkit anatomy and the scaffolding technique, examine the following workflows to help you build your desired application by creating the APIkit project, generating Mule flows, performing calls to the API, and finalizing its implementation: - [Build a REST API using APIKit for REST](https://docs.mulesoft.com/apikit/latest/apikit-4-for-rest) - [Build a SOAP API using APKit for SOAP](https://docs.mulesoft.com/apikit/latest/apikit-4-for-soap) Additionally, you can: - [Convert an Existing Mule Project to an APIkit Project](https://docs.mulesoft.com/apikit/latest/apikit-workflow-convert-existing) Add an API specification to an existing APIkit backend-first design, define API definition files, create main flow, generate backend REST API flows, map RAML resources to actions. - [Perform APIkit 4.x Tasks](https://docs.mulesoft.com/apikit/latest/key-configurations) Change APIkit project, customize API console, configure headers, retrieve RAML files, execute nonfunctional requirements, configure load balancers. - [Create an Enable O-Data API using the APIkit OData Extension](https://docs.mulesoft.com/apikit/latest/creating-an-odatav4-api-with-apikit) Generate Mule flows to handle OData requests. - [Create an APIkit project with Maven](https://docs.mulesoft.com/apikit/latest/apikit-4-scaffolding-reference) Add APIkit components to an existing Apache Maven project. ## Consume Data from an API After you build your application, you can start consuming data from the API. Review the [Consume Data from an API documentation](https://docs.mulesoft.com/mule-runtime/4.12/consume-data-from-an-api) for guidelines. ## See Also - [APIkit](https://docs.mulesoft.com/apikit/latest/) - [APIKit Handling Errors](https://docs.mulesoft.com/apikit/latest/apikit-error-handling-reference) --- product: Mule Runtime version: 4.3 keywords: build, application, api, specification --- # Build an Application from an API Specification > For the full documentation index, see: https://docs.mulesoft.com/llms.txt During your app development lifecycle, you can build Mule REST or SOAP APIs from an API specification using APIkit. You develop APIs based on the following modeling languages: - RAML (RESTful API Modeling Language) - WSDL (Web Service Description Language) - OData (OData-Enabled APIs using APIkit OData Extension) - OAS (Open API Specification) By using APIkit in Anypoint Studio, you can simplify the design and implementation of APIs by automating Mule flow creation based on importing either a RAML or a WSDL specification file. After generating the API, you can perform calls to test the API and then finalize its implementation. Additionally, APIkit helps you build applications using Apache Maven, and also provides a CLI tool to generate flows for an already existing application. However, before you perform any of these tasks, you must learn the basic APIkit anatomy and understand the scaffolding technique that generates Mule flows when you start APIkit projects. ## APIkit Anatomy A REST or SOAP Studio project that uses APIkit has the following parts: - A REST or SOAP interface - A main flow - Backend flows ![REST Studio Project](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-rest-studio-project.png) Figure 1. REST Studio Project. ![SOAP Studio Project](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-soap-studio-project.png) Figure 2. SOAP Studio Project. ### REST Interface The relationship between REST resources and actions is called _resource-action_ pairing. The interface exposes internal data assets requested by the REST service. Also, the interface defines the API, designating resources that contain or access data and specify actions, such as GET and PUT, on the example data. ### SOAP Interface The interface defined by a WSDL file exposes a number of services. Each service has a set of operations. The underlying type of data is XML defined by schemas within the WSDL file or by an imported XSD file. ### Main Flow The main flow for the API manages these functions: - Exposes the API using Anypoint Connector for HTTP (HTTP Connector). - Routes requests between the interface and the backend flows based on the HTTP request. - Accepts requests, sends responses, and facilitates communication between the interface and API processes. The main flow consists of HTTP Listener and APIkit (REST or SOAP) Router components. The APIkit Router is a key message processor that validates requests against the provided definition, enriches messages (for example by adding default values to the messages) and routes requests to a particular flow. Also, the Router raises errors messages if errors occurs while routing, validating or processing the user request. ![REST API Main Flow](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-rest-main-flow.png) Figure 3. REST API Main Flow. ![SOAP API Main Flow](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-soap-main-flow.png) Figure 4. SOAP API Main Flow. ### Backend Flows APIkit for REST generates a backend flow for each resource-action pairing in a RAML file. APIkit for SOAP generates a backend flow for each operation in a WSDL. In the following example, the RAML interface receives the GET request users. The backend flow accesses a database to look up users by ID. ![REST API Backend Flows](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-rest-backend-flows.png) Figure 5. REST API Backend Flows. ### Perform Calls For REST APIs, use API Console to perform calls to the API. For SOAP APIs, use a SOAP testing tool such as SoapUI to perform calls to the API. ## Start APIkit Project and Generate Mule Flows When you start a new APIkit project in Studio, you have the option to import an API definition file. When you import the file, the APIkit scaffolding mechanism generates different flows for the API. There are three ways to start an APIkit project in Anypoint Studio: ### Start a New APIkit Project Using an API Definition File Use this method if you want to start a project by either importing an existing RAML or WSDL file or by referencing the file URL: 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, select **Specify API Definition File Location or URL**. 5. In **Location**, do one of the following: - If you created an `api.raml` file in Design Center, select **Design Center** . Login to Anypoint Platform if necessary, and select `api.raml`. - If you didn’t create a RAML file in Design Center, select **Browse Files** and select the RAML or WSDL file that you created in a text editor. For a WSDL file, select a service and port from the drop-down menus or accept the defaults. 6. Accept the Location default options, and click **Finish**. ![New Mule Project with API Specification selected](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-start-apikit-project-1.png) Figure 6. New Mule Project window selecting API specification . Using this method the APIkit scaffolding technique generates: - An archetype that contains basic configuration files plus a Mule XML configuration file - An implementation of the API For RAML-based APIs, the RAML file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A main flow with an HTTP Listener - APIkit Router component - Error handlers - RAML dependencies (push or pull changes from one location, such as Studio, to the other, such as Design Center) - Backend flows containing REST resource-action mappings For WSDL-based APIs, the WSDL file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A SOAP Router - A SOAP fault response template - Backend flows containing SOAP message templates The following graphics illustrate the APIkit scaffolding: ![RAML Scaffolding](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-raml-scaffolding.png) Figure 7. RAML Scaffolding. ![WSDL Scaffolding](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-wsdl-scaffolding.png) Figure 8. WSDL Scaffolding. In Studio, the REST API APIkit project looks like this: ![REST API Anypoint Studio UI with the Package Explorer and Canvas sections](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-rest-api-studio-apikit.png) Figure 9. REST API in Anypoint Studio UI with the Package Explorer and Canvas sections. The five items illustrated here show: 1. The project files in the Package Explorer of Studio with the `api.raml` file under `src/main/resources/api` folder. 2. The main flow, with the APIkit Router. 3. APIkit Console 4. Error Handling 5. Generated flows for each resource method. The generated minimal flows meets the communication operations required by a REST contract. In Studio, the SOAP API APIkit project looks like this: ![SOAP API Anypoint Studio UI with the Package Explorer and Canvas sections](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-soap-api-studio-apikit.png) Figure 10. SOAP API in Anypoint Studio UI with the Package Explorer and Canvas sections. The four items illustrated here show: 1. The project files in the Package Explorer of Studio with the `example.wsdl` file under `src/main/resources/api` folder. 2. The main flow, with the SOAP Router. 3. SOAP fault response template 4. Generated backend flows containing SOAP message templates. After you create your APIkit project, you can continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project Use this method if you start an APIkit project without an API specification file and you can later add it into the project. APIkit generates a skeletal RAML file and XML configuration file. 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE . Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, do _not_ select **Specify API Definition File Location or URL**. This creates the backend-first APIkit design. 5. Accept the other default options, and click **Finish**. ![New Mule Project window without API specification](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-start-apikit-project-2.png) Figure 11. New Mule Project window. Using this method the APIkit scaffolding generates a skeletal RAML file and XML configuration file that includes the following components: - A main flow `` - HTTP Listener configuration in the main flow - APIkit Router component - Error handlers You can later add an API specification to the backend-first APIkit design and generate backend flows to continue building the application. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project by Generating Backend Flows To perform this task, you must have met the following prerequisites: - Created a RAML file in Studio (RAML editor) - Created a main flow with an HTTP Listener and APIkit Router components When you create a RAML file in Studio, generating backend flows is optional. Error handling is generated automatically for a RAML-based API. To start the APIkit project, you need to generate the backend flows from the main flow. Follow the next steps: 1. In Package Explorer, right-click the project name. 2. Select **Mule > Generate Flows From REST API**. ![Generating backend flows from Mule Project](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-start-apikit-project-3.png) Figure 12. Generating backend flows from Mule Project. The APIkit scaffolding technique generates the backend flows following the main flow. You can then continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ## Build Applications Workflows After you are familiar with the basic APIkit anatomy and the scaffolding technique, examine the following workflows to help you build your desired application by creating the APIkit project, generating Mule flows, performing calls to the API, and finalizing its implementation: - [Build a REST API using APIKit for REST](https://docs.mulesoft.com/apikit/latest/apikit-4-for-rest) - [Build a SOAP API using APKit for SOAP](https://docs.mulesoft.com/apikit/latest/apikit-4-for-soap) Additionally, you can: - [Convert an Existing Mule Project to an APIkit Project](https://docs.mulesoft.com/apikit/latest/apikit-workflow-convert-existing) Add an API specification to an existing APIkit backend-first design, define API definition files, create main flow, generate backend REST API flows, map RAML resources to actions. - [Perform APIkit 4.x Tasks](https://docs.mulesoft.com/apikit/latest/key-configurations) Change APIkit project, customize API console, configure headers, retrieve RAML files, execute nonfunctional requirements, configure load balancers. - [Create an Enable O-Data API using the APIkit OData Extension](https://docs.mulesoft.com/apikit/latest/creating-an-odatav4-api-with-apikit) Generate Mule flows to handle OData requests. - [Create an APIkit project with Maven](https://docs.mulesoft.com/apikit/latest/apikit-4-scaffolding-reference) Add APIkit components to an existing Apache Maven project. ## Consume Data from an API After you build your application, you can start consuming data from the API. Review the [Consume Data from an API documentation](https://docs.mulesoft.com/mule-runtime/4.3/consume-data-from-an-api) for guidelines. ## See Also - [APIkit](https://docs.mulesoft.com/apikit/latest/) - [APIKit Handling Errors](https://docs.mulesoft.com/apikit/latest/apikit-error-handling-reference) --- product: Mule Runtime version: 4.4 keywords: build, application, api, specification --- # Build an Application from an API Specification > For the full documentation index, see: https://docs.mulesoft.com/llms.txt During your app development lifecycle, you can build Mule REST or SOAP APIs from an API specification using APIkit. You develop APIs based on the following modeling languages: - RAML (RESTful API Modeling Language) - WSDL (Web Service Description Language) - OData (OData-Enabled APIs using APIkit OData Extension) - OAS (Open API Specification) By using APIkit in Anypoint Studio, you can simplify the design and implementation of APIs by automating Mule flow creation based on importing either a RAML or a WSDL specification file. After generating the API, you can perform calls to test the API and then finalize its implementation. Additionally, APIkit helps you build applications using Apache Maven, and also provides a CLI tool to generate flows for an already existing application. However, before you perform any of these tasks, you must learn the basic APIkit anatomy and understand the scaffolding technique that generates Mule flows when you start APIkit projects. ## APIkit Anatomy A REST or SOAP Studio project that uses APIkit has the following parts: - A REST or SOAP interface - A main flow - Backend flows ![REST Studio Project](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-rest-studio-project.png) Figure 1. REST Studio Project. ![SOAP Studio Project](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-soap-studio-project.png) Figure 2. SOAP Studio Project. ### REST Interface The relationship between REST resources and actions is called _resource-action_ pairing. The interface exposes internal data assets requested by the REST service. Also, the interface defines the API, designating resources that contain or access data and specify actions, such as GET and PUT, on the example data. ### SOAP Interface The interface defined by a WSDL file exposes a number of services. Each service has a set of operations. The underlying type of data is XML defined by schemas within the WSDL file or by an imported XSD file. ### Main Flow The main flow for the API manages these functions: - Exposes the API using Anypoint Connector for HTTP (HTTP Connector). - Routes requests between the interface and the backend flows based on the HTTP request. - Accepts requests, sends responses, and facilitates communication between the interface and API processes. The main flow consists of HTTP Listener and APIkit (REST or SOAP) Router components. The APIkit Router is a key message processor that validates requests against the provided definition, enriches messages (for example by adding default values to the messages) and routes requests to a particular flow. Also, the Router raises errors messages if errors occurs while routing, validating or processing the user request. ![REST API Main Flow](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-rest-main-flow.png) Figure 3. REST API Main Flow. ![SOAP API Main Flow](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-soap-main-flow.png) Figure 4. SOAP API Main Flow. ### Backend Flows APIkit for REST generates a backend flow for each resource-action pairing in a RAML file. APIkit for SOAP generates a backend flow for each operation in a WSDL. In the following example, the RAML interface receives the GET request users. The backend flow accesses a database to look up users by ID. ![REST API Backend Flows](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-rest-backend-flows.png) Figure 5. REST API Backend Flows. ### Perform Calls For REST APIs, use API Console to perform calls to the API. For SOAP APIs, use a SOAP testing tool such as SoapUI to perform calls to the API. ## Start APIkit Project and Generate Mule Flows When you start a new APIkit project in Studio, you have the option to import an API definition file. When you import the file, the APIkit scaffolding mechanism generates different flows for the API. There are three ways to start an APIkit project in Anypoint Studio: ### Start a New APIkit Project Using an API Definition File Use this method if you want to start a project by either importing an existing RAML or WSDL file or by referencing the file URL: 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, select **Specify API Definition File Location or URL**. 5. In **Location**, do one of the following: - If you created an `api.raml` file in Design Center, select **Design Center** . Login to Anypoint Platform if necessary, and select `api.raml`. - If you didn’t create a RAML file in Design Center, select **Browse Files** and select the RAML or WSDL file that you created in a text editor. For a WSDL file, select a service and port from the drop-down menus or accept the defaults. 6. Accept the Location default options, and click **Finish**. ![New Mule Project with API Specification selected](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-start-apikit-project-1.png) Figure 6. New Mule Project window selecting API specification . Using this method the APIkit scaffolding technique generates: - An archetype that contains basic configuration files plus a Mule XML configuration file - An implementation of the API For RAML-based APIs, the RAML file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A main flow with an HTTP Listener - APIkit Router component - Error handlers - RAML dependencies (push or pull changes from one location, such as Studio, to the other, such as Design Center) - Backend flows containing REST resource-action mappings For WSDL-based APIs, the WSDL file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A SOAP Router - A SOAP fault response template - Backend flows containing SOAP message templates The following graphics illustrate the APIkit scaffolding: ![RAML Scaffolding](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-raml-scaffolding.png) Figure 7. RAML Scaffolding. ![WSDL Scaffolding](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-wsdl-scaffolding.png) Figure 8. WSDL Scaffolding. In Studio, the REST API APIkit project looks like this: ![REST API Anypoint Studio UI with the Package Explorer and Canvas sections](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-rest-api-studio-apikit.png) Figure 9. REST API in Anypoint Studio UI with the Package Explorer and Canvas sections. The five items illustrated here show: 1. The project files in the Package Explorer of Studio with the `api.raml` file under `src/main/resources/api` folder. 2. The main flow, with the APIkit Router. 3. APIkit Console 4. Error Handling 5. Generated flows for each resource method. The generated minimal flows meets the communication operations required by a REST contract. In Studio, the SOAP API APIkit project looks like this: ![SOAP API Anypoint Studio UI with the Package Explorer and Canvas sections](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-soap-api-studio-apikit.png) Figure 10. SOAP API in Anypoint Studio UI with the Package Explorer and Canvas sections. The four items illustrated here show: 1. The project files in the Package Explorer of Studio with the `example.wsdl` file under `src/main/resources/api` folder. 2. The main flow, with the SOAP Router. 3. SOAP fault response template 4. Generated backend flows containing SOAP message templates. After you create your APIkit project, you can continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project Use this method if you start an APIkit project without an API specification file and you can later add it into the project. APIkit generates a skeletal RAML file and XML configuration file. 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE . Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, do _not_ select **Specify API Definition File Location or URL**. This creates the backend-first APIkit design. 5. Accept the other default options, and click **Finish**. ![New Mule Project window without API specification](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-start-apikit-project-2.png) Figure 11. New Mule Project window. Using this method the APIkit scaffolding generates a skeletal RAML file and XML configuration file that includes the following components: - A main flow `` - HTTP Listener configuration in the main flow - APIkit Router component - Error handlers You can later add an API specification to the backend-first APIkit design and generate backend flows to continue building the application. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project by Generating Backend Flows To perform this task, you must have met the following prerequisites: - Created a RAML file in Studio (RAML editor) - Created a main flow with an HTTP Listener and APIkit Router components When you create a RAML file in Studio, generating backend flows is optional. Error handling is generated automatically for a RAML-based API. To start the APIkit project, you need to generate the backend flows from the main flow. Follow the next steps: 1. In Package Explorer, right-click the project name. 2. Select **Mule > Generate Flows From REST API**. ![Generating backend flows from Mule Project](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-start-apikit-project-3.png) Figure 12. Generating backend flows from Mule Project. The APIkit scaffolding technique generates the backend flows following the main flow. You can then continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ## Build Applications Workflows After you are familiar with the basic APIkit anatomy and the scaffolding technique, examine the following workflows to help you build your desired application by creating the APIkit project, generating Mule flows, performing calls to the API, and finalizing its implementation: - [Build a REST API using APIKit for REST](https://docs.mulesoft.com/apikit/latest/apikit-4-for-rest) - [Build a SOAP API using APKit for SOAP](https://docs.mulesoft.com/apikit/latest/apikit-4-for-soap) Additionally, you can: - [Convert an Existing Mule Project to an APIkit Project](https://docs.mulesoft.com/apikit/latest/apikit-workflow-convert-existing) Add an API specification to an existing APIkit backend-first design, define API definition files, create main flow, generate backend REST API flows, map RAML resources to actions. - [Perform APIkit 4.x Tasks](https://docs.mulesoft.com/apikit/latest/key-configurations) Change APIkit project, customize API console, configure headers, retrieve RAML files, execute nonfunctional requirements, configure load balancers. - [Create an Enable O-Data API using the APIkit OData Extension](https://docs.mulesoft.com/apikit/latest/creating-an-odatav4-api-with-apikit) Generate Mule flows to handle OData requests. - [Create an APIkit project with Maven](https://docs.mulesoft.com/apikit/latest/apikit-4-scaffolding-reference) Add APIkit components to an existing Apache Maven project. ## Consume Data from an API After you build your application, you can start consuming data from the API. Review the [Consume Data from an API documentation](https://docs.mulesoft.com/mule-runtime/4.4/consume-data-from-an-api) for guidelines. ## See Also - [APIkit](https://docs.mulesoft.com/apikit/latest/) - [APIKit Handling Errors](https://docs.mulesoft.com/apikit/latest/apikit-error-handling-reference) --- product: Mule Runtime version: 4.6 keywords: build, application, api, specification --- # Build an Application from an API Specification > For the full documentation index, see: https://docs.mulesoft.com/llms.txt During your app development lifecycle, you can build Mule REST or SOAP APIs from an API specification using APIkit. You develop APIs based on the following modeling languages: - RAML (RESTful API Modeling Language) - WSDL (Web Service Description Language) - OData (OData-Enabled APIs using APIkit OData Extension) - OAS (Open API Specification) By using APIkit in Anypoint Studio, you can simplify the design and implementation of APIs by automating Mule flow creation based on importing either a RAML or a WSDL specification file. After generating the API, you can perform calls to test the API and then finalize its implementation. Additionally, APIkit helps you build applications using Apache Maven, and also provides a CLI tool to generate flows for an already existing application. However, before you perform any of these tasks, you must learn the basic APIkit anatomy and understand the scaffolding technique that generates Mule flows when you start APIkit projects. ## APIkit Anatomy A REST or SOAP Studio project that uses APIkit has the following parts: - A REST or SOAP interface - A main flow - Backend flows ![REST Studio Project](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-rest-studio-project.png) Figure 1. REST Studio Project. ![SOAP Studio Project](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-soap-studio-project.png) Figure 2. SOAP Studio Project. ### REST Interface The relationship between REST resources and actions is called _resource-action_ pairing. The interface exposes internal data assets requested by the REST service. Also, the interface defines the API, designating resources that contain or access data and specify actions, such as GET and PUT, on the example data. ### SOAP Interface The interface defined by a WSDL file exposes a number of services. Each service has a set of operations. The underlying type of data is XML defined by schemas within the WSDL file or by an imported XSD file. ### Main Flow The main flow for the API manages these functions: - Exposes the API using Anypoint Connector for HTTP (HTTP Connector). - Routes requests between the interface and the backend flows based on the HTTP request. - Accepts requests, sends responses, and facilitates communication between the interface and API processes. The main flow consists of HTTP Listener and APIkit (REST or SOAP) Router components. The APIkit Router is a key message processor that validates requests against the provided definition, enriches messages (for example by adding default values to the messages) and routes requests to a particular flow. Also, the Router raises errors messages if errors occurs while routing, validating or processing the user request. ![REST API Main Flow](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-rest-main-flow.png) Figure 3. REST API Main Flow. ![SOAP API Main Flow](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-soap-main-flow.png) Figure 4. SOAP API Main Flow. ### Backend Flows APIkit for REST generates a backend flow for each resource-action pairing in a RAML file. APIkit for SOAP generates a backend flow for each operation in a WSDL. In the following example, the RAML interface receives the GET request users. The backend flow accesses a database to look up users by ID. ![REST API Backend Flows](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-rest-backend-flows.png) Figure 5. REST API Backend Flows. ### Perform Calls For REST APIs, use API Console to perform calls to the API. For SOAP APIs, use a SOAP testing tool such as SoapUI to perform calls to the API. ## Start APIkit Project and Generate Mule Flows When you start a new APIkit project in Studio, you have the option to import an API definition file. When you import the file, the APIkit scaffolding mechanism generates different flows for the API. There are three ways to start an APIkit project in Anypoint Studio: ### Start a New APIkit Project Using an API Definition File Use this method if you want to start a project by either importing an existing RAML or WSDL file or by referencing the file URL: 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, select **Specify API Definition File Location or URL**. 5. In **Location**, do one of the following: - If you created an `api.raml` file in Design Center, select **Design Center** . Login to Anypoint Platform if necessary, and select `api.raml`. - If you didn’t create a RAML file in Design Center, select **Browse Files** and select the RAML or WSDL file that you created in a text editor. For a WSDL file, select a service and port from the drop-down menus or accept the defaults. 6. Accept the Location default options, and click **Finish**. ![New Mule Project with API Specification selected](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-start-apikit-project-1.png) Figure 6. New Mule Project window selecting API specification . Using this method the APIkit scaffolding technique generates: - An archetype that contains basic configuration files plus a Mule XML configuration file - An implementation of the API For RAML-based APIs, the RAML file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A main flow with an HTTP Listener - APIkit Router component - Error handlers - RAML dependencies (push or pull changes from one location, such as Studio, to the other, such as Design Center) - Backend flows containing REST resource-action mappings For WSDL-based APIs, the WSDL file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A SOAP Router - A SOAP fault response template - Backend flows containing SOAP message templates The following graphics illustrate the APIkit scaffolding: ![RAML Scaffolding](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-raml-scaffolding.png) Figure 7. RAML Scaffolding. ![WSDL Scaffolding](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-wsdl-scaffolding.png) Figure 8. WSDL Scaffolding. In Studio, the REST API APIkit project looks like this: ![REST API Anypoint Studio UI with the Package Explorer and Canvas sections](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-rest-api-studio-apikit.png) Figure 9. REST API in Anypoint Studio UI with the Package Explorer and Canvas sections. The five items illustrated here show: 1. The project files in the Package Explorer of Studio with the `api.raml` file under `src/main/resources/api` folder. 2. The main flow, with the APIkit Router. 3. APIkit Console 4. Error Handling 5. Generated flows for each resource method. The generated minimal flows meets the communication operations required by a REST contract. In Studio, the SOAP API APIkit project looks like this: ![SOAP API Anypoint Studio UI with the Package Explorer and Canvas sections](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-soap-api-studio-apikit.png) Figure 10. SOAP API in Anypoint Studio UI with the Package Explorer and Canvas sections. The four items illustrated here show: 1. The project files in the Package Explorer of Studio with the `example.wsdl` file under `src/main/resources/api` folder. 2. The main flow, with the SOAP Router. 3. SOAP fault response template 4. Generated backend flows containing SOAP message templates. After you create your APIkit project, you can continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project Use this method if you start an APIkit project without an API specification file and you can later add it into the project. APIkit generates a skeletal RAML file and XML configuration file. 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE . Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, do _not_ select **Specify API Definition File Location or URL**. This creates the backend-first APIkit design. 5. Accept the other default options, and click **Finish**. ![New Mule Project window without API specification](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-start-apikit-project-2.png) Figure 11. New Mule Project window. Using this method the APIkit scaffolding generates a skeletal RAML file and XML configuration file that includes the following components: - A main flow `` - HTTP Listener configuration in the main flow - APIkit Router component - Error handlers You can later add an API specification to the backend-first APIkit design and generate backend flows to continue building the application. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project by Generating Backend Flows To perform this task, you must have met the following prerequisites: - Created a RAML file in Studio (RAML editor) - Created a main flow with an HTTP Listener and APIkit Router components When you create a RAML file in Studio, generating backend flows is optional. Error handling is generated automatically for a RAML-based API. To start the APIkit project, you need to generate the backend flows from the main flow. Follow the next steps: 1. In Package Explorer, right-click the project name. 2. Select **Mule > Generate Flows From REST API**. ![Generating backend flows from Mule Project](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-start-apikit-project-3.png) Figure 12. Generating backend flows from Mule Project. The APIkit scaffolding technique generates the backend flows following the main flow. You can then continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ## Build Applications Workflows After you are familiar with the basic APIkit anatomy and the scaffolding technique, examine the following workflows to help you build your desired application by creating the APIkit project, generating Mule flows, performing calls to the API, and finalizing its implementation: - [Build a REST API using APIKit for REST](https://docs.mulesoft.com/apikit/latest/apikit-4-for-rest) - [Build a SOAP API using APKit for SOAP](https://docs.mulesoft.com/apikit/latest/apikit-4-for-soap) Additionally, you can: - [Convert an Existing Mule Project to an APIkit Project](https://docs.mulesoft.com/apikit/latest/apikit-workflow-convert-existing) Add an API specification to an existing APIkit backend-first design, define API definition files, create main flow, generate backend REST API flows, map RAML resources to actions. - [Perform APIkit 4.x Tasks](https://docs.mulesoft.com/apikit/latest/key-configurations) Change APIkit project, customize API console, configure headers, retrieve RAML files, execute nonfunctional requirements, configure load balancers. - [Create an Enable O-Data API using the APIkit OData Extension](https://docs.mulesoft.com/apikit/latest/creating-an-odatav4-api-with-apikit) Generate Mule flows to handle OData requests. - [Create an APIkit project with Maven](https://docs.mulesoft.com/apikit/latest/apikit-4-scaffolding-reference) Add APIkit components to an existing Apache Maven project. ## Consume Data from an API After you build your application, you can start consuming data from the API. Review the [Consume Data from an API documentation](https://docs.mulesoft.com/mule-runtime/4.6/consume-data-from-an-api) for guidelines. ## See Also - [APIkit](https://docs.mulesoft.com/apikit/latest/) - [APIKit Handling Errors](https://docs.mulesoft.com/apikit/latest/apikit-error-handling-reference) --- product: Mule Runtime version: 4.9 keywords: build, application, api, specification --- # Build an Application from an API Specification > For the full documentation index, see: https://docs.mulesoft.com/llms.txt During your app development lifecycle, you can build Mule REST or SOAP APIs from an API specification using APIkit. You develop APIs based on the following modeling languages: - RAML (RESTful API Modeling Language) - WSDL (Web Service Description Language) - OData (OData-Enabled APIs using APIkit OData Extension) - OAS (Open API Specification) By using APIkit in Anypoint Studio, you can simplify the design and implementation of APIs by automating Mule flow creation based on importing either a RAML or a WSDL specification file. After generating the API, you can perform calls to test the API and then finalize its implementation. Additionally, APIkit helps you build applications using Apache Maven, and also provides a CLI tool to generate flows for an already existing application. However, before you perform any of these tasks, you must learn the basic APIkit anatomy and understand the scaffolding technique that generates Mule flows when you start APIkit projects. ## APIkit Anatomy A REST or SOAP Studio project that uses APIkit has the following parts: - A REST or SOAP interface - A main flow - Backend flows ![A REST Studio project showing components including APIkit Router and API console](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-rest-studio-project.png) Figure 1. REST Studio Project. ![A SOAP Studio project showing components including SOAP Router and Transform Message](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-soap-studio-project.png) Figure 2. SOAP Studio Project. ### REST Interface The relationship between REST resources and actions is called _resource-action_ pairing. The interface exposes internal data assets requested by the REST service. Also, the interface defines the API, designating resources that contain or access data and specify actions, such as GET and PUT, on the example data. ### SOAP Interface The interface defined by a WSDL file exposes a number of services. Each service has a set of operations. The underlying type of data is XML defined by schemas within the WSDL file or by an imported XSD file. ### Main Flow The main flow for the API manages these functions: - Exposes the API using Anypoint Connector for HTTP (HTTP Connector). - Routes requests between the interface and the backend flows based on the HTTP request. - Accepts requests, sends responses, and facilitates communication between the interface and API processes. The main flow consists of HTTP Listener and APIkit (REST or SOAP) Router components. The APIkit Router is a key message processor that validates requests against the provided definition, enriches messages (for example by adding default values to the messages) and routes requests to a particular flow. Also, the Router raises errors messages if errors occurs while routing, validating or processing the user request. ![A REST API main flow with components including Listener and APIkit Router](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-rest-main-flow.png) Figure 3. REST API Main Flow. ![A SOAP API main flow with components including Listener and SOAP Router](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-soap-main-flow.png) Figure 4. SOAP API Main Flow. ### Backend Flows APIkit for REST generates a backend flow for each resource-action pairing in a RAML file. APIkit for SOAP generates a backend flow for each operation in a WSDL. In the following example, the RAML interface receives the GET request users. The backend flow accesses a database to look up users by ID. ![REST API backend flows](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-rest-backend-flows.png) Figure 5. REST API Backend Flows. ### Perform Calls For REST APIs, use API Console to perform calls to the API. For SOAP APIs, use a SOAP testing tool such as SoapUI to perform calls to the API. ## Start APIkit Project and Generate Mule Flows When you start a new APIkit project in Studio, you have the option to import an API definition file. When you import the file, the APIkit scaffolding mechanism generates different flows for the API. There are three ways to start an APIkit project in Anypoint Studio: ### Start a New APIkit Project Using an API Definition File Use this method if you want to start a project by either importing an existing RAML or WSDL file or by referencing the file URL: 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, select **Specify API Definition File Location or URL**. 5. In **Location**, do one of the following: - If you created an `api.raml` file in Design Center, select **Design Center** . Login to Anypoint Platform if necessary, and select `api.raml`. - If you didn’t create a RAML file in Design Center, select **Browse Files** and select the RAML or WSDL file that you created in a text editor. For a WSDL file, select a service and port from the drop-down menus or accept the defaults. 6. Accept the Location default options, and click **Finish**. ![A new Mule project with an API specification selected](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-start-apikit-project-1.png) Figure 6. New Mule Project window selecting API specification . Using this method the APIkit scaffolding technique generates: - An archetype that contains basic configuration files plus a Mule XML configuration file - An implementation of the API For RAML-based APIs, the RAML file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A main flow with an HTTP Listener - APIkit Router component - Error handlers - RAML dependencies (push or pull changes from one location, such as Studio, to the other, such as Design Center) - Backend flows containing REST resource-action mappings For WSDL-based APIs, the WSDL file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A SOAP Router - A SOAP fault response template - Backend flows containing SOAP message templates The following graphics illustrate the APIkit scaffolding: ![XML configuration for RAML scaffolding including Listener, APIkit Router, and Error handling components.](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-raml-scaffolding.png) Figure 7. RAML Scaffolding. ![XML configuration for WSDL scaffolding including Listener, SOAP Router, and Error handling components](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-wsdl-scaffolding.png) Figure 8. WSDL Scaffolding. In Studio, the REST API APIkit project looks like this: ![An APIkit project with files and configurations for handling REST API requests.](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-rest-api-studio-apikit.png) Figure 9. REST API in Anypoint Studio UI with the Package Explorer and Canvas sections. The five items illustrated here show: 1. The project files in the Package Explorer of Studio with the `api.raml` file under `src/main/resources/api` folder. 2. The main flow, with the APIkit Router. 3. APIkit Console 4. Error Handling 5. Generated flows for each resource method. The generated minimal flows meets the communication operations required by a REST contract. In Studio, the SOAP API APIkit project looks like this: ![A REST API APIkit project setup showing the Package Explorer and canvas in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-soap-api-studio-apikit.png) Figure 10. SOAP API in Anypoint Studio UI with the Package Explorer and Canvas sections. The four items illustrated here show: 1. The project files in the Package Explorer of Studio with the `example.wsdl` file under `src/main/resources/api` folder. 2. The main flow, with the SOAP Router. 3. SOAP fault response template 4. Generated backend flows containing SOAP message templates. After you create your APIkit project, you can continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project Use this method if you start an APIkit project without an API specification file and you can later add it into the project. APIkit generates a skeletal RAML file and XML configuration file. 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE . Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, do _not_ select **Specify API Definition File Location or URL**. This creates the backend-first APIkit design. 5. Accept the other default options, and click **Finish**. ![A new Mule project without an API specification](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-start-apikit-project-2.png) Figure 11. New Mule Project window. Using this method the APIkit scaffolding generates a skeletal RAML file and XML configuration file that includes the following components: - A main flow `` - HTTP Listener configuration in the main flow - APIkit Router component - Error handlers You can later add an API specification to the backend-first APIkit design and generate backend flows to continue building the application. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project by Generating Backend Flows To perform this task, you must have met the following prerequisites: - Created a RAML file in Studio (RAML editor) - Created a main flow with an HTTP Listener and APIkit Router components When you create a RAML file in Studio, generating backend flows is optional. Error handling is generated automatically for a RAML-based API. To start the APIkit project, you need to generate the backend flows from the main flow. Follow the next steps: 1. In Package Explorer, right-click the project name. 2. Select **Mule > Generate Flows From REST API**. ![A Package Explorer view showing options for generating backend flows from Mule project](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-start-apikit-project-3.png) Figure 12. Generating backend flows from Mule Project. The APIkit scaffolding technique generates the backend flows following the main flow. You can then continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ## Build Applications Workflows After you are familiar with the basic APIkit anatomy and the scaffolding technique, examine the following workflows to help you build your desired application by creating the APIkit project, generating Mule flows, performing calls to the API, and finalizing its implementation: - [Build a REST API using APIKit for REST](https://docs.mulesoft.com/apikit/latest/apikit-4-for-rest) - [Build a SOAP API using APKit for SOAP](https://docs.mulesoft.com/apikit/latest/apikit-4-for-soap) Additionally, you can: - [Convert an Existing Mule Project to an APIkit Project](https://docs.mulesoft.com/apikit/latest/apikit-workflow-convert-existing) Add an API specification to an existing APIkit backend-first design, define API definition files, create main flow, generate backend REST API flows, map RAML resources to actions. - [Perform APIkit 4.x Tasks](https://docs.mulesoft.com/apikit/latest/key-configurations) Change APIkit project, customize API console, configure headers, retrieve RAML files, execute nonfunctional requirements, configure load balancers. - [Create an Enable O-Data API using the APIkit OData Extension](https://docs.mulesoft.com/apikit/latest/creating-an-odatav4-api-with-apikit) Generate Mule flows to handle OData requests. - [Create an APIkit project with Maven](https://docs.mulesoft.com/apikit/latest/apikit-4-scaffolding-reference) Add APIkit components to an existing Apache Maven project. ## Consume Data from an API After you build your application, you can start consuming data from the API. Review the [Consume Data from an API documentation](https://docs.mulesoft.com/mule-runtime/4.9/consume-data-from-an-api) for guidelines. ## See Also - [APIkit](https://docs.mulesoft.com/apikit/latest/) - [APIKit Handling Errors](https://docs.mulesoft.com/apikit/latest/apikit-error-handling-reference) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: build, application, api, specification --- # Build an Application from an API Specification > For the full documentation index, see: https://docs.mulesoft.com/llms.txt During your app development lifecycle, you can build Mule REST or SOAP APIs from an API specification using APIkit. You develop APIs based on the following modeling languages: - RAML (RESTful API Modeling Language) - WSDL (Web Service Description Language) - OData (OData-Enabled APIs using APIkit OData Extension) - OAS (Open API Specification) By using APIkit in Anypoint Studio, you can simplify the design and implementation of APIs by automating Mule flow creation based on importing either a RAML or a WSDL specification file. After generating the API, you can perform calls to test the API and then finalize its implementation. Additionally, APIkit helps you build applications using Apache Maven, and also provides a CLI tool to generate flows for an already existing application. However, before you perform any of these tasks, you must learn the basic APIkit anatomy and understand the scaffolding technique that generates Mule flows when you start APIkit projects. ## APIkit Anatomy A REST or SOAP Studio project that uses APIkit has the following parts: - A REST or SOAP interface - A main flow - Backend flows ![A REST Studio project showing components including APIkit Router and API console](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-rest-studio-project.png) Figure 1. REST Studio Project. ![A SOAP Studio project showing components including SOAP Router and Transform Message](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-soap-studio-project.png) Figure 2. SOAP Studio Project. ### REST Interface The relationship between REST resources and actions is called _resource-action_ pairing. The interface exposes internal data assets requested by the REST service. Also, the interface defines the API, designating resources that contain or access data and specify actions, such as GET and PUT, on the example data. ### SOAP Interface The interface defined by a WSDL file exposes a number of services. Each service has a set of operations. The underlying type of data is XML defined by schemas within the WSDL file or by an imported XSD file. ### Main Flow The main flow for the API manages these functions: - Exposes the API using Anypoint Connector for HTTP (HTTP Connector). - Routes requests between the interface and the backend flows based on the HTTP request. - Accepts requests, sends responses, and facilitates communication between the interface and API processes. The main flow consists of HTTP Listener and APIkit (REST or SOAP) Router components. The APIkit Router is a key message processor that validates requests against the provided definition, enriches messages (for example by adding default values to the messages) and routes requests to a particular flow. Also, the Router raises errors messages if errors occurs while routing, validating or processing the user request. ![A REST API main flow with components including Listener and APIkit Router](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-rest-main-flow.png) Figure 3. REST API Main Flow. ![A SOAP API main flow with components including Listener and SOAP Router](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-soap-main-flow.png) Figure 4. SOAP API Main Flow. ### Backend Flows APIkit for REST generates a backend flow for each resource-action pairing in a RAML file. APIkit for SOAP generates a backend flow for each operation in a WSDL. In the following example, the RAML interface receives the GET request users. The backend flow accesses a database to look up users by ID. ![REST API backend flows](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-rest-backend-flows.png) Figure 5. REST API Backend Flows. ### Perform Calls For REST APIs, use API Console to perform calls to the API. For SOAP APIs, use a SOAP testing tool such as SoapUI to perform calls to the API. ## Start APIkit Project and Generate Mule Flows When you start a new APIkit project in Studio, you have the option to import an API definition file. When you import the file, the APIkit scaffolding mechanism generates different flows for the API. There are three ways to start an APIkit project in Anypoint Studio: ### Start a New APIkit Project Using an API Definition File Use this method if you want to start a project by either importing an existing RAML or WSDL file or by referencing the file URL: 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, select **Specify API Definition File Location or URL**. 5. In **Location**, do one of the following: - If you created an `api.raml` file in Design Center, select **Design Center** . Login to Anypoint Platform if necessary, and select `api.raml`. - If you didn’t create a RAML file in Design Center, select **Browse Files** and select the RAML or WSDL file that you created in a text editor. For a WSDL file, select a service and port from the drop-down menus or accept the defaults. 6. Accept the Location default options, and click **Finish**. ![A new Mule project with an API specification selected](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-start-apikit-project-1.png) Figure 6. New Mule Project window selecting API specification . Using this method the APIkit scaffolding technique generates: - An archetype that contains basic configuration files plus a Mule XML configuration file - An implementation of the API For RAML-based APIs, the RAML file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A main flow with an HTTP Listener - APIkit Router component - Error handlers - RAML dependencies (push or pull changes from one location, such as Studio, to the other, such as Design Center) - Backend flows containing REST resource-action mappings For WSDL-based APIs, the WSDL file appears under the `src/main/resources/api` folder. The implementation of the API contains: - A SOAP Router - A SOAP fault response template - Backend flows containing SOAP message templates The following graphics illustrate the APIkit scaffolding: ![XML configuration for RAML scaffolding including Listener, APIkit Router, and Error handling components.](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-raml-scaffolding.png) Figure 7. RAML Scaffolding. ![XML configuration for WSDL scaffolding including Listener, SOAP Router, and Error handling components](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-wsdl-scaffolding.png) Figure 8. WSDL Scaffolding. In Studio, the REST API APIkit project looks like this: ![An APIkit project with files and configurations for handling REST API requests.](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-rest-api-studio-apikit.png) Figure 9. REST API in Anypoint Studio UI with the Package Explorer and Canvas sections. The five items illustrated here show: 1. The project files in the Package Explorer of Studio with the `api.raml` file under `src/main/resources/api` folder. 2. The main flow, with the APIkit Router. 3. APIkit Console 4. Error Handling 5. Generated flows for each resource method. The generated minimal flows meets the communication operations required by a REST contract. In Studio, the SOAP API APIkit project looks like this: ![A REST API APIkit project setup showing the Package Explorer and canvas in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-soap-api-studio-apikit.png) Figure 10. SOAP API in Anypoint Studio UI with the Package Explorer and Canvas sections. The four items illustrated here show: 1. The project files in the Package Explorer of Studio with the `example.wsdl` file under `src/main/resources/api` folder. 2. The main flow, with the SOAP Router. 3. SOAP fault response template 4. Generated backend flows containing SOAP message templates. After you create your APIkit project, you can continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project Use this method if you start an APIkit project without an API specification file and you can later add it into the project. APIkit generates a skeletal RAML file and XML configuration file. 1. Select **File > New > Mule Project**. 2. In **Project Name**, enter a name for the project, for example **myproject**. 3. Select or accept the default EE . Runtime, for example **Mule Server 4.2.0 EE**. 4. In **API Implementation**, do _not_ select **Specify API Definition File Location or URL**. This creates the backend-first APIkit design. 5. Accept the other default options, and click **Finish**. ![A new Mule project without an API specification](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-start-apikit-project-2.png) Figure 11. New Mule Project window. Using this method the APIkit scaffolding generates a skeletal RAML file and XML configuration file that includes the following components: - A main flow `` - HTTP Listener configuration in the main flow - APIkit Router component - Error handlers You can later add an API specification to the backend-first APIkit design and generate backend flows to continue building the application. See [Build Applications Workflows](#build-applications-workflows) for details. ### Start a New APIkit Project by Generating Backend Flows To perform this task, you must have met the following prerequisites: - Created a RAML file in Studio (RAML editor) - Created a main flow with an HTTP Listener and APIkit Router components When you create a RAML file in Studio, generating backend flows is optional. Error handling is generated automatically for a RAML-based API. To start the APIkit project, you need to generate the backend flows from the main flow. Follow the next steps: 1. In Package Explorer, right-click the project name. 2. Select **Mule > Generate Flows From REST API**. ![A Package Explorer view showing options for generating backend flows from Mule project](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-start-apikit-project-3.png) Figure 12. Generating backend flows from Mule Project. The APIkit scaffolding technique generates the backend flows following the main flow. You can then continue building the application by performing calls to test the API and finalize its implementation. See [Build Applications Workflows](#build-applications-workflows) for details. ## Build Applications Workflows After you are familiar with the basic APIkit anatomy and the scaffolding technique, examine the following workflows to help you build your desired application by creating the APIkit project, generating Mule flows, performing calls to the API, and finalizing its implementation: - [Build a REST API using APIKit for REST](https://docs.mulesoft.com/apikit/latest/apikit-4-for-rest) - [Build a SOAP API using APKit for SOAP](https://docs.mulesoft.com/apikit/latest/apikit-4-for-soap) Additionally, you can: - [Convert an Existing Mule Project to an APIkit Project](https://docs.mulesoft.com/apikit/latest/apikit-workflow-convert-existing) Add an API specification to an existing APIkit backend-first design, define API definition files, create main flow, generate backend REST API flows, map RAML resources to actions. - [Perform APIkit 4.x Tasks](https://docs.mulesoft.com/apikit/latest/key-configurations) Change APIkit project, customize API console, configure headers, retrieve RAML files, execute nonfunctional requirements, configure load balancers. - [Create an Enable O-Data API using the APIkit OData Extension](https://docs.mulesoft.com/apikit/latest/creating-an-odatav4-api-with-apikit) Generate Mule flows to handle OData requests. - [Create an APIkit project with Maven](https://docs.mulesoft.com/apikit/latest/apikit-4-scaffolding-reference) Add APIkit components to an existing Apache Maven project. ## Consume Data from an API After you build your application, you can start consuming data from the API. Review the [Consume Data from an API documentation](https://docs.mulesoft.com/mule-runtime/latest/consume-data-from-an-api) for guidelines. ## See Also - [APIkit](https://docs.mulesoft.com/apikit/latest/) - [APIKit Handling Errors](https://docs.mulesoft.com/apikit/latest/apikit-error-handling-reference) --- product: Mule Runtime version: 4.11 keywords: mule runtime, arm, https, cloudhub --- # Build an HTTPS Service > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you ensure data confidentiality, you can deploy your Mule app using an HTTPS-based service. Learn how to build: - An HTTPS service to deploy your application to CloudHub - HTTPS services using API Manager proxies Additionally, learn how to configure HTTP request and response headers. If you need to deploy your app locally, see [TLS Configuration](https://docs.mulesoft.com/mule-runtime/4.11/tls-configuration). ## Prerequisites Before you begin, build a service (such as a simple "Hello World" service) and deploy it. Learn how to design and develop an API using our [Build an API from Start to Finish](https://docs.mulesoft.com/general/api-led-overview) tutorial. ## Build an HTTPS Service Modify your service to HTTPS to deploy your app to CloudHub: 1. Generate a `keystore.jks` file using the JDK `keytool` utility on the command line. You must also specify the hostname on the command line to generate a self-signed certificate. For example, the following command with hostname `SAN=DNS:localhost,IP:127.0.0.1` creates a `keystore.jks` file: ```text keytool -genkeypair -keystore keystore.jks -dname "CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass password -storepass password -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -alias mule -ext SAN=DNS:localhost,IP:127.0.0.1 -validity 9999 ``` 2. Add the generated `keystore.jks` file to your Anypoint Studio Mule app folder in `src/main/resources`. 3. Configure the HTTP Listener in your Mule app, specifying: - Any host IP addresses you want to use with the HTTPS scheme for the value of `host` - A value for ``${https.port} variable for the value of `port`` ```xml ... ... ``` 4. Include a `config-ref` reference to the HTTPS global listener configuration. ```xml ``` 5. Configure the HTTP Requester using the TLS configuration required to enable HTTPS requests to external addresses: ```xml ... ... ``` 6. Include a `config-ref` reference to the HTTPS global request configuration: ```xml ``` Your application is now ready to be deployed on CloudHub. You can access your endpoint using the HTTPS address: for example, `https://yourdomain.cloudhub.io` ## Configure Services Under API Manager Proxies If you are prompted to download a proxy from API Manager and need to configure it for HTTPS, follow the same steps that you used in Anypoint Connector for HTTP to configure the HTTP Requester. The HTTP Listener configuration is provided as a template. To complete the configuration: 1. Import the proxy project into Anypoint Studio. 2. Select the **Configuration XML** tab for your proxy flow. The parser detects an error because the flow references an HTTPS Connector that is commented out. 3. Uncomment the `http:listener-config` block. 4. Add the `keystore` values: `path`, `password`, and `keyPassword`: ```xml ``` - You can use external properties. - The value of `path` cannot include `src/main/resources`. Your configuration should look similar to the following: ```xml ... ``` ## Configure HTTP Request and Response Headers You can change the maximum values for the server response headers, server request headers, and client request headers by modifying the following system properties in the `wrapper.conf` file:
NamePropertyDescriptionDefault Value

Server Response Headers

mule.http.MAX_SERVER_RESPONSE_HEADERS

Maximum amount of headers allowed on a response sent from the HTTP server.

100

Server Request Headers

mule.http.MAX_SERVER_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent to the HTTP server.

100

Client Request Headers

mule.http.MAX_CLIENT_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent by the HTTP client.

100

There is no Max Client Response Header system property as there is no maximum limit for client HTTP response headers. ## See Also - [Building an HTTPS API Proxy](https://docs.mulesoft.com/api-manager/latest/building-https-proxy) in Mule 4 - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) - [TLS Configuration](https://docs.mulesoft.com/mule-runtime/4.11/tls-configuration) --- product: Mule Runtime version: 4.12 keywords: mule runtime, arm, https, cloudhub --- # Build an HTTPS Service > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you ensure data confidentiality, you can deploy your Mule app using an HTTPS-based service. Learn how to build: - An HTTPS service to deploy your application to CloudHub - HTTPS services using API Manager proxies Additionally, learn how to configure HTTP request and response headers. If you need to deploy your app locally, see [TLS Configuration](https://docs.mulesoft.com/mule-runtime/4.12/tls-configuration). ## Prerequisites Before you begin, build a service (such as a simple "Hello World" service) and deploy it. Learn how to design and develop an API using our [Build an API from Start to Finish](https://docs.mulesoft.com/general/api-led-overview) tutorial. ## Build an HTTPS Service Modify your service to HTTPS to deploy your app to CloudHub: 1. Generate a `keystore.jks` file using the JDK `keytool` utility on the command line. You must also specify the hostname on the command line to generate a self-signed certificate. For example, the following command with hostname `SAN=DNS:localhost,IP:127.0.0.1` creates a `keystore.jks` file: ```text keytool -genkeypair -keystore keystore.jks -dname "CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass password -storepass password -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -alias mule -ext SAN=DNS:localhost,IP:127.0.0.1 -validity 9999 ``` 2. Add the generated `keystore.jks` file to your Anypoint Studio Mule app folder in `src/main/resources`. 3. Configure the HTTP Listener in your Mule app, specifying: - Any host IP addresses you want to use with the HTTPS scheme for the value of `host` - A value for ``${https.port} variable for the value of `port`` ```xml ... ... ``` 4. Include a `config-ref` reference to the HTTPS global listener configuration. ```xml ``` 5. Configure the HTTP Requester using the TLS configuration required to enable HTTPS requests to external addresses: ```xml ... ... ``` 6. Include a `config-ref` reference to the HTTPS global request configuration: ```xml ``` Your application is now ready to be deployed on CloudHub. You can access your endpoint using the HTTPS address: for example, `https://yourdomain.cloudhub.io` ## Configure Services Under API Manager Proxies If you are prompted to download a proxy from API Manager and need to configure it for HTTPS, follow the same steps that you used in Anypoint Connector for HTTP to configure the HTTP Requester. The HTTP Listener configuration is provided as a template. To complete the configuration: 1. Import the proxy project into Anypoint Studio. 2. Select the **Configuration XML** tab for your proxy flow. The parser detects an error because the flow references an HTTPS Connector that is commented out. 3. Uncomment the `http:listener-config` block. 4. Add the `keystore` values: `path`, `password`, and `keyPassword`: ```xml ``` - You can use external properties. - The value of `path` cannot include `src/main/resources`. Your configuration should look similar to the following: ```xml ... ``` ## Configure HTTP Request and Response Headers You can change the maximum values for the server response headers, server request headers, and client request headers by modifying the following system properties in the `wrapper.conf` file:
NamePropertyDescriptionDefault Value

Server Response Headers

mule.http.MAX_SERVER_RESPONSE_HEADERS

Maximum amount of headers allowed on a response sent from the HTTP server.

100

Server Request Headers

mule.http.MAX_SERVER_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent to the HTTP server.

100

Client Request Headers

mule.http.MAX_CLIENT_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent by the HTTP client.

100

There is no Max Client Response Header system property as there is no maximum limit for client HTTP response headers. ## See Also - [Building an HTTPS API Proxy](https://docs.mulesoft.com/api-manager/latest/building-https-proxy) in Mule 4 - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) - [TLS Configuration](https://docs.mulesoft.com/mule-runtime/4.12/tls-configuration) --- product: Mule Runtime version: 4.3 keywords: mule runtime, arm, https, cloudhub --- # Build an HTTPS Service > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you ensure data confidentiality, you can deploy your Mule app using an HTTPS-based service. Learn how to build: - An HTTPS service to deploy your application to CloudHub - HTTPS services using API Manager proxies Additionally, learn how to configure HTTP request and response headers. If you need to deploy your app locally, see [TLS Configuration](https://docs.mulesoft.com/mule-runtime/4.3/tls-configuration). ## Prerequisites Before you begin, build a service (such as a simple "Hello World" service) and deploy it. Learn how to design and develop an API using our [Build an API from Start to Finish](https://docs.mulesoft.com/general/api-led-overview) tutorial. ## Build an HTTPS Service Modify your service to HTTPS to deploy your app to CloudHub: 1. Generate a `keystore.jks` file using the JDK `keytool` utility on the command line. You must also specify the hostname on the command line to generate a self-signed certificate. For example, the following command with hostname `SAN=DNS:localhost,IP:127.0.0.1` creates a `keystore.jks` file: ```text keytool -genkeypair -keystore keystore.jks -dname "CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass password -storepass password -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -alias mule -ext SAN=DNS:localhost,IP:127.0.0.1 -validity 9999 ``` 2. Add the generated `keystore.jks` file to your Anypoint Studio Mule app folder in `src/main/resources`. 3. Configure the HTTP Listener in your Mule app, specifying: - Any host IP addresses you want to use with the HTTPS scheme for the value of `host` - A value for ``${https.port} variable for the value of `port`` ```xml ... ... ``` 4. Include a `config-ref` reference to the HTTPS global listener configuration. ```xml ``` 5. Configure the HTTP Requester using the TLS configuration required to enable HTTPS requests to external addresses: ```xml ... ... ``` 6. Include a `config-ref` reference to the HTTPS global request configuration: ```xml ``` Your application is now ready to be deployed on CloudHub. You can access your endpoint using the HTTPS address: for example, `https://yourdomain.cloudhub.io` ## Configure Services Under API Manager Proxies If you are prompted to download a proxy from API Manager and need to configure it for HTTPS, follow the same steps that you used in Anypoint Connector for HTTP to configure the HTTP Requester. The HTTP Listener configuration is provided as a template. To complete the configuration: 1. Import the proxy project into Anypoint Studio. 2. Select the **Configuration XML** tab for your proxy flow. The parser detects an error because the flow references an HTTPS Connector that is commented out. 3. Uncomment the `http:listener-config` block. 4. Add the `keystore` values: `path`, `password`, and `keyPassword`: ```xml ``` - You can use external properties. - The value of `path` cannot include `src/main/resources`. Your configuration should look similar to the following: ```xml ... ``` ## Configure HTTP Request and Response Headers You can change the maximum values for the server response headers, server request headers, and client request headers by modifying the following system properties in the `wrapper.conf` file:
NamePropertyDescriptionDefault Value

Server Response Headers

mule.http.MAX_SERVER_RESPONSE_HEADERS

Maximum amount of headers allowed on a response sent from the HTTP server.

100

Server Request Headers

mule.http.MAX_SERVER_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent to the HTTP server.

100

Client Request Headers

mule.http.MAX_CLIENT_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent by the HTTP client.

100

There is no such Max Client Response Header system property as there is no maximum limit for client HTTP response headers. ## See Also - [Building an HTTPS API Proxy](https://docs.mulesoft.com/api-manager/latest/building-https-proxy) in Mule 4 - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) - [TLS Configuration](https://docs.mulesoft.com/mule-runtime/4.3/tls-configuration) --- product: Mule Runtime version: 4.4 keywords: mule runtime, arm, https, cloudhub --- # Build an HTTPS Service > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you ensure data confidentiality, you can deploy your Mule app using an HTTPS-based service. Learn how to build: - An HTTPS service to deploy your application to CloudHub - HTTPS services using API Manager proxies Additionally, learn how to configure HTTP request and response headers. If you need to deploy your app locally, see [TLS Configuration](https://docs.mulesoft.com/mule-runtime/4.4/tls-configuration). ## Prerequisites Before you begin, build a service (such as a simple "Hello World" service) and deploy it. Learn how to design and develop an API using our [Build an API from Start to Finish](https://docs.mulesoft.com/general/api-led-overview) tutorial. ## Build an HTTPS Service Modify your service to HTTPS to deploy your app to CloudHub: 1. Generate a `keystore.jks` file using the JDK `keytool` utility on the command line. You must also specify the hostname on the command line to generate a self-signed certificate. For example, the following command with hostname `SAN=DNS:localhost,IP:127.0.0.1` creates a `keystore.jks` file: ```text keytool -genkeypair -keystore keystore.jks -dname "CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass password -storepass password -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -alias mule -ext SAN=DNS:localhost,IP:127.0.0.1 -validity 9999 ``` 2. Add the generated `keystore.jks` file to your Anypoint Studio Mule app folder in `src/main/resources`. 3. Configure the HTTP Listener in your Mule app, specifying: - Any host IP addresses you want to use with the HTTPS scheme for the value of `host` - A value for ``${https.port} variable for the value of `port`` ```xml ... ... ``` 4. Include a `config-ref` reference to the HTTPS global listener configuration. ```xml ``` 5. Configure the HTTP Requester using the TLS configuration required to enable HTTPS requests to external addresses: ```xml ... ... ``` 6. Include a `config-ref` reference to the HTTPS global request configuration: ```xml ``` Your application is now ready to be deployed on CloudHub. You can access your endpoint using the HTTPS address: for example, `https://yourdomain.cloudhub.io` ## Configure Services Under API Manager Proxies If you are prompted to download a proxy from API Manager and need to configure it for HTTPS, follow the same steps that you used in Anypoint Connector for HTTP to configure the HTTP Requester. The HTTP Listener configuration is provided as a template. To complete the configuration: 1. Import the proxy project into Anypoint Studio. 2. Select the **Configuration XML** tab for your proxy flow. The parser detects an error because the flow references an HTTPS Connector that is commented out. 3. Uncomment the `http:listener-config` block. 4. Add the `keystore` values: `path`, `password`, and `keyPassword`: ```xml ``` - You can use external properties. - The value of `path` cannot include `src/main/resources`. Your configuration should look similar to the following: ```xml ... ``` ## Configure HTTP Request and Response Headers You can change the maximum values for the server response headers, server request headers, and client request headers by modifying the following system properties in the `wrapper.conf` file:
NamePropertyDescriptionDefault Value

Server Response Headers

mule.http.MAX_SERVER_RESPONSE_HEADERS

Maximum amount of headers allowed on a response sent from the HTTP server.

100

Server Request Headers

mule.http.MAX_SERVER_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent to the HTTP server.

100

Client Request Headers

mule.http.MAX_CLIENT_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent by the HTTP client.

100

There is no Max Client Response Header system property as there is no maximum limit for client HTTP response headers. ## See Also - [Building an HTTPS API Proxy](https://docs.mulesoft.com/api-manager/latest/building-https-proxy) in Mule 4 - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) - [TLS Configuration](https://docs.mulesoft.com/mule-runtime/4.4/tls-configuration) --- product: Mule Runtime version: 4.6 keywords: mule runtime, arm, https, cloudhub --- # Build an HTTPS Service > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you ensure data confidentiality, you can deploy your Mule app using an HTTPS-based service. Learn how to build: - An HTTPS service to deploy your application to CloudHub - HTTPS services using API Manager proxies Additionally, learn how to configure HTTP request and response headers. If you need to deploy your app locally, see [TLS Configuration](https://docs.mulesoft.com/mule-runtime/4.6/tls-configuration). ## Prerequisites Before you begin, build a service (such as a simple "Hello World" service) and deploy it. Learn how to design and develop an API using our [Build an API from Start to Finish](https://docs.mulesoft.com/general/api-led-overview) tutorial. ## Build an HTTPS Service Modify your service to HTTPS to deploy your app to CloudHub: 1. Generate a `keystore.jks` file using the JDK `keytool` utility on the command line. You must also specify the hostname on the command line to generate a self-signed certificate. For example, the following command with hostname `SAN=DNS:localhost,IP:127.0.0.1` creates a `keystore.jks` file: ```text keytool -genkeypair -keystore keystore.jks -dname "CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass password -storepass password -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -alias mule -ext SAN=DNS:localhost,IP:127.0.0.1 -validity 9999 ``` 2. Add the generated `keystore.jks` file to your Anypoint Studio Mule app folder in `src/main/resources`. 3. Configure the HTTP Listener in your Mule app, specifying: - Any host IP addresses you want to use with the HTTPS scheme for the value of `host` - A value for ``${https.port} variable for the value of `port`` ```xml ... ... ``` 4. Include a `config-ref` reference to the HTTPS global listener configuration. ```xml ``` 5. Configure the HTTP Requester using the TLS configuration required to enable HTTPS requests to external addresses: ```xml ... ... ``` 6. Include a `config-ref` reference to the HTTPS global request configuration: ```xml ``` Your application is now ready to be deployed on CloudHub. You can access your endpoint using the HTTPS address: for example, `https://yourdomain.cloudhub.io` ## Configure Services Under API Manager Proxies If you are prompted to download a proxy from API Manager and need to configure it for HTTPS, follow the same steps that you used in Anypoint Connector for HTTP to configure the HTTP Requester. The HTTP Listener configuration is provided as a template. To complete the configuration: 1. Import the proxy project into Anypoint Studio. 2. Select the **Configuration XML** tab for your proxy flow. The parser detects an error because the flow references an HTTPS Connector that is commented out. 3. Uncomment the `http:listener-config` block. 4. Add the `keystore` values: `path`, `password`, and `keyPassword`: ```xml ``` - You can use external properties. - The value of `path` cannot include `src/main/resources`. Your configuration should look similar to the following: ```xml ... ``` ## Configure HTTP Request and Response Headers You can change the maximum values for the server response headers, server request headers, and client request headers by modifying the following system properties in the `wrapper.conf` file:
NamePropertyDescriptionDefault Value

Server Response Headers

mule.http.MAX_SERVER_RESPONSE_HEADERS

Maximum amount of headers allowed on a response sent from the HTTP server.

100

Server Request Headers

mule.http.MAX_SERVER_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent to the HTTP server.

100

Client Request Headers

mule.http.MAX_CLIENT_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent by the HTTP client.

100

There is no Max Client Response Header system property as there is no maximum limit for client HTTP response headers. ## See Also - [Building an HTTPS API Proxy](https://docs.mulesoft.com/api-manager/latest/building-https-proxy) in Mule 4 - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) - [TLS Configuration](https://docs.mulesoft.com/mule-runtime/4.6/tls-configuration) --- product: Mule Runtime version: 4.9 keywords: mule runtime, arm, https, cloudhub --- # Build an HTTPS Service > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you ensure data confidentiality, you can deploy your Mule app using an HTTPS-based service. Learn how to build: - An HTTPS service to deploy your application to CloudHub - HTTPS services using API Manager proxies Additionally, learn how to configure HTTP request and response headers. If you need to deploy your app locally, see [TLS Configuration](https://docs.mulesoft.com/mule-runtime/4.9/tls-configuration). ## Prerequisites Before you begin, build a service (such as a simple "Hello World" service) and deploy it. Learn how to design and develop an API using our [Build an API from Start to Finish](https://docs.mulesoft.com/general/api-led-overview) tutorial. ## Build an HTTPS Service Modify your service to HTTPS to deploy your app to CloudHub: 1. Generate a `keystore.jks` file using the JDK `keytool` utility on the command line. You must also specify the hostname on the command line to generate a self-signed certificate. For example, the following command with hostname `SAN=DNS:localhost,IP:127.0.0.1` creates a `keystore.jks` file: ```text keytool -genkeypair -keystore keystore.jks -dname "CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass password -storepass password -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -alias mule -ext SAN=DNS:localhost,IP:127.0.0.1 -validity 9999 ``` 2. Add the generated `keystore.jks` file to your Anypoint Studio Mule app folder in `src/main/resources`. 3. Configure the HTTP Listener in your Mule app, specifying: - Any host IP addresses you want to use with the HTTPS scheme for the value of `host` - A value for ``${https.port} variable for the value of `port`` ```xml ... ... ``` 4. Include a `config-ref` reference to the HTTPS global listener configuration. ```xml ``` 5. Configure the HTTP Requester using the TLS configuration required to enable HTTPS requests to external addresses: ```xml ... ... ``` 6. Include a `config-ref` reference to the HTTPS global request configuration: ```xml ``` Your application is now ready to be deployed on CloudHub. You can access your endpoint using the HTTPS address: for example, `https://yourdomain.cloudhub.io` ## Configure Services Under API Manager Proxies If you are prompted to download a proxy from API Manager and need to configure it for HTTPS, follow the same steps that you used in Anypoint Connector for HTTP to configure the HTTP Requester. The HTTP Listener configuration is provided as a template. To complete the configuration: 1. Import the proxy project into Anypoint Studio. 2. Select the **Configuration XML** tab for your proxy flow. The parser detects an error because the flow references an HTTPS Connector that is commented out. 3. Uncomment the `http:listener-config` block. 4. Add the `keystore` values: `path`, `password`, and `keyPassword`: ```xml ``` - You can use external properties. - The value of `path` cannot include `src/main/resources`. Your configuration should look similar to the following: ```xml ... ``` ## Configure HTTP Request and Response Headers You can change the maximum values for the server response headers, server request headers, and client request headers by modifying the following system properties in the `wrapper.conf` file:
NamePropertyDescriptionDefault Value

Server Response Headers

mule.http.MAX_SERVER_RESPONSE_HEADERS

Maximum amount of headers allowed on a response sent from the HTTP server.

100

Server Request Headers

mule.http.MAX_SERVER_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent to the HTTP server.

100

Client Request Headers

mule.http.MAX_CLIENT_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent by the HTTP client.

100

There is no Max Client Response Header system property as there is no maximum limit for client HTTP response headers. ## See Also - [Building an HTTPS API Proxy](https://docs.mulesoft.com/api-manager/latest/building-https-proxy) in Mule 4 - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) - [TLS Configuration](https://docs.mulesoft.com/mule-runtime/4.9/tls-configuration) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: mule runtime, arm, https, cloudhub --- # Build an HTTPS Service > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you ensure data confidentiality, you can deploy your Mule app using an HTTPS-based service. Learn how to build: - An HTTPS service to deploy your application to CloudHub - HTTPS services using API Manager proxies Additionally, learn how to configure HTTP request and response headers. If you need to deploy your app locally, see [TLS Configuration](https://docs.mulesoft.com/mule-runtime/latest/tls-configuration). ## Prerequisites Before you begin, build a service (such as a simple "Hello World" service) and deploy it. Learn how to design and develop an API using our [Build an API from Start to Finish](https://docs.mulesoft.com/general/api-led-overview) tutorial. ## Build an HTTPS Service Modify your service to HTTPS to deploy your app to CloudHub: 1. Generate a `keystore.jks` file using the JDK `keytool` utility on the command line. You must also specify the hostname on the command line to generate a self-signed certificate. For example, the following command with hostname `SAN=DNS:localhost,IP:127.0.0.1` creates a `keystore.jks` file: ```text keytool -genkeypair -keystore keystore.jks -dname "CN=localhost, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass password -storepass password -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -alias mule -ext SAN=DNS:localhost,IP:127.0.0.1 -validity 9999 ``` 2. Add the generated `keystore.jks` file to your Anypoint Studio Mule app folder in `src/main/resources`. 3. Configure the HTTP Listener in your Mule app, specifying: - Any host IP addresses you want to use with the HTTPS scheme for the value of `host` - A value for ``${https.port} variable for the value of `port`` ```xml ... ... ``` 4. Include a `config-ref` reference to the HTTPS global listener configuration. ```xml ``` 5. Configure the HTTP Requester using the TLS configuration required to enable HTTPS requests to external addresses: ```xml ... ... ``` 6. Include a `config-ref` reference to the HTTPS global request configuration: ```xml ``` Your application is now ready to be deployed on CloudHub. You can access your endpoint using the HTTPS address: for example, `https://yourdomain.cloudhub.io` ## Configure Services Under API Manager Proxies If you are prompted to download a proxy from API Manager and need to configure it for HTTPS, follow the same steps that you used in Anypoint Connector for HTTP to configure the HTTP Requester. The HTTP Listener configuration is provided as a template. To complete the configuration: 1. Import the proxy project into Anypoint Studio. 2. Select the **Configuration XML** tab for your proxy flow. The parser detects an error because the flow references an HTTPS Connector that is commented out. 3. Uncomment the `http:listener-config` block. 4. Add the `keystore` values: `path`, `password`, and `keyPassword`: ```xml ``` - You can use external properties. - The value of `path` cannot include `src/main/resources`. Your configuration should look similar to the following: ```xml ... ``` ## Configure HTTP Request and Response Headers You can change the maximum values for the server response headers, server request headers, and client request headers by modifying the following system properties in the `wrapper.conf` file:
NamePropertyDescriptionDefault Value

Server Response Headers

mule.http.MAX_SERVER_RESPONSE_HEADERS

Maximum amount of headers allowed on a response sent from the HTTP server.

100

Server Request Headers

mule.http.MAX_SERVER_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent to the HTTP server.

100

Client Request Headers

mule.http.MAX_CLIENT_REQUEST_HEADERS

Maximum amount of headers allowed on a request sent by the HTTP client.

100

There is no Max Client Response Header system property as there is no maximum limit for client HTTP response headers. ## See Also - [Building an HTTPS API Proxy](https://docs.mulesoft.com/api-manager/latest/building-https-proxy) in Mule 4 - [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) - [TLS Configuration](https://docs.mulesoft.com/mule-runtime/latest/tls-configuration) --- product: Mule Runtime version: 4.11 --- # Business Events > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule applications collect _business event_ information (such as transaction execution time, errors, success or failure results, and message payload information) about flows and message processors that handle your _business transactions_: - Events map to message processors and connectors and are the low-level details of a transaction. Events are not supported in batch processing. - Transactions are logical groupings of related events that often correspond to a business view of the system, at the flow level. ## Business Event Types You can track two types of business events: _default events_ and _custom events_. Default event tracking is supported by all connectors and selected message processors. Enabling default events for these elements enables you to perform advanced debugging at runtime. You can enable default event tracking at either the flow level or the message processor level. See [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/4.11/business-events-in-components) for configuration details. Custom event tracking is supported by the Custom Business Event component. Custom events are always tracked, enabling you to monitor high-level activities in your flow that are relevant to your business. See [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/4.11/business-events-custom) for configuration details. ## Monitoring Business Events You can enable Insight in Runtime Manager to monitor business events at runtime. These events can help you analyze the root cause of failures, isolate performance bottlenecks, and test for compliance with company procedures. Certain default events are tracked automatically after you enable Insight, but you must enable others in your application before they are tracked. See the [Insight](https://docs.mulesoft.com/runtime-manager/insight) documentation for more details. ## Best Practices for Business Events Consider the following recommended practices when configuring business events tracking: - Enable default events only for processes that have particular value to you. To filter out unnecessary information, determine which stages within a business transaction you need to track, and enable tracking for only those stages. - Use custom events to track key process indicators: for example, "Total Order Amount" or "Tracking Number" to surface the high-level business activities in your flow. - Customize the transaction ID so that meaningful information, such as an order number, an employee identification number, or a shipment tracking number, is displayed for a transaction. This practice makes analysis and debugging easier and more intuitive at runtime. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-event) - [Transaction Management](https://docs.mulesoft.com/mule-runtime/4.11/transaction-management) - [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/4.11/business-events-in-components) - [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/4.11/business-events-custom) --- product: Mule Runtime version: 4.12 --- # Business Events > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule applications collect _business event_ information (such as transaction execution time, errors, success or failure results, and message payload information) about flows and message processors that handle your _business transactions_: - Events map to message processors and connectors and are the low-level details of a transaction. Events are not supported in batch processing. - Transactions are logical groupings of related events that often correspond to a business view of the system, at the flow level. ## Business Event Types You can track two types of business events: _default events_ and _custom events_. Default event tracking is supported by all connectors and selected message processors. Enabling default events for these elements enables you to perform advanced debugging at runtime. You can enable default event tracking at either the flow level or the message processor level. See [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/4.12/business-events-in-components) for configuration details. Custom event tracking is supported by the Custom Business Event component. Custom events are always tracked, enabling you to monitor high-level activities in your flow that are relevant to your business. See [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/4.12/business-events-custom) for configuration details. ## Monitoring Business Events You can enable Insight in Runtime Manager to monitor business events at runtime. These events can help you analyze the root cause of failures, isolate performance bottlenecks, and test for compliance with company procedures. Certain default events are tracked automatically after you enable Insight, but you must enable others in your application before they are tracked. See the [Insight](https://docs.mulesoft.com/runtime-manager/insight) documentation for more details. ## Best Practices for Business Events Consider the following recommended practices when configuring business events tracking: - Enable default events only for processes that have particular value to you. To filter out unnecessary information, determine which stages within a business transaction you need to track, and enable tracking for only those stages. - Use custom events to track key process indicators: for example, "Total Order Amount" or "Tracking Number" to surface the high-level business activities in your flow. - Customize the transaction ID so that meaningful information, such as an order number, an employee identification number, or a shipment tracking number, is displayed for a transaction. This practice makes analysis and debugging easier and more intuitive at runtime. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-event) - [Transaction Management](https://docs.mulesoft.com/mule-runtime/4.12/transaction-management) - [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/4.12/business-events-in-components) - [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/4.12/business-events-custom) --- product: Mule Runtime version: 4.3 --- # Business Events > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule applications collect _business event_ information (such as transaction execution time, errors, success or failure results, and message payload information) about flows and message processors that handle your _business transactions_: - Events map to message processors and connectors and are the low-level details of a transaction. Events are not supported in batch processing. - Transactions are logical groupings of related events that often correspond to a business view of the system, at the flow level. ## Business Event Types You can track two types of business events: _default events_ and _custom events_. Default event tracking is supported by all connectors and selected message processors. Enabling default events for these elements enables you to perform advanced debugging at runtime. You can enable default event tracking at either the flow level or the message processor level. See [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/4.3/business-events-in-components) for configuration details. Custom event tracking is supported by the Custom Business Event component. Custom events are always tracked, enabling you to monitor high-level activities in your flow that are relevant to your business. See [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/4.3/business-events-custom) for configuration details. ## Monitoring Business Events You can enable Insight in Runtime Manager to monitor business events at runtime. These events can help you analyze the root cause of failures, isolate performance bottlenecks, and test for compliance with company procedures. Certain default events are tracked automatically after you enable Insight, but you must enable others in your application before they are tracked. See the [Insight](https://docs.mulesoft.com/runtime-manager/insight) documentation for more details. ## Best Practices for Business Events Consider the following recommended practices when configuring business events tracking: - Enable default events only for processes that have particular value to you. To filter out unnecessary information, determine which stages within a business transaction you need to track, and enable tracking for only those stages. - Use custom events to track key process indicators: for example, "Total Order Amount" or "Tracking Number" to surface the high-level business activities in your flow. - Customize the transaction ID so that meaningful information, such as an order number, an employee identification number, or a shipment tracking number, is displayed for a transaction. This practice makes analysis and debugging easier and more intuitive at runtime. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-event) - [Transaction Management](https://docs.mulesoft.com/mule-runtime/4.3/transaction-management) - [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/4.3/business-events-in-components) - [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/4.3/business-events-custom) --- product: Mule Runtime version: 4.4 --- # Business Events > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule applications collect _business event_ information (such as transaction execution time, errors, success or failure results, and message payload information) about flows and message processors that handle your _business transactions_: - Events map to message processors and connectors and are the low-level details of a transaction. Events are not supported in batch processing. - Transactions are logical groupings of related events that often correspond to a business view of the system, at the flow level. ## Business Event Types You can track two types of business events: _default events_ and _custom events_. Default event tracking is supported by all connectors and selected message processors. Enabling default events for these elements enables you to perform advanced debugging at runtime. You can enable default event tracking at either the flow level or the message processor level. See [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/4.4/business-events-in-components) for configuration details. Custom event tracking is supported by the Custom Business Event component. Custom events are always tracked, enabling you to monitor high-level activities in your flow that are relevant to your business. See [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/4.4/business-events-custom) for configuration details. ## Monitoring Business Events You can enable Insight in Runtime Manager to monitor business events at runtime. These events can help you analyze the root cause of failures, isolate performance bottlenecks, and test for compliance with company procedures. Certain default events are tracked automatically after you enable Insight, but you must enable others in your application before they are tracked. See the [Insight](https://docs.mulesoft.com/runtime-manager/insight) documentation for more details. ## Best Practices for Business Events Consider the following recommended practices when configuring business events tracking: - Enable default events only for processes that have particular value to you. To filter out unnecessary information, determine which stages within a business transaction you need to track, and enable tracking for only those stages. - Use custom events to track key process indicators: for example, "Total Order Amount" or "Tracking Number" to surface the high-level business activities in your flow. - Customize the transaction ID so that meaningful information, such as an order number, an employee identification number, or a shipment tracking number, is displayed for a transaction. This practice makes analysis and debugging easier and more intuitive at runtime. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-event) - [Transaction Management](https://docs.mulesoft.com/mule-runtime/4.4/transaction-management) - [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/4.4/business-events-in-components) - [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/4.4/business-events-custom) --- product: Mule Runtime version: 4.6 --- # Business Events > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule applications collect _business event_ information (such as transaction execution time, errors, success or failure results, and message payload information) about flows and message processors that handle your _business transactions_: - Events map to message processors and connectors and are the low-level details of a transaction. Events are not supported in batch processing. - Transactions are logical groupings of related events that often correspond to a business view of the system, at the flow level. ## Business Event Types You can track two types of business events: _default events_ and _custom events_. Default event tracking is supported by all connectors and selected message processors. Enabling default events for these elements enables you to perform advanced debugging at runtime. You can enable default event tracking at either the flow level or the message processor level. See [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/4.6/business-events-in-components) for configuration details. Custom event tracking is supported by the Custom Business Event component. Custom events are always tracked, enabling you to monitor high-level activities in your flow that are relevant to your business. See [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/4.6/business-events-custom) for configuration details. ## Monitoring Business Events You can enable Insight in Runtime Manager to monitor business events at runtime. These events can help you analyze the root cause of failures, isolate performance bottlenecks, and test for compliance with company procedures. Certain default events are tracked automatically after you enable Insight, but you must enable others in your application before they are tracked. See the [Insight](https://docs.mulesoft.com/runtime-manager/insight) documentation for more details. ## Best Practices for Business Events Consider the following recommended practices when configuring business events tracking: - Enable default events only for processes that have particular value to you. To filter out unnecessary information, determine which stages within a business transaction you need to track, and enable tracking for only those stages. - Use custom events to track key process indicators: for example, "Total Order Amount" or "Tracking Number" to surface the high-level business activities in your flow. - Customize the transaction ID so that meaningful information, such as an order number, an employee identification number, or a shipment tracking number, is displayed for a transaction. This practice makes analysis and debugging easier and more intuitive at runtime. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-event) - [Transaction Management](https://docs.mulesoft.com/mule-runtime/4.6/transaction-management) - [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/4.6/business-events-in-components) - [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/4.6/business-events-custom) --- product: Mule Runtime version: 4.9 --- # Business Events > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule applications collect _business event_ information (such as transaction execution time, errors, success or failure results, and message payload information) about flows and message processors that handle your _business transactions_: - Events map to message processors and connectors and are the low-level details of a transaction. Events are not supported in batch processing. - Transactions are logical groupings of related events that often correspond to a business view of the system, at the flow level. ## Business Event Types You can track two types of business events: _default events_ and _custom events_. Default event tracking is supported by all connectors and selected message processors. Enabling default events for these elements enables you to perform advanced debugging at runtime. You can enable default event tracking at either the flow level or the message processor level. See [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/4.9/business-events-in-components) for configuration details. Custom event tracking is supported by the Custom Business Event component. Custom events are always tracked, enabling you to monitor high-level activities in your flow that are relevant to your business. See [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/4.9/business-events-custom) for configuration details. ## Monitoring Business Events You can enable Insight in Runtime Manager to monitor business events at runtime. These events can help you analyze the root cause of failures, isolate performance bottlenecks, and test for compliance with company procedures. Certain default events are tracked automatically after you enable Insight, but you must enable others in your application before they are tracked. See the [Insight](https://docs.mulesoft.com/runtime-manager/insight) documentation for more details. ## Best Practices for Business Events Consider the following recommended practices when configuring business events tracking: - Enable default events only for processes that have particular value to you. To filter out unnecessary information, determine which stages within a business transaction you need to track, and enable tracking for only those stages. - Use custom events to track key process indicators: for example, "Total Order Amount" or "Tracking Number" to surface the high-level business activities in your flow. - Customize the transaction ID so that meaningful information, such as an order number, an employee identification number, or a shipment tracking number, is displayed for a transaction. This practice makes analysis and debugging easier and more intuitive at runtime. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-event) - [Transaction Management](https://docs.mulesoft.com/mule-runtime/4.9/transaction-management) - [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/4.9/business-events-in-components) - [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/4.9/business-events-custom) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Business Events > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule applications collect _business event_ information (such as transaction execution time, errors, success or failure results, and message payload information) about flows and message processors that handle your _business transactions_: - Events map to message processors and connectors and are the low-level details of a transaction. Events are not supported in batch processing. - Transactions are logical groupings of related events that often correspond to a business view of the system, at the flow level. ## Business Event Types You can track two types of business events: _default events_ and _custom events_. Default event tracking is supported by all connectors and selected message processors. Enabling default events for these elements enables you to perform advanced debugging at runtime. You can enable default event tracking at either the flow level or the message processor level. See [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/latest/business-events-in-components) for configuration details. Custom event tracking is supported by the Custom Business Event component. Custom events are always tracked, enabling you to monitor high-level activities in your flow that are relevant to your business. See [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/latest/business-events-custom) for configuration details. ## Monitoring Business Events You can enable Insight in Runtime Manager to monitor business events at runtime. These events can help you analyze the root cause of failures, isolate performance bottlenecks, and test for compliance with company procedures. Certain default events are tracked automatically after you enable Insight, but you must enable others in your application before they are tracked. See the [Insight](https://docs.mulesoft.com/runtime-manager/insight) documentation for more details. ## Best Practices for Business Events Consider the following recommended practices when configuring business events tracking: - Enable default events only for processes that have particular value to you. To filter out unnecessary information, determine which stages within a business transaction you need to track, and enable tracking for only those stages. - Use custom events to track key process indicators: for example, "Total Order Amount" or "Tracking Number" to surface the high-level business activities in your flow. - Customize the transaction ID so that meaningful information, such as an order number, an employee identification number, or a shipment tracking number, is displayed for a transaction. This practice makes analysis and debugging easier and more intuitive at runtime. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/latest/about-mule-event) - [Transaction Management](https://docs.mulesoft.com/mule-runtime/latest/transaction-management) - [Configure Default Events Tracking](https://docs.mulesoft.com/mule-runtime/latest/business-events-in-components) - [Custom Business Event Component](https://docs.mulesoft.com/mule-runtime/latest/business-events-custom) --- product: Mule Runtime version: 4.11 keywords: cache, anypoint, studio --- # Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Cache scope is for storing and reusing frequently called data. You can use a Cache scope to reduce the processing load on the Mule instance and to increase the speed of message processing within a flow. It is particularly effective for these tasks: - Processing repeated requests for the same information. - Processing requests for information that involve large repeatable streams. When a message processor in a Mule app sends a message to the Cache scope, the parent flow expects an output. The Cache scope processes the message payload, delivers the output to the parent flow, and saves the output (that is, caches the response). The next time the Cache scope receives the same kind of message payload, the scope can offer a cached response rather than invoking a potentially time-consuming process again. For instance, you can use a Cache scope to manage customer requests for flight information. Many customers might request the same pricing information about flights from San Francisco to Buenos Aires. Rather than using a lot of processing power to send separate requests to several airline databases with each customer query, you can use a Cache scope to arrange to send a request to the databases fewer times – say, once every ten minutes – and present users with the cached flight pricing information. Where timeliness of data is not critical, Cache scope can save time and processing power. Note that you can put any number of message processors (such as connectors or components) into a Cache scope and configure the caching strategy to store the responses (which contain the payload of the response message) produced by the processing that occurs within the scope. The cache scope also works in clustered environments because the object store configured in the caching strategy is shared across all nodes in the cluster. ## Caching Process The Cache scope caches repeatable streams. It does not cache nonrepeatable streams, which can be read only once before they are lost. By default, all streams are repeatable in Mule unless a component’s streaming strategy is configured to be nonrepeatable. In general, the caching process follows this sequence: 1. A message enters the Cache scope. 2. The Cache scope determines whether the message payload is nonrepeatable. 3. The Cache scope generates a key to identify the message’s payload. By default, Mule uses an SHA256KeyGenerator and a SHA256 digest to generate a unique key for the message payload. However, you can set up your own key through a custom caching strategy. 4. The Cache scope compares the newly generated key to cached responses that it has previously processed and saves it in the ObjectStore you set up (recommended) or in the default `InMemoryObjectStore`. - If there is no cached response event (a _cache miss_), the Cache scope processes the new message and produces a response. It also saves the resulting response in the object store (if the response is repeatable). - If there is a cached response event (a _cache hit_), the caching strategy generates a response that combines data from both the new request and the cached response. Note that if the generated response is a nonrepeatable stream, the scope does not cache the response. 5. The Cache scope pushes the response out into the parent flow for continued processing. ## Caching Strategy A caching strategy defines the actions a Cache scope takes when a message enters its sub-flow. By default, the Cache scope uses a caching strategy that stores data in an in-memory object store. You can create a custom caching strategy that references an existing object store, or you can create a new custom object store to use in this caching strategy. You can configure the cache size, expiration time, and maximum allowed entries by setting these values in the object store that you define or reference from the caching strategy. You can also configure a caching strategy to synchronize access to the cache, to avoid different message processors from using the cache at the same time. Your caching strategy can also reference these customizations: - Event Key for the ObjectStore, which is a DataWeave expression or Java object used to create the key to use for storing the payload in the ObjectStore. - Response Generator for your strategy, which is a reference to a Java object that is used to create the responses returned by the caching strategy. - Event Copy Strategy for mutable or immutable data. ## Filters Instead of processing all message payloads that it receives, the Cache scope can exclude specific payloads from the Cache scope flow based on an DataWeave expression. ## Example In Anypoint Studio, you can download and open the example project _Cache Scope with Salesforce Contacts_ from Anypoint Exchange to learn more about how to use the Cache scope. This example caches fetched data from Salesforce. When a query is issued to request the data again, results are returned from cache and a new call to Salesforce is not made. To download and open this example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/4.11/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.11/cache-scope-strategy) - [Streaming in Mule Applications](https://docs.mulesoft.com/mule-runtime/4.11/streaming-about) --- product: Mule Runtime version: 4.12 keywords: cache, anypoint, studio --- # Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Cache scope is for storing and reusing frequently called data. You can use a Cache scope to reduce the processing load on the Mule instance and to increase the speed of message processing within a flow. It is particularly effective for these tasks: - Processing repeated requests for the same information. - Processing requests for information that involve large repeatable streams. When a message processor in a Mule app sends a message to the Cache scope, the parent flow expects an output. The Cache scope processes the message payload, delivers the output to the parent flow, and saves the output (that is, caches the response). The next time the Cache scope receives the same kind of message payload, the scope can offer a cached response rather than invoking a potentially time-consuming process again. For instance, you can use a Cache scope to manage customer requests for flight information. Many customers might request the same pricing information about flights from San Francisco to Buenos Aires. Rather than using a lot of processing power to send separate requests to several airline databases with each customer query, you can use a Cache scope to arrange to send a request to the databases fewer times – say, once every ten minutes – and present users with the cached flight pricing information. Where timeliness of data is not critical, Cache scope can save time and processing power. Note that you can put any number of message processors (such as connectors or components) into a Cache scope and configure the caching strategy to store the responses (which contain the payload of the response message) produced by the processing that occurs within the scope. The cache scope also works in clustered environments because the object store configured in the caching strategy is shared across all nodes in the cluster. ## Caching Process The Cache scope caches repeatable streams. It does not cache nonrepeatable streams, which can be read only once before they are lost. By default, all streams are repeatable in Mule unless a component’s streaming strategy is configured to be nonrepeatable. In general, the caching process follows this sequence: 1. A message enters the Cache scope. 2. The Cache scope determines whether the message payload is nonrepeatable. 3. The Cache scope generates a key to identify the message’s payload. By default, Mule uses an SHA256KeyGenerator and a SHA256 digest to generate a unique key for the message payload. However, you can set up your own key through a custom caching strategy. 4. The Cache scope compares the newly generated key to cached responses that it has previously processed and saves it in the ObjectStore you set up (recommended) or in the default `InMemoryObjectStore`. - If there is no cached response event (a _cache miss_), the Cache scope processes the new message and produces a response. It also saves the resulting response in the object store (if the response is repeatable). - If there is a cached response event (a _cache hit_), the caching strategy generates a response that combines data from both the new request and the cached response. Note that if the generated response is a nonrepeatable stream, the scope does not cache the response. 5. The Cache scope pushes the response out into the parent flow for continued processing. ## Caching Strategy A caching strategy defines the actions a Cache scope takes when a message enters its sub-flow. By default, the Cache scope uses a caching strategy that stores data in an in-memory object store. You can create a custom caching strategy that references an existing object store, or you can create a new custom object store to use in this caching strategy. You can configure the cache size, expiration time, and maximum allowed entries by setting these values in the object store that you define or reference from the caching strategy. You can also configure a caching strategy to synchronize access to the cache, to avoid different message processors from using the cache at the same time. Your caching strategy can also reference these customizations: - Event Key for the ObjectStore, which is a DataWeave expression or Java object used to create the key to use for storing the payload in the ObjectStore. - Response Generator for your strategy, which is a reference to a Java object that is used to create the responses returned by the caching strategy. - Event Copy Strategy for mutable or immutable data. ## Filters Instead of processing all message payloads that it receives, the Cache scope can exclude specific payloads from the Cache scope flow based on an DataWeave expression. ## Example In Anypoint Studio, you can download and open the example project _Cache Scope with Salesforce Contacts_ from Anypoint Exchange to learn more about how to use the Cache scope. This example caches fetched data from Salesforce. When a query is issued to request the data again, results are returned from cache and a new call to Salesforce is not made. To download and open this example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/4.12/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.12/cache-scope-strategy) - [Streaming in Mule Applications](https://docs.mulesoft.com/mule-runtime/4.12/streaming-about) --- product: Mule Runtime version: 4.3 keywords: cache, anypoint, studio --- # Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Cache scope is for storing and reusing frequently called data. You can use a Cache scope to reduce the processing load on the Mule instance and to increase the speed of message processing within a flow. It is particularly effective for these tasks: - Processing repeated requests for the same information. - Processing requests for information that involve large repeatable streams. When a message processor in a Mule app sends a message to the Cache scope, the parent flow expects an output. The Cache scope processes the message payload, delivers the output to the parent flow, and saves the output (that is, caches the response). The next time the Cache scope receives the same kind of message payload, the scope can offer a cached response rather than invoking a potentially time-consuming process again. For instance, you can use a Cache scope to manage customer requests for flight information. Many customers might request the same pricing information about flights from San Francisco to Buenos Aires. Rather than using a lot of processing power to send separate requests to several airline databases with each customer query, you can use a Cache scope to arrange to send a request to the databases fewer times – say, once every ten minutes – and present users with the cached flight pricing information. Where timeliness of data is not critical, Cache scope can save time and processing power. Note that you can put any number of message processors (such as connectors or components) into a Cache scope and configure the caching strategy to store the responses (which contain the payload of the response message) produced by the processing that occurs within the scope. The cache scope also works in clustered environments because the object store configured in the caching strategy is shared across all nodes in the cluster. ## Caching Process The Cache scope caches repeatable streams. It does not cache nonrepeatable streams, which can be read only once before they are lost. By default, all streams are repeatable in Mule unless a component’s streaming strategy is configured to be nonrepeatable. In general, the caching process follows this sequence: 1. A message enters the Cache scope. 2. The Cache scope determines whether the message payload is nonrepeatable. 3. The Cache scope generates a key to identify the message’s payload. By default, Mule uses an SHA256KeyGenerator and a SHA256 digest to generate a unique key for the message payload. However, you can set up your own key through a custom caching strategy. 4. The Cache scope compares the newly generated key to cached responses that it has previously processed and saves it in the ObjectStore you set up (recommended) or in the default `InMemoryObjectStore`. - If there is no cached response event (a _cache miss_), the Cache scope processes the new message and produces a response. It also saves the resulting response in the object store (if the response is repeatable). - If there is a cached response event (a _cache hit_), the caching strategy generates a response that combines data from both the new request and the cached response. Note that if the generated response is a nonrepeatable stream, the scope does not cache the response. 5. The Cache scope pushes the response out into the parent flow for continued processing. ## Caching Strategy A caching strategy defines the actions a Cache scope takes when a message enters its sub-flow. By default, the Cache scope uses a caching strategy that stores data in an in-memory object store. You can create a custom caching strategy that references an existing object store, or you can create a new custom object store to use in this caching strategy. You can configure the cache size, expiration time, and maximum allowed entries by setting these values in the object store that you define or reference from the caching strategy. You can also configure a caching strategy to synchronize access to the cache, to avoid different message processors from using the cache at the same time. Your caching strategy can also reference these customizations: - Event Key for the ObjectStore, which is a DataWeave expression or Java object used to create the key to use for storing the payload in the ObjectStore. - Response Generator for your strategy, which is a reference to a Java object that is used to create the responses returned by the caching strategy. - Event Copy Strategy for mutable or immutable data. ## Filters Instead of processing all message payloads that it receives, the Cache scope can exclude specific payloads from the Cache scope flow based on an DataWeave expression. ## Example In Anypoint Studio, you can download and open the example project _Cache Scope with Salesforce Contacts_ from Anypoint Exchange to learn more about how to use the Cache scope. This example caches fetched data from Salesforce. When a query is issued to request the data again, results are returned from cache and a new call to Salesforce is not made. To download and open this example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/4.3/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.3/cache-scope-strategy) - [Streaming in Mule Applications](https://docs.mulesoft.com/mule-runtime/4.3/streaming-about) --- product: Mule Runtime version: 4.4 keywords: cache, anypoint, studio --- # Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Cache scope is for storing and reusing frequently called data. You can use a Cache scope to reduce the processing load on the Mule instance and to increase the speed of message processing within a flow. It is particularly effective for these tasks: - Processing repeated requests for the same information. - Processing requests for information that involve large repeatable streams. When a message processor in a Mule app sends a message to the Cache scope, the parent flow expects an output. The Cache scope processes the message payload, delivers the output to the parent flow, and saves the output (that is, caches the response). The next time the Cache scope receives the same kind of message payload, the scope can offer a cached response rather than invoking a potentially time-consuming process again. For instance, you can use a Cache scope to manage customer requests for flight information. Many customers might request the same pricing information about flights from San Francisco to Buenos Aires. Rather than using a lot of processing power to send separate requests to several airline databases with each customer query, you can use a Cache scope to arrange to send a request to the databases fewer times – say, once every ten minutes – and present users with the cached flight pricing information. Where timeliness of data is not critical, Cache scope can save time and processing power. Note that you can put any number of message processors (such as connectors or components) into a Cache scope and configure the caching strategy to store the responses (which contain the payload of the response message) produced by the processing that occurs within the scope. The cache scope also works in clustered environments because the object store configured in the caching strategy is shared across all nodes in the cluster. ## Caching Process The Cache scope caches repeatable streams. It does not cache nonrepeatable streams, which can be read only once before they are lost. By default, all streams are repeatable in Mule unless a component’s streaming strategy is configured to be nonrepeatable. In general, the caching process follows this sequence: 1. A message enters the Cache scope. 2. The Cache scope determines whether the message payload is nonrepeatable. 3. The Cache scope generates a key to identify the message’s payload. By default, Mule uses an SHA256KeyGenerator and a SHA256 digest to generate a unique key for the message payload. However, you can set up your own key through a custom caching strategy. 4. The Cache scope compares the newly generated key to cached responses that it has previously processed and saves it in the ObjectStore you set up (recommended) or in the default `InMemoryObjectStore`. - If there is no cached response event (a _cache miss_), the Cache scope processes the new message and produces a response. It also saves the resulting response in the object store (if the response is repeatable). - If there is a cached response event (a _cache hit_), the caching strategy generates a response that combines data from both the new request and the cached response. Note that if the generated response is a nonrepeatable stream, the scope does not cache the response. 5. The Cache scope pushes the response out into the parent flow for continued processing. ## Caching Strategy A caching strategy defines the actions a Cache scope takes when a message enters its sub-flow. By default, the Cache scope uses a caching strategy that stores data in an in-memory object store. You can create a custom caching strategy that references an existing object store, or you can create a new custom object store to use in this caching strategy. You can configure the cache size, expiration time, and maximum allowed entries by setting these values in the object store that you define or reference from the caching strategy. You can also configure a caching strategy to synchronize access to the cache, to avoid different message processors from using the cache at the same time. Your caching strategy can also reference these customizations: - Event Key for the ObjectStore, which is a DataWeave expression or Java object used to create the key to use for storing the payload in the ObjectStore. - Response Generator for your strategy, which is a reference to a Java object that is used to create the responses returned by the caching strategy. - Event Copy Strategy for mutable or immutable data. ## Filters Instead of processing all message payloads that it receives, the Cache scope can exclude specific payloads from the Cache scope flow based on an DataWeave expression. ## Example In Anypoint Studio, you can download and open the example project _Cache Scope with Salesforce Contacts_ from Anypoint Exchange to learn more about how to use the Cache scope. This example caches fetched data from Salesforce. When a query is issued to request the data again, results are returned from cache and a new call to Salesforce is not made. To download and open this example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/4.4/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.4/cache-scope-strategy) - [Streaming in Mule Applications](https://docs.mulesoft.com/mule-runtime/4.4/streaming-about) --- product: Mule Runtime version: 4.6 keywords: cache, anypoint, studio --- # Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Cache scope is for storing and reusing frequently called data. You can use a Cache scope to reduce the processing load on the Mule instance and to increase the speed of message processing within a flow. It is particularly effective for these tasks: - Processing repeated requests for the same information. - Processing requests for information that involve large repeatable streams. When a message processor in a Mule app sends a message to the Cache scope, the parent flow expects an output. The Cache scope processes the message payload, delivers the output to the parent flow, and saves the output (that is, caches the response). The next time the Cache scope receives the same kind of message payload, the scope can offer a cached response rather than invoking a potentially time-consuming process again. For instance, you can use a Cache scope to manage customer requests for flight information. Many customers might request the same pricing information about flights from San Francisco to Buenos Aires. Rather than using a lot of processing power to send separate requests to several airline databases with each customer query, you can use a Cache scope to arrange to send a request to the databases fewer times – say, once every ten minutes – and present users with the cached flight pricing information. Where timeliness of data is not critical, Cache scope can save time and processing power. Note that you can put any number of message processors (such as connectors or components) into a Cache scope and configure the caching strategy to store the responses (which contain the payload of the response message) produced by the processing that occurs within the scope. The cache scope also works in clustered environments because the object store configured in the caching strategy is shared across all nodes in the cluster. ## Caching Process The Cache scope caches repeatable streams. It does not cache nonrepeatable streams, which can be read only once before they are lost. By default, all streams are repeatable in Mule unless a component’s streaming strategy is configured to be nonrepeatable. In general, the caching process follows this sequence: 1. A message enters the Cache scope. 2. The Cache scope determines whether the message payload is nonrepeatable. 3. The Cache scope generates a key to identify the message’s payload. By default, Mule uses an SHA256KeyGenerator and a SHA256 digest to generate a unique key for the message payload. However, you can set up your own key through a custom caching strategy. 4. The Cache scope compares the newly generated key to cached responses that it has previously processed and saves it in the ObjectStore you set up (recommended) or in the default `InMemoryObjectStore`. - If there is no cached response event (a _cache miss_), the Cache scope processes the new message and produces a response. It also saves the resulting response in the object store (if the response is repeatable). - If there is a cached response event (a _cache hit_), the caching strategy generates a response that combines data from both the new request and the cached response. Note that if the generated response is a nonrepeatable stream, the scope does not cache the response. 5. The Cache scope pushes the response out into the parent flow for continued processing. ## Caching Strategy A caching strategy defines the actions a Cache scope takes when a message enters its sub-flow. By default, the Cache scope uses a caching strategy that stores data in an in-memory object store. You can create a custom caching strategy that references an existing object store, or you can create a new custom object store to use in this caching strategy. You can configure the cache size, expiration time, and maximum allowed entries by setting these values in the object store that you define or reference from the caching strategy. You can also configure a caching strategy to synchronize access to the cache, to avoid different message processors from using the cache at the same time. Your caching strategy can also reference these customizations: - Event Key for the ObjectStore, which is a DataWeave expression or Java object used to create the key to use for storing the payload in the ObjectStore. - Response Generator for your strategy, which is a reference to a Java object that is used to create the responses returned by the caching strategy. - Event Copy Strategy for mutable or immutable data. ## Filters Instead of processing all message payloads that it receives, the Cache scope can exclude specific payloads from the Cache scope flow based on an DataWeave expression. ## Example In Anypoint Studio, you can download and open the example project _Cache Scope with Salesforce Contacts_ from Anypoint Exchange to learn more about how to use the Cache scope. This example caches fetched data from Salesforce. When a query is issued to request the data again, results are returned from cache and a new call to Salesforce is not made. To download and open this example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/4.6/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.6/cache-scope-strategy) - [Streaming in Mule Applications](https://docs.mulesoft.com/mule-runtime/4.6/streaming-about) --- product: Mule Runtime version: 4.9 keywords: cache, anypoint, studio --- # Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Cache scope is for storing and reusing frequently called data. You can use a Cache scope to reduce the processing load on the Mule instance and to increase the speed of message processing within a flow. It is particularly effective for these tasks: - Processing repeated requests for the same information. - Processing requests for information that involve large repeatable streams. When a message processor in a Mule app sends a message to the Cache scope, the parent flow expects an output. The Cache scope processes the message payload, delivers the output to the parent flow, and saves the output (that is, caches the response). The next time the Cache scope receives the same kind of message payload, the scope can offer a cached response rather than invoking a potentially time-consuming process again. For instance, you can use a Cache scope to manage customer requests for flight information. Many customers might request the same pricing information about flights from San Francisco to Buenos Aires. Rather than using a lot of processing power to send separate requests to several airline databases with each customer query, you can use a Cache scope to arrange to send a request to the databases fewer times – say, once every ten minutes – and present users with the cached flight pricing information. Where timeliness of data is not critical, Cache scope can save time and processing power. Note that you can put any number of message processors (such as connectors or components) into a Cache scope and configure the caching strategy to store the responses (which contain the payload of the response message) produced by the processing that occurs within the scope. The cache scope also works in clustered environments because the object store configured in the caching strategy is shared across all nodes in the cluster. ## Caching Process The Cache scope caches repeatable streams. It does not cache nonrepeatable streams, which can be read only once before they are lost. By default, all streams are repeatable in Mule unless a component’s streaming strategy is configured to be nonrepeatable. In general, the caching process follows this sequence: 1. A message enters the Cache scope. 2. The Cache scope determines whether the message payload is nonrepeatable. 3. The Cache scope generates a key to identify the message’s payload. By default, Mule uses an SHA256KeyGenerator and a SHA256 digest to generate a unique key for the message payload. However, you can set up your own key through a custom caching strategy. 4. The Cache scope compares the newly generated key to cached responses that it has previously processed and saves it in the ObjectStore you set up (recommended) or in the default `InMemoryObjectStore`. - If there is no cached response event (a _cache miss_), the Cache scope processes the new message and produces a response. It also saves the resulting response in the object store (if the response is repeatable). - If there is a cached response event (a _cache hit_), the caching strategy generates a response that combines data from both the new request and the cached response. Note that if the generated response is a nonrepeatable stream, the scope does not cache the response. 5. The Cache scope pushes the response out into the parent flow for continued processing. ## Caching Strategy A caching strategy defines the actions a Cache scope takes when a message enters its sub-flow. By default, the Cache scope uses a caching strategy that stores data in an in-memory object store. You can create a custom caching strategy that references an existing object store, or you can create a new custom object store to use in this caching strategy. You can configure the cache size, expiration time, and maximum allowed entries by setting these values in the object store that you define or reference from the caching strategy. You can also configure a caching strategy to synchronize access to the cache, to avoid different message processors from using the cache at the same time. Your caching strategy can also reference these customizations: - Event Key for the ObjectStore, which is a DataWeave expression or Java object used to create the key to use for storing the payload in the ObjectStore. - Response Generator for your strategy, which is a reference to a Java object that is used to create the responses returned by the caching strategy. - Event Copy Strategy for mutable or immutable data. ## Filters Instead of processing all message payloads that it receives, the Cache scope can exclude specific payloads from the Cache scope flow based on an DataWeave expression. ## Example In Anypoint Studio, you can download and open the example project _Cache Scope with Salesforce Contacts_ from Anypoint Exchange to learn more about how to use the Cache scope. This example caches fetched data from Salesforce. When a query is issued to request the data again, results are returned from cache and a new call to Salesforce is not made. To download and open this example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/4.9/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.9/cache-scope-strategy) - [Streaming in Mule Applications](https://docs.mulesoft.com/mule-runtime/4.9/streaming-about) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: cache, anypoint, studio --- # Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Cache scope is for storing and reusing frequently called data. You can use a Cache scope to reduce the processing load on the Mule instance and to increase the speed of message processing within a flow. It is particularly effective for these tasks: - Processing repeated requests for the same information. - Processing requests for information that involve large repeatable streams. When a message processor in a Mule app sends a message to the Cache scope, the parent flow expects an output. The Cache scope processes the message payload, delivers the output to the parent flow, and saves the output (that is, caches the response). The next time the Cache scope receives the same kind of message payload, the scope can offer a cached response rather than invoking a potentially time-consuming process again. For instance, you can use a Cache scope to manage customer requests for flight information. Many customers might request the same pricing information about flights from San Francisco to Buenos Aires. Rather than using a lot of processing power to send separate requests to several airline databases with each customer query, you can use a Cache scope to arrange to send a request to the databases fewer times – say, once every ten minutes – and present users with the cached flight pricing information. Where timeliness of data is not critical, Cache scope can save time and processing power. You can put any number of message processors (such as connectors or components) into a Cache scope and configure the caching strategy to store the responses (which contain the payload of the response message) produced by the processing that occurs within the scope. The cache scope also works in clustered environments because the object store configured in the caching strategy is shared across all nodes in the cluster. ## Caching Process The Cache scope caches repeatable streams. It does not cache nonrepeatable streams, which can be read only once before they are lost. By default, all streams are repeatable in Mule unless a component’s streaming strategy is configured to be nonrepeatable. In general, the caching process follows this sequence: 1. A message enters the Cache scope. 2. The Cache scope determines whether the message payload is nonrepeatable. 3. The Cache scope generates a key to identify the message’s payload. By default, Mule uses an `SHA256KeyGenerator` and a SHA256 digest to generate a unique key for the message payload. However, you can define a custom key by setting a Key Expression in your caching strategy. 4. The Cache scope compares the newly generated key to cached responses that it has previously processed and saves it in the ObjectStore you set up (recommended) or in the default `InMemoryObjectStore`. - If there is no cached response (a _cache miss_), the Cache scope processes the new message and produces a response. It also saves the resulting response in the object store (if the response is repeatable). - If there is a cached response (a _cache hit_), the caching strategy generates a response that combines data from both the new request and the cached response. If the generated response is a nonrepeatable stream, the scope does not cache the response. 5. The Cache scope pushes the response out into the parent flow for continued processing. ## Caching Strategy A caching strategy defines the actions a Cache scope takes when a message enters its sub-flow. By default, the Cache scope uses a caching strategy that stores data in an in-memory object store. You can create a custom caching strategy that references an existing object store, or you can create a new custom object store to use in this caching strategy. You can configure the cache size, expiration time, and maximum allowed entries by setting these values in the object store that you define or reference from the caching strategy. You can also configure a caching strategy to synchronize access to the cache, to avoid different message processors from using the cache at the same time. Your caching strategy can also reference a Key Expression for the object store, which is a DataWeave expression that creates the key for storing the payload in the object store. The Cache scope persists only the message (payload and attributes) in the object store, not the full Mule event. Because these Java-based customizations require the full Mule event, they’re deprecated: > [!WARNING] Key Generator, Response Generator, and Event Copy Strategy are deprecated because they > require Java implementations that operate on the full Mule event. > > Applications with a `minMuleVersion` of 4.13 or later can’t use these customizations: Anypoint > Studio doesn’t show them, and deploying such an application fails if any of them is configured. > Applications with an earlier `minMuleVersion` can continue to use them. For details, see [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/latest/cache-scope-strategy). ## Filters Instead of processing all message payloads that it receives, the Cache scope can exclude specific payloads from the Cache scope flow based on an DataWeave expression. ## Example In Anypoint Studio, you can download and open the example project _Cache Scope with Salesforce Contacts_ from Anypoint Exchange to learn more about how to use the Cache scope. This example caches fetched data from Salesforce. When a query is issued to request the data again, results are returned from cache and a new call to Salesforce is not made. To download and open this example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/latest/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/latest/cache-scope-strategy) - [Streaming in Mule Applications](https://docs.mulesoft.com/mule-runtime/latest/streaming-about) - [Feature Flagging Mechanism](https://docs.mulesoft.com/mule-runtime/latest/feature-flagging) --- product: Mule Runtime version: 4.11 --- # Caching > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Identifying key aspects of your data such as when to use cache and which cache strategy to follow, helps you to improve processing performance: - Is the data frequently called, with often repeated results? - Can you afford eventual consistency between the data source and the cache information? At least for a while until cache refreshes. Mule runtime engine (Mule) offers customizable strategies, such as the Cache scope and the HTTP Caching API Gateway policy, to enable cache according to your needs. Both strategies help applications that constantly request the same data by reducing the processing load, especially network interactions with a remote host. For Cache scope, consider a production environment in which the default in-memory caching consumes all of your memory resources. To avoid this consumption, use an object-store caching configuration with well-defined storage and expiry policies. ## See Also - [Cache Scope](https://docs.mulesoft.com/mule-runtime/4.11/cache-scope) - [HTTP Caching](https://docs.mulesoft.com/gateway/latest/policies-included-http-caching) --- product: Mule Runtime version: 4.12 --- # Caching > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Identifying key aspects of your data such as when to use cache and which cache strategy to follow, helps you to improve processing performance: - Is the data frequently called, with often repeated results? - Can you afford eventual consistency between the data source and the cache information? At least for a while until cache refreshes. Mule runtime engine (Mule) offers customizable strategies, such as the Cache scope and the HTTP Caching API Gateway policy, to enable cache according to your needs. Both strategies help applications that constantly request the same data by reducing the processing load, especially network interactions with a remote host. For Cache scope, consider a production environment in which the default in-memory caching consumes all of your memory resources. To avoid this consumption, use an object-store caching configuration with well-defined storage and expiry policies. ## See Also - [Cache Scope](https://docs.mulesoft.com/mule-runtime/4.12/cache-scope) - [HTTP Caching](https://docs.mulesoft.com/gateway/latest/policies-included-http-caching) --- product: Mule Runtime version: 4.3 --- # Caching > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Identifying key aspects of your data such as when to use cache and which cache strategy to follow, helps you to improve processing performance: - Is the data frequently called, with often repeated results? - Can you afford eventual consistency between the data source and the cache information? At least for a while until cache refreshes. Mule runtime engine (Mule) offers customizable strategies, such as the Cache scope and the HTTP Caching API Gateway policy, to enable cache according to your needs. Both strategies help applications that constantly request the same data by reducing the processing load, especially network interactions with a remote host. For Cache scope, consider a production environment in which the default in-memory caching consumes all of your memory resources. To avoid this consumption, use an object-store caching configuration with well-defined storage and expiry policies. ## See Also - [Cache Scope](https://docs.mulesoft.com/mule-runtime/4.3/cache-scope) - [HTTP Caching](https://docs.mulesoft.com/gateway/latest/policies-included-http-caching) --- product: Mule Runtime version: 4.4 --- # Caching > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Identifying key aspects of your data such as when to use cache and which cache strategy to follow, helps you to improve processing performance: - Is the data frequently called, with often repeated results? - Can you afford eventual consistency between the data source and the cache information? At least for a while until cache refreshes. Mule runtime engine (Mule) offers customizable strategies, such as the Cache scope and the HTTP Caching API Gateway policy, to enable cache according to your needs. Both strategies help applications that constantly request the same data by reducing the processing load, especially network interactions with a remote host. For Cache scope, consider a production environment in which the default in-memory caching consumes all of your memory resources. To avoid this consumption, use an object-store caching configuration with well-defined storage and expiry policies. ## See Also - [Cache Scope](https://docs.mulesoft.com/mule-runtime/4.4/cache-scope) - [HTTP Caching](https://docs.mulesoft.com/gateway/latest/policies-included-http-caching) --- product: Mule Runtime version: 4.6 --- # Caching > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Identifying key aspects of your data such as when to use cache and which cache strategy to follow, helps you to improve processing performance: - Is the data frequently called, with often repeated results? - Can you afford eventual consistency between the data source and the cache information? At least for a while until cache refreshes. Mule runtime engine (Mule) offers customizable strategies, such as the Cache scope and the HTTP Caching API Gateway policy, to enable cache according to your needs. Both strategies help applications that constantly request the same data by reducing the processing load, especially network interactions with a remote host. For Cache scope, consider a production environment in which the default in-memory caching consumes all of your memory resources. To avoid this consumption, use an object-store caching configuration with well-defined storage and expiry policies. ## See Also - [Cache Scope](https://docs.mulesoft.com/mule-runtime/4.6/cache-scope) - [HTTP Caching](https://docs.mulesoft.com/gateway/latest/policies-included-http-caching) --- product: Mule Runtime version: 4.9 --- # Caching > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Identifying key aspects of your data such as when to use cache and which cache strategy to follow, helps you to improve processing performance: - Is the data frequently called, with often repeated results? - Can you afford eventual consistency between the data source and the cache information? At least for a while until cache refreshes. Mule runtime engine (Mule) offers customizable strategies, such as the Cache scope and the HTTP Caching API Gateway policy, to enable cache according to your needs. Both strategies help applications that constantly request the same data by reducing the processing load, especially network interactions with a remote host. For Cache scope, consider a production environment in which the default in-memory caching consumes all of your memory resources. To avoid this consumption, use an object-store caching configuration with well-defined storage and expiry policies. ## See Also - [Cache Scope](https://docs.mulesoft.com/mule-runtime/4.9/cache-scope) - [HTTP Caching](https://docs.mulesoft.com/gateway/latest/policies-included-http-caching) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Caching > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Identifying key aspects of your data such as when to use cache and which cache strategy to follow, helps you to improve processing performance: - Is the data frequently called, with often repeated results? - Can you afford eventual consistency between the data source and the cache information? At least for a while until cache refreshes. Mule runtime engine (Mule) offers customizable strategies, such as the Cache scope and the HTTP Caching API Gateway policy, to enable cache according to your needs. Both strategies help applications that constantly request the same data by reducing the processing load, especially network interactions with a remote host. For Cache scope, consider a production environment in which the default in-memory caching consumes all of your memory resources. To avoid this consumption, use an object-store caching configuration with well-defined storage and expiry policies. ## See Also - [Cache Scope](https://docs.mulesoft.com/mule-runtime/latest/cache-scope) - [HTTP Caching](https://docs.mulesoft.com/gateway/latest/policies-included-http-caching) --- product: Mule Runtime version: 4.11 --- # Change the Target Output of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the Transform Message component outputs to the message payload. You can change this target, so that the result of your transformation populates another part of the output such as a property or variable. 1. Click **Edit Current Target** above the DataWeave code editor. ![Edit icon](/mulesoft/current/en-us/mule-runtime/4.11/_images/using-dataweave-in-studio-47984.png) 2. Specify where in the output Mule message to place the result of your DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![An output with an option to choose a source code](/mulesoft/current/en-us/mule-runtime/4.11/_images/dw-new-variable.png) ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.11/transform-component-about) [Add Another Output to the Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.11/transform-add-another-output-transform-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.11/dataweave) --- product: Mule Runtime version: 4.12 --- # Change the Target Output of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the Transform Message component outputs to the message payload. You can change this target, so that the result of your transformation populates another part of the output such as a property or variable. 1. Click **Edit Current Target** above the DataWeave code editor. ![Edit icon](/mulesoft/current/en-us/mule-runtime/4.12/_images/using-dataweave-in-studio-47984.png) 2. Specify where in the output Mule message to place the result of your DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![An output with an option to choose a source code](/mulesoft/current/en-us/mule-runtime/4.12/_images/dw-new-variable.png) ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.12/transform-component-about) [Add Another Output to the Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.12/transform-add-another-output-transform-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.12/dataweave) --- product: Mule Runtime version: 4.3 --- # Change the Target Output of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the Transform Message component outputs to the message payload. You can change this target, so that the result of your transformation populates another part of the output such as a property or variable. 1. Click **Edit Current Target** above the DataWeave code editor. ![using dataweave in studio 47984](/mulesoft/current/en-us/mule-runtime/4.3/_images/using-dataweave-in-studio-47984.png) 2. Specify where in the output Mule message to place the result of your DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![new variable](/mulesoft/current/en-us/mule-runtime/4.3/_images/dw-new-variable.png) ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.3/transform-component-about) [Add Another Output to the Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.3/transform-add-another-output-transform-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) --- product: Mule Runtime version: 4.4 --- # Change the Target Output of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the Transform Message component outputs to the message payload. You can change this target, so that the result of your transformation populates another part of the output such as a property or variable. 1. Click **Edit Current Target** above the DataWeave code editor. ![using dataweave in studio 47984](/mulesoft/current/en-us/mule-runtime/4.4/_images/using-dataweave-in-studio-47984.png) 2. Specify where in the output Mule message to place the result of your DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![new variable](/mulesoft/current/en-us/mule-runtime/4.4/_images/dw-new-variable.png) ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.4/transform-component-about) [Add Another Output to the Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.4/transform-add-another-output-transform-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) --- product: Mule Runtime version: 4.6 --- # Change the Target Output of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the Transform Message component outputs to the message payload. You can change this target, so that the result of your transformation populates another part of the output such as a property or variable. 1. Click **Edit Current Target** above the DataWeave code editor. ![using dataweave in studio 47984](/mulesoft/current/en-us/mule-runtime/4.6/_images/using-dataweave-in-studio-47984.png) 2. Specify where in the output Mule message to place the result of your DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![new variable](/mulesoft/current/en-us/mule-runtime/4.6/_images/dw-new-variable.png) ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.6/transform-component-about) [Add Another Output to the Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.6/transform-add-another-output-transform-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.6/dataweave) --- product: Mule Runtime version: 4.9 --- # Change the Target Output of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the Transform Message component outputs to the message payload. You can change this target, so that the result of your transformation populates another part of the output such as a property or variable. 1. Click **Edit Current Target** above the DataWeave code editor. ![Edit icon](/mulesoft/current/en-us/mule-runtime/4.9/_images/using-dataweave-in-studio-47984.png) 2. Specify where in the output Mule message to place the result of your DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![An output with an option to choose a source code](/mulesoft/current/en-us/mule-runtime/4.9/_images/dw-new-variable.png) ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.9/transform-component-about) [Add Another Output to the Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.9/transform-add-another-output-transform-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.9/dataweave) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Change the Target Output of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the Transform Message component outputs to the message payload. You can change this target, so that the result of your transformation populates another part of the output such as a property or variable. 1. Click **Edit Current Target** above the DataWeave code editor. ![Edit icon](/mulesoft/current/en-us/mule-runtime/latest/_images/using-dataweave-in-studio-47984.png) 2. Specify where in the output Mule message to place the result of your DataWeave transform. In case you’re creating a new variable or property, you must also set a name for it. ![An output with an option to choose a source code](/mulesoft/current/en-us/mule-runtime/latest/_images/dw-new-variable.png) ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/latest/transform-component-about) [Add Another Output to the Transform Message Component](https://docs.mulesoft.com/mule-runtime/latest/transform-add-another-output-transform-studio-task) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/latest/about-mule-message) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/latest/dataweave) --- product: Mule Runtime version: 4.11 --- # Choice Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Choice router dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. Only one of the routes in the Choice router executes, meaning that the first expression that evaluates to `true` triggers that route’s execution and the others are not checked. If none of the expressions are `true`, then the default route executes. ![A choice router schematic showing multiple options, one being the default](/mulesoft/current/en-us/mule-runtime/4.11/_images/component-choice-schematic.png) Figure 1. Schematic diagram of a Choice router with three options, one being the default option ## Configuration To configure the Choice router, specify one or more conditions to evaluate, and the message processors that execute when any condition evaluates to `true`. Additionally, configure a default route that executes when none of the defined conditions are `true`. ### Anypoint Studio Configuration To configure the Choice router in Studio, follow these steps: ![A flow showing the configuration of a Choice component in Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-choice-configuration-studio.png) 1. Drag the **Choice** component to any point of the flow. 2. Click **When**, inside the Choice router, and configure the **Expression** value in the properties window to specify the condition to evaluate. 3. Drag message processors inside **When** to specify the processors to execute when the condition is met. 4. Drag message processors inside **Default** to specify the processors to execute when none of the defined conditions are met. ### XML Configuration Following is the basic XML structure for a Choice router: ```xml (1) (2) (3) ```
1The expression attribute has the condition to evaluate.
2Add any number of message processors to execute if expression evaluates to true.
3Add any number of message processors to execute if none of the conditions evaluates to true.
## Adding Routes to the Choice Router By default, the Choice router has one route option that executes when the configured DataWeave expression evaluates to `true`, and a default route that executes when none of the expressions in the existing routes are `true`. Add more routes when you need to evaluate more than one condition and then execute different operations depending on which condition is met. ### Add Routes by Dragging Components in Studio From **Mule Palette** in Anypoint Studio, click any component and drag it into the Choice router, where you see a vertical black line: ![A flow showing a content-based routing configuration](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-choice-add-route.png) ### Add Routes by Editing the XML You can also add additional route options to a Choice router by modifying the XML configuration file: 1. In Studio, right-click the Choice router and select **Go to XML…​**. 2. Inside the `` element, add a `` element: ```xml ``` After adding a new `` element, the new route option shows in the Message Flow view: ![A flow for a new content-based routing path](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-choice-new-route.png) ## Example Project You can use Anypoint Studio to download the example project _Content-Based Routing_ from Anypoint Exchange. This project presents a working example of a flow that uses the Choice router. ![A flow for content-based routing including payload settings and error handling](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-choice-example.png) Figure 2. Flow with a Choice router with three options, one being the default option To download and open this example project: 1. Click the Exchange icon (![](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-exchange-icon.png)) in Anypoint Studio. 2. In the left panel, click **All assets**. 3. In the window that opens, log in to Anypoint Exchange and search for the example project Content-Based Routing. 4. Click the Open icon (![](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-open-exchange-icon.png)). ### Behavior of the Example Project When you run the project as a Mule application, the application performs the following actions: 1. Listens for messages. 2. Passes messages to a Set Variable component that sets the variable `language` to the language that is passed in the message by the parameter `language`. 3. Uses a Choice router to find out whether each message contains a `language` attribute. The presence and value of this attribute determine how the Choice router routes the message: - If the value is `French`, the router routes the message to a Set Payload component that is named _Reply in French_. This latter component returns the message `Bonjour!` to the requester. - If the value is `Spanish`, the router routes the message to a Set Payload component that is named _Reply in Spanish_. This latter component returns the message `Hola!` to the requester. - If the message contains no `language` attribute, the router routes the message to the default path, which is a subflow that: 4. Logs the message "No language specified. Using English as a default." to the console 5. Sets the value of `language` to `English`. 6. Returns the message `Hello!`. The example project demonstrates that, when you are planning to route messages in a flow by using a Choice router, there are four aspects to planning that you need to consider: - The content that the Choice router evaluates to determine how it routes messages - The number of routes - The default routing option - The processing that the flow performs for each routing option ## Example XML Following is the XML code for the Choice router example: ```xml ``` ## Choice Router XML Reference A Choice flow control component contains these elements: - A single root element `` - A `` child element for each routing option, each with an expression to match - Optionally, an `` child element of Choice that handles all cases where none of the expressions on the `` elements evaluate to `true` - Components that are conditionally executed under each of the choices are defined as child elements of the `when` and `otherwise` elements ### Properties of
PropertyDescription

Business Events

For activating the Business Events feature:

<choice doc:name="Choice" tracking:enable-default-events="true" >
### Properties of
PropertyDescription

Expression (expression)

Expression in DataWeave language to evaluate input.
If the expression evaluates to true, this routing option is used:

<when expression="#[vars.language == 'Spanish']" >
## See Also - [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.11/about-flows) - [Extract Data](https://docs.mulesoft.com/dataweave/latest/dataweave-cookbook-extract-data) - [DataWeave Scripts](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction) - [Business Events](https://docs.mulesoft.com/mule-runtime/4.11/business-events) --- product: Mule Runtime version: 4.12 --- # Choice Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Choice router dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. Only one of the routes in the Choice router executes, meaning that the first expression that evaluates to `true` triggers that route’s execution and the others are not checked. If none of the expressions are `true`, then the default route executes. ![A choice router schematic showing multiple options, one being the default](/mulesoft/current/en-us/mule-runtime/4.12/_images/component-choice-schematic.png) Figure 1. Schematic diagram of a Choice router with three options, one being the default option ## Configuration To configure the Choice router, specify one or more conditions to evaluate, and the message processors that execute when any condition evaluates to `true`. Additionally, configure a default route that executes when none of the defined conditions are `true`. ### Anypoint Studio Configuration To configure the Choice router in Studio, follow these steps: ![A flow showing the configuration of a Choice component in Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-choice-configuration-studio.png) 1. Drag the **Choice** component to any point of the flow. 2. Click **When**, inside the Choice router, and configure the **Expression** value in the properties window to specify the condition to evaluate. 3. Drag message processors inside **When** to specify the processors to execute when the condition is met. 4. Drag message processors inside **Default** to specify the processors to execute when none of the defined conditions are met. ### XML Configuration Following is the basic XML structure for a Choice router: ```xml (1) (2) (3) ```
1The expression attribute has the condition to evaluate.
2Add any number of message processors to execute if expression evaluates to true.
3Add any number of message processors to execute if none of the conditions evaluates to true.
## Adding Routes to the Choice Router By default, the Choice router has one route option that executes when the configured DataWeave expression evaluates to `true`, and a default route that executes when none of the expressions in the existing routes are `true`. Add more routes when you need to evaluate more than one condition and then execute different operations depending on which condition is met. ### Add Routes by Dragging Components in Studio From **Mule Palette** in Anypoint Studio, click any component and drag it into the Choice router, where you see a vertical black line: ![A flow showing a content-based routing configuration](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-choice-add-route.png) ### Add Routes by Editing the XML You can also add additional route options to a Choice router by modifying the XML configuration file: 1. In Studio, right-click the Choice router and select **Go to XML…​**. 2. Inside the `` element, add a `` element: ```xml ``` After adding a new `` element, the new route option shows in the Message Flow view: ![A flow for a new content-based routing path](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-choice-new-route.png) ## Example Project You can use Anypoint Studio to download the example project _Content-Based Routing_ from Anypoint Exchange. This project presents a working example of a flow that uses the Choice router. ![A flow for content-based routing including payload settings and error handling](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-choice-example.png) Figure 2. Flow with a Choice router with three options, one being the default option To download and open this example project: 1. Click the Exchange icon (![](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-exchange-icon.png)) in Anypoint Studio. 2. In the left panel, click **All assets**. 3. In the window that opens, log in to Anypoint Exchange and search for the example project Content-Based Routing. 4. Click the Open icon (![](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-open-exchange-icon.png)). ### Behavior of the Example Project When you run the project as a Mule application, the application performs the following actions: 1. Listens for messages. 2. Passes messages to a Set Variable component that sets the variable `language` to the language that is passed in the message by the parameter `language`. 3. Uses a Choice router to find out whether each message contains a `language` attribute. The presence and value of this attribute determine how the Choice router routes the message: - If the value is `French`, the router routes the message to a Set Payload component that is named _Reply in French_. This latter component returns the message `Bonjour!` to the requester. - If the value is `Spanish`, the router routes the message to a Set Payload component that is named _Reply in Spanish_. This latter component returns the message `Hola!` to the requester. - If the message contains no `language` attribute, the router routes the message to the default path, which is a subflow that: 4. Logs the message "No language specified. Using English as a default." to the console 5. Sets the value of `language` to `English`. 6. Returns the message `Hello!`. The example project demonstrates that, when you are planning to route messages in a flow by using a Choice router, there are four aspects to planning that you need to consider: - The content that the Choice router evaluates to determine how it routes messages - The number of routes - The default routing option - The processing that the flow performs for each routing option ## Example XML Following is the XML code for the Choice router example: ```xml ``` ## Choice Router XML Reference A Choice flow control component contains these elements: - A single root element `` - A `` child element for each routing option, each with an expression to match - Optionally, an `` child element of Choice that handles all cases where none of the expressions on the `` elements evaluate to `true` - Components that are conditionally executed under each of the choices are defined as child elements of the `when` and `otherwise` elements ### Properties of
PropertyDescription

Business Events

For activating the Business Events feature:

<choice doc:name="Choice" tracking:enable-default-events="true" >
### Properties of
PropertyDescription

Expression (expression)

Expression in DataWeave language to evaluate input.
If the expression evaluates to true, this routing option is used:

<when expression="#[vars.language == 'Spanish']" >
## See Also - [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.12/about-flows) - [Extract Data](https://docs.mulesoft.com/dataweave/latest/dataweave-cookbook-extract-data) - [DataWeave Scripts](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction) - [Business Events](https://docs.mulesoft.com/mule-runtime/4.12/business-events) --- product: Mule Runtime version: 4.3 --- # Choice Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Choice router dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. Only one of the routes in the Choice router executes, meaning that the first expression that evaluates to `true` triggers that route’s execution and the others are not checked. If none of the expressions are `true`, then the default route executes. ![Choice Router Schematic](/mulesoft/current/en-us/mule-runtime/4.3/_images/component-choice-schematic.png) Figure 1. Schematic diagram of a Choice router with three options, one being the default option ## Configuration To configure the Choice router, specify one or more conditions to evaluate, and the message processors that execute when any condition evaluates to `true`. Additionally, configure a default route that executes when none of the defined conditions are `true`. ### Anypoint Studio Configuration To configure the Choice router in Studio, follow these steps: ![Choice configuration Studio](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-choice-configuration-studio.png) 1. Drag the **Choice** component to any point of the flow. 2. Click **When**, inside the Choice router, and configure the **Expression** value in the properties window to specify the condition to evaluate. 3. Drag message processors inside **When** to specify the processors to execute when the condition is met. 4. Drag message processors inside **Default** to specify the processors to execute when none of the defined conditions are met. ### XML Configuration Following is the basic XML structure for a Choice router: ```xml (1) (2) (3) ```
1The expression attribute has the condition to evaluate.
2Add any number of message processors to execute if expression evaluates to true.
3Add any number of message processors to execute if none of the conditions evaluates to true.
## Adding Routes to the Choice Router By default, the Choice router has one route option that executes when the configured DataWeave expression evaluates to `true`, and a default route that executes when none of the expressions in the existing routes are `true`. Add more routes when you need to evaluate more than one condition and then execute different operations depending on which condition is met. ### Add Routes by Dragging Components in Studio From **Mule Palette** in Anypoint Studio, click any component and drag it into the Choice router, where you see a vertical black line: ![add+route+option](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-choice-add-route.png) ### Add Routes by Editing the XML You can also add additional route options to a Choice router by modifying the XML configuration file: 1. In Studio, right-click the Choice router and select **Go to XML…​**. 2. Inside the `` element, add a `` element: ```xml ``` After adding a new `` element, the new route option shows in the Message Flow view: ![new-route-option](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-choice-new-route.png) ## Example Project You can use Anypoint Studio to download the example project _Content-Based Routing_ from Anypoint Exchange. This project presents a working example of a flow that uses the Choice router. ![choice-router-example](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-choice-example.png) Figure 2. Flow with a Choice router with three options, one being the default option To download and open this example project: 1. Click the Exchange icon (![3%](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-exchange-icon.png)) in Anypoint Studio. 2. In the left panel, click **All assets**. 3. In the window that opens, log in to Anypoint Exchange and search for the example project Content-Based Routing. 4. Click the Open icon (![6%](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-open-exchange-icon.png)). ### Behavior of the Example Project When you run the project as a Mule application, the application performs the following actions: 1. Listens for messages. 2. Passes messages to a Set Variable component that sets the variable `language` to the language that is passed in the message by the parameter `language`. 3. Uses a Choice router to find out whether each message contains a `language` attribute. The presence and value of this attribute determine how the Choice router routes the message: - If the value is `French`, the router routes the message to a Set Payload component that is named _Reply in French_. This latter component returns the message `Bonjour!` to the requester. - If the value is `Spanish`, the router routes the message to a Set Payload component that is named _Reply in Spanish_. This latter component returns the message `Hola!` to the requester. - If the message contains no `language` attribute, the router routes the message to the default path, which is a subflow that: 4. Logs the message "No language specified. Using English as a default." to the console 5. Sets the value of `language` to `English`. 6. Returns the message `Hello!`. The example project demonstrates that, when you are planning to route messages in a flow by using a Choice router, there are four aspects to planning that you need to consider: - The content that the Choice router evaluates to determine how it routes messages - The number of routes - The default routing option - The processing that the flow performs for each routing option ## Example XML Following is the XML code for the Choice router example: ```xml ``` ## Choice Router XML Reference A Choice flow control component contains these elements: - A single root element `` - A `` child element for each routing option, each with an expression to match - Optionally, an `` child element of Choice that handles all cases where none of the expressions on the `` elements evaluate to `true` - Components that are conditionally executed under each of the choices are defined as child elements of the `when` and `otherwise` elements ### Properties of
PropertyDescription

Business Events

For activating the Business Events feature:

<choice doc:name="Choice" tracking:enable-default-events="true" >
### Properties of
PropertyDescription

Expression (expression)

Expression in DataWeave language to evaluate input.
If the expression evaluates to true, this routing option is used:

<when expression="#[vars.language == 'Spanish']" >
## See Also - [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.3/about-flows) - [Extract Data](https://docs.mulesoft.com/dataweave/2.3/dataweave-cookbook-extract-data) - [DataWeave Scripts](https://docs.mulesoft.com/dataweave/2.3/dataweave-language-introduction) - [Business Events](https://docs.mulesoft.com/mule-runtime/4.3/business-events) --- product: Mule Runtime version: 4.4 --- # Choice Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Choice router dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. Only one of the routes in the Choice router executes, meaning that the first expression that evaluates to `true` triggers that route’s execution and the others are not checked. If none of the expressions are `true`, then the default route executes. ![Choice Router Schematic](/mulesoft/current/en-us/mule-runtime/4.4/_images/component-choice-schematic.png) Figure 1. Schematic diagram of a Choice router with three options, one being the default option ## Configuration To configure the Choice router, specify one or more conditions to evaluate, and the message processors that execute when any condition evaluates to `true`. Additionally, configure a default route that executes when none of the defined conditions are `true`. ### Anypoint Studio Configuration To configure the Choice router in Studio, follow these steps: ![Choice configuration Studio](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-choice-configuration-studio.png) 1. Drag the **Choice** component to any point of the flow. 2. Click **When**, inside the Choice router, and configure the **Expression** value in the properties window to specify the condition to evaluate. 3. Drag message processors inside **When** to specify the processors to execute when the condition is met. 4. Drag message processors inside **Default** to specify the processors to execute when none of the defined conditions are met. ### XML Configuration Following is the basic XML structure for a Choice router: ```xml (1) (2) (3) ```
1The expression attribute has the condition to evaluate.
2Add any number of message processors to execute if expression evaluates to true.
3Add any number of message processors to execute if none of the conditions evaluates to true.
## Adding Routes to the Choice Router By default, the Choice router has one route option that executes when the configured DataWeave expression evaluates to `true`, and a default route that executes when none of the expressions in the existing routes are `true`. Add more routes when you need to evaluate more than one condition and then execute different operations depending on which condition is met. ### Add Routes by Dragging Components in Studio From **Mule Palette** in Anypoint Studio, click any component and drag it into the Choice router, where you see a vertical black line: ![add+route+option](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-choice-add-route.png) ### Add Routes by Editing the XML You can also add additional route options to a Choice router by modifying the XML configuration file: 1. In Studio, right-click the Choice router and select **Go to XML…​**. 2. Inside the `` element, add a `` element: ```xml ``` After adding a new `` element, the new route option shows in the Message Flow view: ![new-route-option](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-choice-new-route.png) ## Example Project You can use Anypoint Studio to download the example project _Content-Based Routing_ from Anypoint Exchange. This project presents a working example of a flow that uses the Choice router. ![choice-router-example](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-choice-example.png) Figure 2. Flow with a Choice router with three options, one being the default option To download and open this example project: 1. Click the Exchange icon (![3%](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-exchange-icon.png)) in Anypoint Studio. 2. In the left panel, click **All assets**. 3. In the window that opens, log in to Anypoint Exchange and search for the example project Content-Based Routing. 4. Click the Open icon (![6%](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-open-exchange-icon.png)). ### Behavior of the Example Project When you run the project as a Mule application, the application performs the following actions: 1. Listens for messages. 2. Passes messages to a Set Variable component that sets the variable `language` to the language that is passed in the message by the parameter `language`. 3. Uses a Choice router to find out whether each message contains a `language` attribute. The presence and value of this attribute determine how the Choice router routes the message: - If the value is `French`, the router routes the message to a Set Payload component that is named _Reply in French_. This latter component returns the message `Bonjour!` to the requester. - If the value is `Spanish`, the router routes the message to a Set Payload component that is named _Reply in Spanish_. This latter component returns the message `Hola!` to the requester. - If the message contains no `language` attribute, the router routes the message to the default path, which is a subflow that: 4. Logs the message "No language specified. Using English as a default." to the console 5. Sets the value of `language` to `English`. 6. Returns the message `Hello!`. The example project demonstrates that, when you are planning to route messages in a flow by using a Choice router, there are four aspects to planning that you need to consider: - The content that the Choice router evaluates to determine how it routes messages - The number of routes - The default routing option - The processing that the flow performs for each routing option ## Example XML Following is the XML code for the Choice router example: ```xml ``` ## Choice Router XML Reference A Choice flow control component contains these elements: - A single root element `` - A `` child element for each routing option, each with an expression to match - Optionally, an `` child element of Choice that handles all cases where none of the expressions on the `` elements evaluate to `true` - Components that are conditionally executed under each of the choices are defined as child elements of the `when` and `otherwise` elements ### Properties of
PropertyDescription

Business Events

For activating the Business Events feature:

<choice doc:name="Choice" tracking:enable-default-events="true" >
### Properties of
PropertyDescription

Expression (expression)

Expression in DataWeave language to evaluate input.
If the expression evaluates to true, this routing option is used:

<when expression="#[vars.language == 'Spanish']" >
## See Also - [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.4/about-flows) - [Extract Data](https://docs.mulesoft.com/dataweave/latest/dataweave-cookbook-extract-data) - [DataWeave Scripts](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction) - [Business Events](https://docs.mulesoft.com/mule-runtime/4.4/business-events) --- product: Mule Runtime version: 4.6 --- # Choice Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Choice router dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. Only one of the routes in the Choice router executes, meaning that the first expression that evaluates to `true` triggers that route’s execution and the others are not checked. If none of the expressions are `true`, then the default route executes. ![Choice Router Schematic](/mulesoft/current/en-us/mule-runtime/4.6/_images/component-choice-schematic.png) Figure 1. Schematic diagram of a Choice router with three options, one being the default option ## Configuration To configure the Choice router, specify one or more conditions to evaluate, and the message processors that execute when any condition evaluates to `true`. Additionally, configure a default route that executes when none of the defined conditions are `true`. ### Anypoint Studio Configuration To configure the Choice router in Studio, follow these steps: ![Choice configuration Studio](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-choice-configuration-studio.png) 1. Drag the **Choice** component to any point of the flow. 2. Click **When**, inside the Choice router, and configure the **Expression** value in the properties window to specify the condition to evaluate. 3. Drag message processors inside **When** to specify the processors to execute when the condition is met. 4. Drag message processors inside **Default** to specify the processors to execute when none of the defined conditions are met. ### XML Configuration Following is the basic XML structure for a Choice router: ```xml (1) (2) (3) ```
1The expression attribute has the condition to evaluate.
2Add any number of message processors to execute if expression evaluates to true.
3Add any number of message processors to execute if none of the conditions evaluates to true.
## Adding Routes to the Choice Router By default, the Choice router has one route option that executes when the configured DataWeave expression evaluates to `true`, and a default route that executes when none of the expressions in the existing routes are `true`. Add more routes when you need to evaluate more than one condition and then execute different operations depending on which condition is met. ### Add Routes by Dragging Components in Studio From **Mule Palette** in Anypoint Studio, click any component and drag it into the Choice router, where you see a vertical black line: ![add+route+option](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-choice-add-route.png) ### Add Routes by Editing the XML You can also add additional route options to a Choice router by modifying the XML configuration file: 1. In Studio, right-click the Choice router and select **Go to XML…​**. 2. Inside the `` element, add a `` element: ```xml ``` After adding a new `` element, the new route option shows in the Message Flow view: ![new-route-option](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-choice-new-route.png) ## Example Project You can use Anypoint Studio to download the example project _Content-Based Routing_ from Anypoint Exchange. This project presents a working example of a flow that uses the Choice router. ![choice-router-example](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-choice-example.png) Figure 2. Flow with a Choice router with three options, one being the default option To download and open this example project: 1. Click the Exchange icon (![3%](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-exchange-icon.png)) in Anypoint Studio. 2. In the left panel, click **All assets**. 3. In the window that opens, log in to Anypoint Exchange and search for the example project Content-Based Routing. 4. Click the Open icon (![6%](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-open-exchange-icon.png)). ### Behavior of the Example Project When you run the project as a Mule application, the application performs the following actions: 1. Listens for messages. 2. Passes messages to a Set Variable component that sets the variable `language` to the language that is passed in the message by the parameter `language`. 3. Uses a Choice router to find out whether each message contains a `language` attribute. The presence and value of this attribute determine how the Choice router routes the message: - If the value is `French`, the router routes the message to a Set Payload component that is named _Reply in French_. This latter component returns the message `Bonjour!` to the requester. - If the value is `Spanish`, the router routes the message to a Set Payload component that is named _Reply in Spanish_. This latter component returns the message `Hola!` to the requester. - If the message contains no `language` attribute, the router routes the message to the default path, which is a subflow that: 4. Logs the message "No language specified. Using English as a default." to the console 5. Sets the value of `language` to `English`. 6. Returns the message `Hello!`. The example project demonstrates that, when you are planning to route messages in a flow by using a Choice router, there are four aspects to planning that you need to consider: - The content that the Choice router evaluates to determine how it routes messages - The number of routes - The default routing option - The processing that the flow performs for each routing option ## Example XML Following is the XML code for the Choice router example: ```xml ``` ## Choice Router XML Reference A Choice flow control component contains these elements: - A single root element `` - A `` child element for each routing option, each with an expression to match - Optionally, an `` child element of Choice that handles all cases where none of the expressions on the `` elements evaluate to `true` - Components that are conditionally executed under each of the choices are defined as child elements of the `when` and `otherwise` elements ### Properties of
PropertyDescription

Business Events

For activating the Business Events feature:

<choice doc:name="Choice" tracking:enable-default-events="true" >
### Properties of
PropertyDescription

Expression (expression)

Expression in DataWeave language to evaluate input.
If the expression evaluates to true, this routing option is used:

<when expression="#[vars.language == 'Spanish']" >
## See Also - [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.6/about-flows) - [Extract Data](https://docs.mulesoft.com/dataweave/latest/dataweave-cookbook-extract-data) - [DataWeave Scripts](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction) - [Business Events](https://docs.mulesoft.com/mule-runtime/4.6/business-events) --- product: Mule Runtime version: 4.9 --- # Choice Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Choice router dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. Only one of the routes in the Choice router executes, meaning that the first expression that evaluates to `true` triggers that route’s execution and the others are not checked. If none of the expressions are `true`, then the default route executes. ![A choice router schematic showing multiple options, one being the default](/mulesoft/current/en-us/mule-runtime/4.9/_images/component-choice-schematic.png) Figure 1. Schematic diagram of a Choice router with three options, one being the default option ## Configuration To configure the Choice router, specify one or more conditions to evaluate, and the message processors that execute when any condition evaluates to `true`. Additionally, configure a default route that executes when none of the defined conditions are `true`. ### Anypoint Studio Configuration To configure the Choice router in Studio, follow these steps: ![A flow showing the configuration of a Choice component in Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-choice-configuration-studio.png) 1. Drag the **Choice** component to any point of the flow. 2. Click **When**, inside the Choice router, and configure the **Expression** value in the properties window to specify the condition to evaluate. 3. Drag message processors inside **When** to specify the processors to execute when the condition is met. 4. Drag message processors inside **Default** to specify the processors to execute when none of the defined conditions are met. ### XML Configuration Following is the basic XML structure for a Choice router: ```xml (1) (2) (3) ```
1The expression attribute has the condition to evaluate.
2Add any number of message processors to execute if expression evaluates to true.
3Add any number of message processors to execute if none of the conditions evaluates to true.
## Adding Routes to the Choice Router By default, the Choice router has one route option that executes when the configured DataWeave expression evaluates to `true`, and a default route that executes when none of the expressions in the existing routes are `true`. Add more routes when you need to evaluate more than one condition and then execute different operations depending on which condition is met. ### Add Routes by Dragging Components in Studio From **Mule Palette** in Anypoint Studio, click any component and drag it into the Choice router, where you see a vertical black line: ![A flow showing a content-based routing configuration](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-choice-add-route.png) ### Add Routes by Editing the XML You can also add additional route options to a Choice router by modifying the XML configuration file: 1. In Studio, right-click the Choice router and select **Go to XML…​**. 2. Inside the `` element, add a `` element: ```xml ``` After adding a new `` element, the new route option shows in the Message Flow view: ![A flow for a new content-based routing path](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-choice-new-route.png) ## Example Project You can use Anypoint Studio to download the example project _Content-Based Routing_ from Anypoint Exchange. This project presents a working example of a flow that uses the Choice router. ![A flow for content-based routing including payload settings and error handling](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-choice-example.png) Figure 2. Flow with a Choice router with three options, one being the default option To download and open this example project: 1. Click the Exchange icon (![](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-exchange-icon.png)) in Anypoint Studio. 2. In the left panel, click **All assets**. 3. In the window that opens, log in to Anypoint Exchange and search for the example project Content-Based Routing. 4. Click the Open icon (![](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-open-exchange-icon.png)). ### Behavior of the Example Project When you run the project as a Mule application, the application performs the following actions: 1. Listens for messages. 2. Passes messages to a Set Variable component that sets the variable `language` to the language that is passed in the message by the parameter `language`. 3. Uses a Choice router to find out whether each message contains a `language` attribute. The presence and value of this attribute determine how the Choice router routes the message: - If the value is `French`, the router routes the message to a Set Payload component that is named _Reply in French_. This latter component returns the message `Bonjour!` to the requester. - If the value is `Spanish`, the router routes the message to a Set Payload component that is named _Reply in Spanish_. This latter component returns the message `Hola!` to the requester. - If the message contains no `language` attribute, the router routes the message to the default path, which is a subflow that: 4. Logs the message "No language specified. Using English as a default." to the console 5. Sets the value of `language` to `English`. 6. Returns the message `Hello!`. The example project demonstrates that, when you are planning to route messages in a flow by using a Choice router, there are four aspects to planning that you need to consider: - The content that the Choice router evaluates to determine how it routes messages - The number of routes - The default routing option - The processing that the flow performs for each routing option ## Example XML Following is the XML code for the Choice router example: ```xml ``` ## Choice Router XML Reference A Choice flow control component contains these elements: - A single root element `` - A `` child element for each routing option, each with an expression to match - Optionally, an `` child element of Choice that handles all cases where none of the expressions on the `` elements evaluate to `true` - Components that are conditionally executed under each of the choices are defined as child elements of the `when` and `otherwise` elements ### Properties of
PropertyDescription

Business Events

For activating the Business Events feature:

<choice doc:name="Choice" tracking:enable-default-events="true" >
### Properties of
PropertyDescription

Expression (expression)

Expression in DataWeave language to evaluate input.
If the expression evaluates to true, this routing option is used:

<when expression="#[vars.language == 'Spanish']" >
## See Also - [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.9/about-flows) - [Extract Data](https://docs.mulesoft.com/dataweave/latest/dataweave-cookbook-extract-data) - [DataWeave Scripts](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction) - [Business Events](https://docs.mulesoft.com/mule-runtime/4.9/business-events) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Choice Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Choice router dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. Only one of the routes in the Choice router executes, meaning that the first expression that evaluates to `true` triggers that route’s execution and the others are not checked. If none of the expressions are `true`, then the default route executes. ![A choice router schematic showing multiple options, one being the default](/mulesoft/current/en-us/mule-runtime/latest/_images/component-choice-schematic.png) Figure 1. Schematic diagram of a Choice router with three options, one being the default option ## Configuration To configure the Choice router, specify one or more conditions to evaluate, and the message processors that execute when any condition evaluates to `true`. Additionally, configure a default route that executes when none of the defined conditions are `true`. ### Anypoint Studio Configuration To configure the Choice router in Studio, follow these steps: ![A flow showing the configuration of a Choice component in Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-choice-configuration-studio.png) 1. Drag the **Choice** component to any point of the flow. 2. Click **When**, inside the Choice router, and configure the **Expression** value in the properties window to specify the condition to evaluate. 3. Drag message processors inside **When** to specify the processors to execute when the condition is met. 4. Drag message processors inside **Default** to specify the processors to execute when none of the defined conditions are met. ### XML Configuration Following is the basic XML structure for a Choice router: ```xml (1) (2) (3) ```
1The expression attribute has the condition to evaluate.
2Add any number of message processors to execute if expression evaluates to true.
3Add any number of message processors to execute if none of the conditions evaluates to true.
## Adding Routes to the Choice Router By default, the Choice router has one route option that executes when the configured DataWeave expression evaluates to `true`, and a default route that executes when none of the expressions in the existing routes are `true`. Add more routes when you need to evaluate more than one condition and then execute different operations depending on which condition is met. ### Add Routes by Dragging Components in Studio From **Mule Palette** in Anypoint Studio, click any component and drag it into the Choice router, where you see a vertical black line: ![A flow showing a content-based routing configuration](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-choice-add-route.png) ### Add Routes by Editing the XML You can also add additional route options to a Choice router by modifying the XML configuration file: 1. In Studio, right-click the Choice router and select **Go to XML…​**. 2. Inside the `` element, add a `` element: ```xml ``` After adding a new `` element, the new route option shows in the Message Flow view: ![A flow for a new content-based routing path](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-choice-new-route.png) ## Example Project You can use Anypoint Studio to download the example project _Content-Based Routing_ from Anypoint Exchange. This project presents a working example of a flow that uses the Choice router. ![A flow for content-based routing including payload settings and error handling](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-choice-example.png) Figure 2. Flow with a Choice router with three options, one being the default option To download and open this example project: 1. Click the Exchange icon (![](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-exchange-icon.png)) in Anypoint Studio. 2. In the left panel, click **All assets**. 3. In the window that opens, log in to Anypoint Exchange and search for the example project Content-Based Routing. 4. Click the Open icon (![](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-open-exchange-icon.png)). ### Behavior of the Example Project When you run the project as a Mule application, the application performs the following actions: 1. Listens for messages. 2. Passes messages to a Set Variable component that sets the variable `language` to the language that is passed in the message by the parameter `language`. 3. Uses a Choice router to find out whether each message contains a `language` attribute. The presence and value of this attribute determine how the Choice router routes the message: - If the value is `French`, the router routes the message to a Set Payload component that is named _Reply in French_. This latter component returns the message `Bonjour!` to the requester. - If the value is `Spanish`, the router routes the message to a Set Payload component that is named _Reply in Spanish_. This latter component returns the message `Hola!` to the requester. - If the message contains no `language` attribute, the router routes the message to the default path, which is a subflow that: 4. Logs the message "No language specified. Using English as a default." to the console 5. Sets the value of `language` to `English`. 6. Returns the message `Hello!`. The example project demonstrates that, when you are planning to route messages in a flow by using a Choice router, there are four aspects to planning that you need to consider: - The content that the Choice router evaluates to determine how it routes messages - The number of routes - The default routing option - The processing that the flow performs for each routing option ## Example XML Following is the XML code for the Choice router example: ```xml ``` ## Choice Router XML Reference A Choice flow control component contains these elements: - A single root element `` - A `` child element for each routing option, each with an expression to match - Optionally, an `` child element of Choice that handles all cases where none of the expressions on the `` elements evaluate to `true` - Components that are conditionally executed under each of the choices are defined as child elements of the `when` and `otherwise` elements ### Properties of
PropertyDescription

Business Events

For activating the Business Events feature:

<choice doc:name="Choice" tracking:enable-default-events="true" >
### Properties of
PropertyDescription

Expression (expression)

Expression in DataWeave language to evaluate input.
If the expression evaluates to true, this routing option is used:

<when expression="#[vars.language == 'Spanish']" >
## See Also - [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/latest/about-flows) - [Extract Data](https://docs.mulesoft.com/dataweave/latest/dataweave-cookbook-extract-data) - [DataWeave Scripts](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction) - [Business Events](https://docs.mulesoft.com/mule-runtime/latest/business-events) --- product: Mule Runtime version: 4.11 --- # Class-loading Isolation > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine is developed using Java and many other third-party libraries. Mule apps can also contain Java libraries, particularly modules that extend Mule to provide integration functionality, such as Anypoint Connector for HTTP and the XML module. These extension modules can also contain Java (JAR) libraries. The default class-loading mechanism of the JVM makes it possible to have conflicting versions of the same JAR files. In Mule, each artifact (the runtime, the Mule apps, and Mule extensions) is developed and released independently, but the JARs for these artifacts are together in the same location. For example, a Mule app might use Apache Commons Collections 2.1. If an extension you use requires Apache Commons Collections 3.1, the app might not work as expected because Commons Collections 2.1 and Commons Collections 3.1 have conflicting resources. ## API Definition Mule runtime engine and the artifacts (apps, domains, policies, and extensions) need to have a clear API definition that specifies a contract for each artifact and limits the exposure of the artifact content to other artifacts. A clear API for each artifact provides a way to limit the scope of classes and libraries, which in turn makes it possible to create class loaders that do not share everything. ### Mule 4 API Mule 4 provides a well-defined API that makes it easy for you to extend Mule and provides clarity on the proper extension points: - Core API: Mule message. - Extensions API: Modules, message processors, transforms, and other elements to extend Mule Runtime 4. - Tooling API: All DataSense metadata and propagation is now part of Mule Runtime 4. This API is bundled with the Runtime Manager agent. ### Artifact API When you create an artifact (app, domain, policy, or extension), you need to declare the public API of that module. #### How To Define the Public API See [Export Resources](https://docs.mulesoft.com/mule-runtime/4.11/how-to-export-resources) to export a resource from an artifact. #### Considerations - Resources and classes that are not exported are not visible from other artifacts. - Expose the minimum required set of packages and resources from your artifact. - Do not export third-party libraries unless required. - Never expose common third-party libraries like Guava, Apache common-collections, and so on. Doing so will cause clashes with other artifacts. - Ideally, expose only classes from your artifact (or the JDK). ### Semver Mule 4 follows [Semantic Versioning 2.0.0](https://semver.org/) for all the provided APIs. ### API restrictions All public APIs might have restrictions. These restrictions limit how you can use the API. See [API annotations module](https://github.com/mulesoft/api-annotations) for more details. > [!IMPORTANT] You need to take into account the API restrictions defined for the API you are > consuming, as they ensure greater flexibility among API changes that can occur between different > versions. ## Class-loading Isolation Mechanism Once APIs are clearly defined, you can prevent access to internal classes of the artifact and only make the public API accessible from outside. To protect the APIs, Mule 4 uses a custom class-loading mechanism. Consider the following extension file structure: com/example/extension/api/MyClass.class com/example/extension/internal/Util.class transformations/customer-to-user.dwl license.txt META-INF/mule-artifact/mule-artifact.json And the following `mule-artifact.json` descriptor file for the extension: ```json { "name": "my-test-extension", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": ["transformations/customer-to-user.dwl"], "exportedPackages": ["com/example/extension/api"] } } } ``` The following diagram shows how resources exported by `mule-artifact.json` are applied within an app: ![A class-loading diagram for a Mule app](/mulesoft/current/en-us/mule-runtime/4.11/_images/simple-classloading-diagram.png) Artifact Class Loader A regular Java class loader pointing to the JAR files included in the extension. This class loader loads all files and classes of the extension. Artifact Filtering Class Loader A wrapper created over the Artifact class loader, which enforces access restrictions to the extension code for foreign artifacts (the app or other plugins). It uses the content of the `mule-artifact.json` descriptor to determine what is public. Extension Code The Mule extension code. Uses the Artifact class loader (which does not have any restriction), and it is only able to locate resources of the plugin itself. Application Code The Mule app code. It uses the Artifact Filtering class loader of the extension to prevent the app from accessing restricted code or resources. ## Adding Dependencies to Connectors When the connectors in your application need access to a dependency in your project, configure the dependency to be visible by the connector’s class loader. There are two different ways to do this: - Configure application dependencies as [shared libraries](#shared-libraries). - Configure [additional plugin dependencies](#additional-plugin-dependencies) for the connector. ### Shared Libraries All dependencies (JAR files, for example) declared in the application’s `pom.xml` file are visible to the application’s class loader but not visible to the class loader of each connector used in the application. The Mule runtime engine class-loading mechanism isolates each connector to prevent it from accessing classes from other connectors. If a connector’s class loader needs access to an application dependency, declare this dependency as a shared library. Consider an application that uses Anypoint Connector for Java, and the connector needs to use a class that is part of a JAR dependency declared in the application’s `pom.xml` file. However, this is not possible, because the connector’s class loader is not able to find that class. To make this class visible to the connector, you must declare the dependency that contains the class as a shared library in the Mule Maven plugin configuration of your application’s `pom.xml` file. If you use Anypoint Studio to configure a connector that uses external libraries, the dependencies are automatically added as shared libraries. For example, if you add Anypoint Connector for Database to your application and then configure the connection driver using Anypoint Studio, the driver is automatically added as a shared library in your project’s `pom.xml` file. See [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.11/mmp-concept#configure-shared-libraries) for configuration instructions. > [!NOTE] Shared libraries are visible to all connectors in the application. Configuring shared > libraries can cause issues if the shared library has different versions of the same classes in > other connectors or their dependencies. ### Additional Plugin Dependencies Instead of configuring shared libraries to make application dependencies visible to all connectors in the application, you can configure additional plugin dependencies to enrich a specific connector’s classpath. This configuration enables you to effectively add new dependencies to a connector, as if the dependencies were declared in the connector’s `pom.xml` file. Configuring additional plugin dependencies ensures that the dependencies are available only for the configured connector, and you don’t need to declare them as application dependencies. When you configure additional plugin dependencies, you must specify the dependency version. See [Configure Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/4.11/mmp-concept#configure-plugin-dependencies) for configuration instructions. ## See Also - [Mule SDK - About Class-loading Isolation](https://docs.mulesoft.com/mule-sdk/latest/isolation) --- product: Mule Runtime version: 4.12 --- # Class-loading Isolation > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine is developed using Java and many other third-party libraries. Mule apps can also contain Java libraries, particularly modules that extend Mule to provide integration functionality, such as Anypoint Connector for HTTP and the XML module. These extension modules can also contain Java (JAR) libraries. The default class-loading mechanism of the JVM makes it possible to have conflicting versions of the same JAR files. In Mule, each artifact (the runtime, the Mule apps, and Mule extensions) is developed and released independently, but the JARs for these artifacts are together in the same location. For example, a Mule app might use Apache Commons Collections 2.1. If an extension you use requires Apache Commons Collections 3.1, the app might not work as expected because Commons Collections 2.1 and Commons Collections 3.1 have conflicting resources. ## API Definition Mule runtime engine and the artifacts (apps, domains, policies, and extensions) need to have a clear API definition that specifies a contract for each artifact and limits the exposure of the artifact content to other artifacts. A clear API for each artifact provides a way to limit the scope of classes and libraries, which in turn makes it possible to create class loaders that do not share everything. ### Mule 4 API Mule 4 provides a well-defined API that makes it easy for you to extend Mule and provides clarity on the proper extension points: - Core API: Mule message. - Extensions API: Modules, message processors, transforms, and other elements to extend Mule Runtime 4. - Tooling API: All DataSense metadata and propagation is now part of Mule Runtime 4. This API is bundled with the Runtime Manager agent. ### Artifact API When you create an artifact (app, domain, policy, or extension), you need to declare the public API of that module. #### How To Define the Public API See [Export Resources](https://docs.mulesoft.com/mule-runtime/4.12/how-to-export-resources) to export a resource from an artifact. #### Considerations - Resources and classes that are not exported are not visible from other artifacts. - Expose the minimum required set of packages and resources from your artifact. - Do not export third-party libraries unless required. - Never expose common third-party libraries like Guava, Apache common-collections, and so on. Doing so will cause clashes with other artifacts. - Ideally, expose only classes from your artifact (or the JDK). ### Semver Mule 4 follows [Semantic Versioning 2.0.0](https://semver.org/) for all the provided APIs. ### API restrictions All public APIs might have restrictions. These restrictions limit how you can use the API. See [API annotations module](https://github.com/mulesoft/api-annotations) for more details. > [!IMPORTANT] You need to take into account the API restrictions defined for the API you are > consuming, as they ensure greater flexibility among API changes that can occur between different > versions. ## Class-loading Isolation Mechanism Once APIs are clearly defined, you can prevent access to internal classes of the artifact and only make the public API accessible from outside. To protect the APIs, Mule 4 uses a custom class-loading mechanism. Consider the following extension file structure: com/example/extension/api/MyClass.class com/example/extension/internal/Util.class transformations/customer-to-user.dwl license.txt META-INF/mule-artifact/mule-artifact.json And the following `mule-artifact.json` descriptor file for the extension: ```json { "name": "my-test-extension", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": ["transformations/customer-to-user.dwl"], "exportedPackages": ["com/example/extension/api"] } } } ``` The following diagram shows how resources exported by `mule-artifact.json` are applied within an app: ![A class-loading diagram for a Mule app](/mulesoft/current/en-us/mule-runtime/4.12/_images/simple-classloading-diagram.png) Artifact Class Loader A regular Java class loader pointing to the JAR files included in the extension. This class loader loads all files and classes of the extension. Artifact Filtering Class Loader A wrapper created over the Artifact class loader, which enforces access restrictions to the extension code for foreign artifacts (the app or other plugins). It uses the content of the `mule-artifact.json` descriptor to determine what is public. Extension Code The Mule extension code. Uses the Artifact class loader (which does not have any restriction), and it is only able to locate resources of the plugin itself. Application Code The Mule app code. It uses the Artifact Filtering class loader of the extension to prevent the app from accessing restricted code or resources. ## Adding Dependencies to Connectors When the connectors in your application need access to a dependency in your project, configure the dependency to be visible by the connector’s class loader. There are two different ways to do this: - Configure application dependencies as [shared libraries](#shared-libraries). - Configure [additional plugin dependencies](#additional-plugin-dependencies) for the connector. ### Shared Libraries All dependencies (JAR files, for example) declared in the application’s `pom.xml` file are visible to the application’s class loader but not visible to the class loader of each connector used in the application. The Mule runtime engine class-loading mechanism isolates each connector to prevent it from accessing classes from other connectors. If a connector’s class loader needs access to an application dependency, declare this dependency as a shared library. Consider an application that uses Anypoint Connector for Java, and the connector needs to use a class that is part of a JAR dependency declared in the application’s `pom.xml` file. However, this is not possible, because the connector’s class loader is not able to find that class. To make this class visible to the connector, you must declare the dependency that contains the class as a shared library in the Mule Maven plugin configuration of your application’s `pom.xml` file. If you use Anypoint Studio to configure a connector that uses external libraries, the dependencies are automatically added as shared libraries. For example, if you add Anypoint Connector for Database to your application and then configure the connection driver using Anypoint Studio, the driver is automatically added as a shared library in your project’s `pom.xml` file. See [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.12/mmp-concept#configure-shared-libraries) for configuration instructions. > [!NOTE] Shared libraries are visible to all connectors in the application. Configuring shared > libraries can cause issues if the shared library has different versions of the same classes in > other connectors or their dependencies. ### Additional Plugin Dependencies Instead of configuring shared libraries to make application dependencies visible to all connectors in the application, you can configure additional plugin dependencies to enrich a specific connector’s classpath. This configuration enables you to effectively add new dependencies to a connector, as if the dependencies were declared in the connector’s `pom.xml` file. Configuring additional plugin dependencies ensures that the dependencies are available only for the configured connector, and you don’t need to declare them as application dependencies. When you configure additional plugin dependencies, you must specify the dependency version. See [Configure Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/4.12/mmp-concept#configure-plugin-dependencies) for configuration instructions. ## See Also - [Mule SDK - About Class-loading Isolation](https://docs.mulesoft.com/mule-sdk/latest/isolation) --- product: Mule Runtime version: 4.3 --- # Class-loading Isolation > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine is developed using Java and many other third-party libraries. Mule apps can also contain Java libraries, particularly modules that extend Mule to provide integration functionality, such as Anypoint Connector for HTTP and the XML module. These extension modules can also contain Java (JAR) libraries. The default class-loading mechanism of the JVM makes it possible to have conflicting versions of the same JAR files. In Mule, each artifact (the runtime, the Mule apps, and Mule extensions) is developed and released independently, but the JARs for these artifacts are together in the same location. For example, a Mule app might use Apache Commons Collections 2.1. If an extension you use requires Apache Commons Collections 3.1, the app might not work as expected because Commons Collections 2.1 and Commons Collections 3.1 have conflicting resources. - Mule 3 Solution To solve the problem of clashes between different apps, Mule 3 relied on hierarchical organization of class loaders. Though Mule apps can see their extensions, the libraries bundled within them, and their runtime libraries, Mule apps cannot access other app libraries. Other potential conflicts remained in Mule 3, such as clashes between libraries from different extensions, clashes between extension and app libraries, and clashes between app and runtime libraries. - Mule 4 Solution In Mule 4, the class-loading mechanism addresses all the problems depicted above for Mule 3. ## API Definition Mule runtime engine and the artifacts (apps, domains, policies, and extensions) need to have a clear API definition that specifies a contract for each artifact and limits the exposure of the artifact content to other artifacts. A clear API for each artifact provides a way to limit the scope of classes and libraries, which in turn makes it possible to create class loaders that do not share everything. ### Mule 4 API Mule 3 exposes all the classes that are bundled within its libraries. This exposure caused problems when upgrading from one Mule version to another because changes in the runtime could potentially affect any of your custom Java classes. Mule 4 provides a well-defined API that makes it easier for you to extend Mule and provides clarity on the proper extension points: - Core API: Mule message. - Extensions API: Modules, message processors, transforms, and other elements to extend Mule Runtime 4. - Tooling API: All DataSense metadata and propagation is now part of Mule Runtime 4. This API is bundled with the Runtime Manager agent. ### Artifact API When you create an artifact (app, domain, policy, or extension), you need to declare the public API of that module. #### How To Define the Public API See [Export Resources](https://docs.mulesoft.com/mule-runtime/4.3/how-to-export-resources) to export a resource from an artifact. #### Considerations - Resources and classes that are not exported are not visible from other artifacts. - Expose the minimum required set of packages and resources from your artifact. - Do not export third-party libraries unless required. - Never expose common third-party libraries like Guava, Apache common-collections, and so on. Doing so will cause clashes with other artifacts. - Ideally, expose only classes from your artifact (or the JDK). ### Semver Mule 4 follows [Semantic Versioning 2.0.0](https://semver.org/) for all the provided APIs. ### API restrictions All public APIs might have restrictions. These restrictions limit how you can use the API. See [API annotations module](https://github.com/mulesoft/api-annotations) for more details. > [!IMPORTANT] You need to take into account the API restrictions defined for the API you are > consuming, as they ensure greater flexibility among API changes that can occur between different > versions. ## Class-loading Isolation Mechanism Once APIs are clearly defined, you can prevent access to internal classes of the artifact and only make the public API accessible from outside. To protect the APIs, Mule 4 uses a custom class-loading mechanism. Consider the following extension file structure: com/example/extension/api/MyClass.class com/example/extension/internal/Util.class transformations/customer-to-user.dwl license.txt META-INF/mule-artifact/mule-artifact.json And the following `mule-artifact.json` descriptor file for the extension: ```json { "name": "my-test-extension", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": ["transformations/customer-to-user.dwl"], "exportedPackages": ["com/example/extension/api"] } } } ``` The following diagram shows how resources exported by `mule-artifact.json` are applied within an app: ![Simple class-loading diagram](/mulesoft/current/en-us/mule-runtime/4.3/_images/simple-classloading-diagram.png) Artifact Class Loader A regular Java class loader pointing to the JAR files included in the extension. This class loader loads all files and classes of the extension. Artifact Filtering Class Loader A wrapper created over the Artifact class loader, which enforces access restrictions to the extension code for foreign artifacts (the app or other plugins). It uses the content of the `mule-artifact.json` descriptor to determine what is public. Extension Code The Mule extension code. Uses the Artifact class loader (which does not have any restriction), and it is only able to locate resources of the plugin itself. Application Code The Mule app code. It uses the Artifact Filtering class loader of the extension to prevent the app from accessing restricted code or resources. ## Adding Dependencies to Connectors When the connectors in your application need access to a dependency in your project, configure the dependency to be visible by the connector’s class loader. There are two different ways to do this: - Configure application dependencies as [shared libraries](#shared-libraries). - Configure [additional plugin dependencies](#additional-plugin-dependencies) for the connector. ### Shared Libraries All dependencies (JAR files, for example) declared in the application’s `pom.xml` file are visible to the application’s class loader but not visible to the class loader of each connector used in the application. The Mule runtime engine class-loading mechanism isolates each connector to prevent it from accessing classes from other connectors. If a connector’s class loader needs access to an application dependency, declare this dependency as a shared library. Consider an application that uses Anypoint Connector for Java, and the connector needs to use a class that is part of a JAR dependency declared in the application’s `pom.xml` file. However, this is not possible, because the connector’s class loader is not able to find that class. To make this class visible to the connector, you must declare the dependency that contains the class as a shared library in the Mule Maven plugin configuration of your application’s `pom.xml` file. If you use Anypoint Studio to configure a connector that uses external libraries, the dependencies are automatically added as shared libraries. For example, if you add Anypoint Connector for Database to your application and then configure the connection driver using Anypoint Studio, the driver is automatically added as a shared library in your project’s `pom.xml` file. See [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.3/mmp-concept#configure-shared-libraries) for configuration instructions. > [!NOTE] Shared libraries are visible to all connectors in the application. Configuring shared > libraries can cause issues if the shared library has different versions of the same classes in > other connectors or their dependencies. ### Additional Plugin Dependencies Instead of configuring shared libraries to make application dependencies visible to all connectors in the application, you can configure additional plugin dependencies to enrich a specific connector’s classpath. This configuration enables you to effectively add new dependencies to a connector, as if the dependencies were declared in the connector’s `pom.xml` file. Configuring additional plugin dependencies ensures that the dependencies are available only for the configured connector, and you don’t need to declare them as application dependencies. When you configure additional plugin dependencies, you must specify the dependency version. See [Configure Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/4.3/mmp-concept#configure-plugin-dependencies) for configuration instructions. ## See Also - [Mule SDK - About Class-loading Isolation](https://docs.mulesoft.com/mule-sdk/latest/isolation) --- product: Mule Runtime version: 4.4 --- # Class-loading Isolation > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine is developed using Java and many other third-party libraries. Mule apps can also contain Java libraries, particularly modules that extend Mule to provide integration functionality, such as Anypoint Connector for HTTP and the XML module. These extension modules can also contain Java (JAR) libraries. The default class-loading mechanism of the JVM makes it possible to have conflicting versions of the same JAR files. In Mule, each artifact (the runtime, the Mule apps, and Mule extensions) is developed and released independently, but the JARs for these artifacts are together in the same location. For example, a Mule app might use Apache Commons Collections 2.1. If an extension you use requires Apache Commons Collections 3.1, the app might not work as expected because Commons Collections 2.1 and Commons Collections 3.1 have conflicting resources. - Mule 3 Solution To solve the problem of clashes between different apps, Mule 3 relied on hierarchical organization of class loaders. Though Mule apps can see their extensions, the libraries bundled within them, and their runtime libraries, Mule apps cannot access other app libraries. Other potential conflicts remained in Mule 3, such as clashes between libraries from different extensions, clashes between extension and app libraries, and clashes between app and runtime libraries. - Mule 4 Solution In Mule 4, the class-loading mechanism addresses all the problems depicted above for Mule 3. ## API Definition Mule runtime engine and the artifacts (apps, domains, policies, and extensions) need to have a clear API definition that specifies a contract for each artifact and limits the exposure of the artifact content to other artifacts. A clear API for each artifact provides a way to limit the scope of classes and libraries, which in turn makes it possible to create class loaders that do not share everything. ### Mule 4 API Mule 3 exposes all the classes that are bundled within its libraries. This exposure caused problems when upgrading from one Mule version to another because changes in the runtime could potentially affect any of your custom Java classes. Mule 4 provides a well-defined API that makes it easier for you to extend Mule and provides clarity on the proper extension points: - Core API: Mule message. - Extensions API: Modules, message processors, transforms, and other elements to extend Mule Runtime 4. - Tooling API: All DataSense metadata and propagation is now part of Mule Runtime 4. This API is bundled with the Runtime Manager agent. ### Artifact API When you create an artifact (app, domain, policy, or extension), you need to declare the public API of that module. #### How To Define the Public API See [Export Resources](https://docs.mulesoft.com/mule-runtime/4.4/how-to-export-resources) to export a resource from an artifact. #### Considerations - Resources and classes that are not exported are not visible from other artifacts. - Expose the minimum required set of packages and resources from your artifact. - Do not export third-party libraries unless required. - Never expose common third-party libraries like Guava, Apache common-collections, and so on. Doing so will cause clashes with other artifacts. - Ideally, expose only classes from your artifact (or the JDK). ### Semver Mule 4 follows [Semantic Versioning 2.0.0](https://semver.org/) for all the provided APIs. ### API restrictions All public APIs might have restrictions. These restrictions limit how you can use the API. See [API annotations module](https://github.com/mulesoft/api-annotations) for more details. > [!IMPORTANT] You need to take into account the API restrictions defined for the API you are > consuming, as they ensure greater flexibility among API changes that can occur between different > versions. ## Class-loading Isolation Mechanism Once APIs are clearly defined, you can prevent access to internal classes of the artifact and only make the public API accessible from outside. To protect the APIs, Mule 4 uses a custom class-loading mechanism. Consider the following extension file structure: com/example/extension/api/MyClass.class com/example/extension/internal/Util.class transformations/customer-to-user.dwl license.txt META-INF/mule-artifact/mule-artifact.json And the following `mule-artifact.json` descriptor file for the extension: ```json { "name": "my-test-extension", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": ["transformations/customer-to-user.dwl"], "exportedPackages": ["com/example/extension/api"] } } } ``` The following diagram shows how resources exported by `mule-artifact.json` are applied within an app: ![Simple class-loading diagram](/mulesoft/current/en-us/mule-runtime/4.4/_images/simple-classloading-diagram.png) Artifact Class Loader A regular Java class loader pointing to the JAR files included in the extension. This class loader loads all files and classes of the extension. Artifact Filtering Class Loader A wrapper created over the Artifact class loader, which enforces access restrictions to the extension code for foreign artifacts (the app or other plugins). It uses the content of the `mule-artifact.json` descriptor to determine what is public. Extension Code The Mule extension code. Uses the Artifact class loader (which does not have any restriction), and it is only able to locate resources of the plugin itself. Application Code The Mule app code. It uses the Artifact Filtering class loader of the extension to prevent the app from accessing restricted code or resources. ## Adding Dependencies to Connectors When the connectors in your application need access to a dependency in your project, configure the dependency to be visible by the connector’s class loader. There are two different ways to do this: - Configure application dependencies as [shared libraries](#shared-libraries). - Configure [additional plugin dependencies](#additional-plugin-dependencies) for the connector. ### Shared Libraries All dependencies (JAR files, for example) declared in the application’s `pom.xml` file are visible to the application’s class loader but not visible to the class loader of each connector used in the application. The Mule runtime engine class-loading mechanism isolates each connector to prevent it from accessing classes from other connectors. If a connector’s class loader needs access to an application dependency, declare this dependency as a shared library. Consider an application that uses Anypoint Connector for Java, and the connector needs to use a class that is part of a JAR dependency declared in the application’s `pom.xml` file. However, this is not possible, because the connector’s class loader is not able to find that class. To make this class visible to the connector, you must declare the dependency that contains the class as a shared library in the Mule Maven plugin configuration of your application’s `pom.xml` file. If you use Anypoint Studio to configure a connector that uses external libraries, the dependencies are automatically added as shared libraries. For example, if you add Anypoint Connector for Database to your application and then configure the connection driver using Anypoint Studio, the driver is automatically added as a shared library in your project’s `pom.xml` file. See [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.4/mmp-concept#configure-shared-libraries) for configuration instructions. > [!NOTE] Shared libraries are visible to all connectors in the application. Configuring shared > libraries can cause issues if the shared library has different versions of the same classes in > other connectors or their dependencies. ### Additional Plugin Dependencies Instead of configuring shared libraries to make application dependencies visible to all connectors in the application, you can configure additional plugin dependencies to enrich a specific connector’s classpath. This configuration enables you to effectively add new dependencies to a connector, as if the dependencies were declared in the connector’s `pom.xml` file. Configuring additional plugin dependencies ensures that the dependencies are available only for the configured connector, and you don’t need to declare them as application dependencies. When you configure additional plugin dependencies, you must specify the dependency version. See [Configure Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/4.4/mmp-concept#configure-plugin-dependencies) for configuration instructions. ## See Also - [Mule SDK - About Class-loading Isolation](https://docs.mulesoft.com/mule-sdk/latest/isolation) --- product: Mule Runtime version: 4.6 --- # Class-loading Isolation > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine is developed using Java and many other third-party libraries. Mule apps can also contain Java libraries, particularly modules that extend Mule to provide integration functionality, such as Anypoint Connector for HTTP and the XML module. These extension modules can also contain Java (JAR) libraries. The default class-loading mechanism of the JVM makes it possible to have conflicting versions of the same JAR files. In Mule, each artifact (the runtime, the Mule apps, and Mule extensions) is developed and released independently, but the JARs for these artifacts are together in the same location. For example, a Mule app might use Apache Commons Collections 2.1. If an extension you use requires Apache Commons Collections 3.1, the app might not work as expected because Commons Collections 2.1 and Commons Collections 3.1 have conflicting resources. ## API Definition Mule runtime engine and the artifacts (apps, domains, policies, and extensions) need to have a clear API definition that specifies a contract for each artifact and limits the exposure of the artifact content to other artifacts. A clear API for each artifact provides a way to limit the scope of classes and libraries, which in turn makes it possible to create class loaders that do not share everything. ### Mule 4 API Mule 4 provides a well-defined API that makes it easy for you to extend Mule and provides clarity on the proper extension points: - Core API: Mule message. - Extensions API: Modules, message processors, transforms, and other elements to extend Mule Runtime 4. - Tooling API: All DataSense metadata and propagation is now part of Mule Runtime 4. This API is bundled with the Runtime Manager agent. ### Artifact API When you create an artifact (app, domain, policy, or extension), you need to declare the public API of that module. #### How To Define the Public API See [Export Resources](https://docs.mulesoft.com/mule-runtime/4.6/how-to-export-resources) to export a resource from an artifact. #### Considerations - Resources and classes that are not exported are not visible from other artifacts. - Expose the minimum required set of packages and resources from your artifact. - Do not export third-party libraries unless required. - Never expose common third-party libraries like Guava, Apache common-collections, and so on. Doing so will cause clashes with other artifacts. - Ideally, expose only classes from your artifact (or the JDK). ### Semver Mule 4 follows [Semantic Versioning 2.0.0](https://semver.org/) for all the provided APIs. ### API restrictions All public APIs might have restrictions. These restrictions limit how you can use the API. See [API annotations module](https://github.com/mulesoft/api-annotations) for more details. > [!IMPORTANT] You need to take into account the API restrictions defined for the API you are > consuming, as they ensure greater flexibility among API changes that can occur between different > versions. ## Class-loading Isolation Mechanism Once APIs are clearly defined, you can prevent access to internal classes of the artifact and only make the public API accessible from outside. To protect the APIs, Mule 4 uses a custom class-loading mechanism. Consider the following extension file structure: com/example/extension/api/MyClass.class com/example/extension/internal/Util.class transformations/customer-to-user.dwl license.txt META-INF/mule-artifact/mule-artifact.json And the following `mule-artifact.json` descriptor file for the extension: ```json { "name": "my-test-extension", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": ["transformations/customer-to-user.dwl"], "exportedPackages": ["com/example/extension/api"] } } } ``` The following diagram shows how resources exported by `mule-artifact.json` are applied within an app: ![Simple class-loading diagram](/mulesoft/current/en-us/mule-runtime/4.6/_images/simple-classloading-diagram.png) Artifact Class Loader A regular Java class loader pointing to the JAR files included in the extension. This class loader loads all files and classes of the extension. Artifact Filtering Class Loader A wrapper created over the Artifact class loader, which enforces access restrictions to the extension code for foreign artifacts (the app or other plugins). It uses the content of the `mule-artifact.json` descriptor to determine what is public. Extension Code The Mule extension code. Uses the Artifact class loader (which does not have any restriction), and it is only able to locate resources of the plugin itself. Application Code The Mule app code. It uses the Artifact Filtering class loader of the extension to prevent the app from accessing restricted code or resources. ## Adding Dependencies to Connectors When the connectors in your application need access to a dependency in your project, configure the dependency to be visible by the connector’s class loader. There are two different ways to do this: - Configure application dependencies as [shared libraries](#shared-libraries). - Configure [additional plugin dependencies](#additional-plugin-dependencies) for the connector. ### Shared Libraries All dependencies (JAR files, for example) declared in the application’s `pom.xml` file are visible to the application’s class loader but not visible to the class loader of each connector used in the application. The Mule runtime engine class-loading mechanism isolates each connector to prevent it from accessing classes from other connectors. If a connector’s class loader needs access to an application dependency, declare this dependency as a shared library. Consider an application that uses Anypoint Connector for Java, and the connector needs to use a class that is part of a JAR dependency declared in the application’s `pom.xml` file. However, this is not possible, because the connector’s class loader is not able to find that class. To make this class visible to the connector, you must declare the dependency that contains the class as a shared library in the Mule Maven plugin configuration of your application’s `pom.xml` file. If you use Anypoint Studio to configure a connector that uses external libraries, the dependencies are automatically added as shared libraries. For example, if you add Anypoint Connector for Database to your application and then configure the connection driver using Anypoint Studio, the driver is automatically added as a shared library in your project’s `pom.xml` file. See [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.6/mmp-concept#configure-shared-libraries) for configuration instructions. > [!NOTE] Shared libraries are visible to all connectors in the application. Configuring shared > libraries can cause issues if the shared library has different versions of the same classes in > other connectors or their dependencies. ### Additional Plugin Dependencies Instead of configuring shared libraries to make application dependencies visible to all connectors in the application, you can configure additional plugin dependencies to enrich a specific connector’s classpath. This configuration enables you to effectively add new dependencies to a connector, as if the dependencies were declared in the connector’s `pom.xml` file. Configuring additional plugin dependencies ensures that the dependencies are available only for the configured connector, and you don’t need to declare them as application dependencies. When you configure additional plugin dependencies, you must specify the dependency version. See [Configure Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/4.6/mmp-concept#configure-plugin-dependencies) for configuration instructions. ## See Also - [Mule SDK - About Class-loading Isolation](https://docs.mulesoft.com/mule-sdk/latest/isolation) --- product: Mule Runtime version: 4.9 --- # Class-loading Isolation > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine is developed using Java and many other third-party libraries. Mule apps can also contain Java libraries, particularly modules that extend Mule to provide integration functionality, such as Anypoint Connector for HTTP and the XML module. These extension modules can also contain Java (JAR) libraries. The default class-loading mechanism of the JVM makes it possible to have conflicting versions of the same JAR files. In Mule, each artifact (the runtime, the Mule apps, and Mule extensions) is developed and released independently, but the JARs for these artifacts are together in the same location. For example, a Mule app might use Apache Commons Collections 2.1. If an extension you use requires Apache Commons Collections 3.1, the app might not work as expected because Commons Collections 2.1 and Commons Collections 3.1 have conflicting resources. ## API Definition Mule runtime engine and the artifacts (apps, domains, policies, and extensions) need to have a clear API definition that specifies a contract for each artifact and limits the exposure of the artifact content to other artifacts. A clear API for each artifact provides a way to limit the scope of classes and libraries, which in turn makes it possible to create class loaders that do not share everything. ### Mule 4 API Mule 4 provides a well-defined API that makes it easy for you to extend Mule and provides clarity on the proper extension points: - Core API: Mule message. - Extensions API: Modules, message processors, transforms, and other elements to extend Mule Runtime 4. - Tooling API: All DataSense metadata and propagation is now part of Mule Runtime 4. This API is bundled with the Runtime Manager agent. ### Artifact API When you create an artifact (app, domain, policy, or extension), you need to declare the public API of that module. #### How To Define the Public API See [Export Resources](https://docs.mulesoft.com/mule-runtime/4.9/how-to-export-resources) to export a resource from an artifact. #### Considerations - Resources and classes that are not exported are not visible from other artifacts. - Expose the minimum required set of packages and resources from your artifact. - Do not export third-party libraries unless required. - Never expose common third-party libraries like Guava, Apache common-collections, and so on. Doing so will cause clashes with other artifacts. - Ideally, expose only classes from your artifact (or the JDK). ### Semver Mule 4 follows [Semantic Versioning 2.0.0](https://semver.org/) for all the provided APIs. ### API restrictions All public APIs might have restrictions. These restrictions limit how you can use the API. See [API annotations module](https://github.com/mulesoft/api-annotations) for more details. > [!IMPORTANT] You need to take into account the API restrictions defined for the API you are > consuming, as they ensure greater flexibility among API changes that can occur between different > versions. ## Class-loading Isolation Mechanism Once APIs are clearly defined, you can prevent access to internal classes of the artifact and only make the public API accessible from outside. To protect the APIs, Mule 4 uses a custom class-loading mechanism. Consider the following extension file structure: com/example/extension/api/MyClass.class com/example/extension/internal/Util.class transformations/customer-to-user.dwl license.txt META-INF/mule-artifact/mule-artifact.json And the following `mule-artifact.json` descriptor file for the extension: ```json { "name": "my-test-extension", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": ["transformations/customer-to-user.dwl"], "exportedPackages": ["com/example/extension/api"] } } } ``` The following diagram shows how resources exported by `mule-artifact.json` are applied within an app: ![A class-loading diagram for a Mule app](/mulesoft/current/en-us/mule-runtime/4.9/_images/simple-classloading-diagram.png) Artifact Class Loader A regular Java class loader pointing to the JAR files included in the extension. This class loader loads all files and classes of the extension. Artifact Filtering Class Loader A wrapper created over the Artifact class loader, which enforces access restrictions to the extension code for foreign artifacts (the app or other plugins). It uses the content of the `mule-artifact.json` descriptor to determine what is public. Extension Code The Mule extension code. Uses the Artifact class loader (which does not have any restriction), and it is only able to locate resources of the plugin itself. Application Code The Mule app code. It uses the Artifact Filtering class loader of the extension to prevent the app from accessing restricted code or resources. ## Adding Dependencies to Connectors When the connectors in your application need access to a dependency in your project, configure the dependency to be visible by the connector’s class loader. There are two different ways to do this: - Configure application dependencies as [shared libraries](#shared-libraries). - Configure [additional plugin dependencies](#additional-plugin-dependencies) for the connector. ### Shared Libraries All dependencies (JAR files, for example) declared in the application’s `pom.xml` file are visible to the application’s class loader but not visible to the class loader of each connector used in the application. The Mule runtime engine class-loading mechanism isolates each connector to prevent it from accessing classes from other connectors. If a connector’s class loader needs access to an application dependency, declare this dependency as a shared library. Consider an application that uses Anypoint Connector for Java, and the connector needs to use a class that is part of a JAR dependency declared in the application’s `pom.xml` file. However, this is not possible, because the connector’s class loader is not able to find that class. To make this class visible to the connector, you must declare the dependency that contains the class as a shared library in the Mule Maven plugin configuration of your application’s `pom.xml` file. If you use Anypoint Studio to configure a connector that uses external libraries, the dependencies are automatically added as shared libraries. For example, if you add Anypoint Connector for Database to your application and then configure the connection driver using Anypoint Studio, the driver is automatically added as a shared library in your project’s `pom.xml` file. See [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.9/mmp-concept#configure-shared-libraries) for configuration instructions. > [!NOTE] Shared libraries are visible to all connectors in the application. Configuring shared > libraries can cause issues if the shared library has different versions of the same classes in > other connectors or their dependencies. ### Additional Plugin Dependencies Instead of configuring shared libraries to make application dependencies visible to all connectors in the application, you can configure additional plugin dependencies to enrich a specific connector’s classpath. This configuration enables you to effectively add new dependencies to a connector, as if the dependencies were declared in the connector’s `pom.xml` file. Configuring additional plugin dependencies ensures that the dependencies are available only for the configured connector, and you don’t need to declare them as application dependencies. When you configure additional plugin dependencies, you must specify the dependency version. See [Configure Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/4.9/mmp-concept#configure-plugin-dependencies) for configuration instructions. ## See Also - [Mule SDK - About Class-loading Isolation](https://docs.mulesoft.com/mule-sdk/latest/isolation) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Class-loading Isolation > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine is developed using Java and many other third-party libraries. Mule apps can also contain Java libraries, particularly modules that extend Mule to provide integration functionality, such as Anypoint Connector for HTTP and the XML module. These extension modules can also contain Java (JAR) libraries. The default class-loading mechanism of the JVM makes it possible to have conflicting versions of the same JAR files. In Mule, each artifact (the runtime, the Mule apps, and Mule extensions) is developed and released independently, but the JARs for these artifacts are together in the same location. For example, a Mule app might use Apache Commons Collections 2.1. If an extension you use requires Apache Commons Collections 3.1, the app might not work as expected because Commons Collections 2.1 and Commons Collections 3.1 have conflicting resources. ## API Definition Mule runtime engine and the artifacts (apps, domains, policies, and extensions) need to have a clear API definition that specifies a contract for each artifact and limits the exposure of the artifact content to other artifacts. A clear API for each artifact provides a way to limit the scope of classes and libraries, which in turn makes it possible to create class loaders that do not share everything. ### Mule 4 API Mule 4 provides a well-defined API that makes it easy for you to extend Mule and provides clarity on the proper extension points: - Core API: Mule message. - Extensions API: Modules, message processors, transforms, and other elements to extend Mule Runtime 4. - Tooling API: All DataSense metadata and propagation is now part of Mule Runtime 4. This API is bundled with the Runtime Manager agent. ### Artifact API When you create an artifact (app, domain, policy, or extension), you need to declare the public API of that module. #### How To Define the Public API See [Export Resources](https://docs.mulesoft.com/mule-runtime/latest/how-to-export-resources) to export a resource from an artifact. #### Considerations - Resources and classes that are not exported are not visible from other artifacts. - Expose the minimum required set of packages and resources from your artifact. - Do not export third-party libraries unless required. - Never expose common third-party libraries like Guava, Apache common-collections, and so on. Doing so will cause clashes with other artifacts. - Ideally, expose only classes from your artifact (or the JDK). ### Semver Mule 4 follows [Semantic Versioning 2.0.0](https://semver.org/) for all the provided APIs. ### API restrictions All public APIs might have restrictions. These restrictions limit how you can use the API. See [API annotations module](https://github.com/mulesoft/api-annotations) for more details. > [!IMPORTANT] You need to take into account the API restrictions defined for the API you are > consuming, as they ensure greater flexibility among API changes that can occur between different > versions. ## Class-loading Isolation Mechanism Once APIs are clearly defined, you can prevent access to internal classes of the artifact and only make the public API accessible from outside. To protect the APIs, Mule 4 uses a custom class-loading mechanism. Consider the following extension file structure: com/example/extension/api/MyClass.class com/example/extension/internal/Util.class transformations/customer-to-user.dwl license.txt META-INF/mule-artifact/mule-artifact.json And the following `mule-artifact.json` descriptor file for the extension: ```json { "name": "my-test-extension", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": ["transformations/customer-to-user.dwl"], "exportedPackages": ["com/example/extension/api"] } } } ``` The following diagram shows how resources exported by `mule-artifact.json` are applied within an app: ![A class-loading diagram for a Mule app](/mulesoft/current/en-us/mule-runtime/latest/_images/simple-classloading-diagram.png) Artifact Class Loader A regular Java class loader pointing to the JAR files included in the extension. This class loader loads all files and classes of the extension. Artifact Filtering Class Loader A wrapper created over the Artifact class loader, which enforces access restrictions to the extension code for foreign artifacts (the app or other plugins). It uses the content of the `mule-artifact.json` descriptor to determine what is public. Extension Code The Mule extension code. Uses the Artifact class loader (which does not have any restriction), and it is only able to locate resources of the plugin itself. Application Code The Mule app code. It uses the Artifact Filtering class loader of the extension to prevent the app from accessing restricted code or resources. ## Adding Dependencies to Connectors When the connectors in your application need access to a dependency in your project, configure the dependency to be visible by the connector’s class loader. There are two different ways to do this: - Configure application dependencies as [shared libraries](#shared-libraries). - Configure [additional plugin dependencies](#additional-plugin-dependencies) for the connector. ### Shared Libraries All dependencies (JAR files, for example) declared in the application’s `pom.xml` file are visible to the application’s class loader but not visible to the class loader of each connector used in the application. The Mule runtime engine class-loading mechanism isolates each connector to prevent it from accessing classes from other connectors. If a connector’s class loader needs access to an application dependency, declare this dependency as a shared library. Consider an application that uses Anypoint Connector for Java, and the connector needs to use a class that is part of a JAR dependency declared in the application’s `pom.xml` file. However, this is not possible, because the connector’s class loader is not able to find that class. To make this class visible to the connector, you must declare the dependency that contains the class as a shared library in the Mule Maven plugin configuration of your application’s `pom.xml` file. If you use Anypoint Studio to configure a connector that uses external libraries, the dependencies are automatically added as shared libraries. For example, if you add Anypoint Connector for Database to your application and then configure the connection driver using Anypoint Studio, the driver is automatically added as a shared library in your project’s `pom.xml` file. See [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#configure-shared-libraries) for configuration instructions. > [!NOTE] Shared libraries are visible to all connectors in the application. Configuring shared > libraries can cause issues if the shared library has different versions of the same classes in > other connectors or their dependencies. ### Additional Plugin Dependencies Instead of configuring shared libraries to make application dependencies visible to all connectors in the application, you can configure additional plugin dependencies to enrich a specific connector’s classpath. This configuration enables you to effectively add new dependencies to a connector, as if the dependencies were declared in the connector’s `pom.xml` file. Configuring additional plugin dependencies ensures that the dependencies are available only for the configured connector, and you don’t need to declare them as application dependencies. When you configure additional plugin dependencies, you must specify the dependency version. See [Configure Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#configure-plugin-dependencies) for configuration instructions. ## See Also - [Mule SDK - About Class-loading Isolation](https://docs.mulesoft.com/mule-sdk/latest/isolation) --- product: Mule Runtime version: 4.11 keywords: anypoint, development, strategies, application, pattern, reliability, modularize, transaction, integration, orchestration --- # Common Development Strategies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you develop your Mule applications, consider common development strategies and practices such as creating reproducible builds, modularizing your configuration files, and implementing reliability patterns, transaction management, continuous integration, orchestration in Mule, and enterprise integration patterns. ## Create Reproducible Builds Create reproducible builds to facilitate application maintenance, by running a particular version of your Mule projects at any time. You can achieve this goal by: - Using source control for your Mule projects - Managing dependencies by using Apache Maven and an in-house manager. For details, see the [Reproducible Builds](https://docs.mulesoft.com/mule-runtime/4.11/reproducible-builds) documentation. ## Implement Reliability Patterns Implement a reliability pattern in your application design so your application is capable of reliable messaging, even if receives messages from a nontransactional connector. A reliability pattern design couples a reliable acquisition flow with an application logic flow. For details, see the [Reliability Patterns](https://docs.mulesoft.com/mule-runtime/4.11/reliability-patterns) documentation. ## Implement Transaction Management Implement transaction operations in a Mule app for which the result cannot remain indeterminate. When a series of steps in a flow must succeed or fail as one unit, Mule uses a transaction to demarcate that unit. For details on the different transaction types, transaction actions operations and how you can configure a transaction in a Mule event source or Try Scope in the [Transaction Management](https://docs.mulesoft.com/mule-runtime/4.11/transaction-management) documentation. Additionally, you can implement [Single Source Transactions](https://docs.mulesoft.com/mule-runtime/4.11/single-resource-transaction), [XA Transactions](https://docs.mulesoft.com/mule-runtime/4.11/xa-transactions) and [Using Bitronix to manage transactions](https://docs.mulesoft.com/mule-runtime/4.11/using-bitronix-to-manage-transactions). ## Modularize Configurations Files Modularize configuration files by splitting monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Although it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. Modularizing Mule configurations is an opportunity for splitting work across teams, whether these teams work on the same project or on different projects with an accent put on reuse. There are two options to load multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. For details see the [Modularize Configurations Files](https://docs.mulesoft.com/mule-runtime/4.11/modularizing-your-configuration-files-for-team-development) documentation. ## Implement Continuous Integration Implement continuous integration (CI) for your projects by using Maven as your build tool. Create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. By doing so you can: - Get early notification of issues in the software development lifecycle. - Ensure code gets fully tested before release. - Confirm that successfully tested branches ensure better success when merging to the main branch. For details, see the [Continuous Integration](https://docs.mulesoft.com/mule-runtime/4.11/continuous-integration) documentation. ## Implement Orchestration in Mule Implement orchestration in Mule to facilitate the process of moving data through a Mule implementation based on flows. The orchestration implements business-level processes combining business-specific services across applications and information systems. Flows uses cases that orchestrate are: - Simple integration. - Scheduling data processing. - Connecting cloud and on-premise applications. - Event processing, where multiple services must be composed and must operate simultaneously. For details, see the [Orchestration Using Mule](https://docs.mulesoft.com/mule-runtime/4.11/understanding-orchestration-using-mule) documentation. ## Implement Enterprise Integration Patterns Implement enterprise integration patterns as solutions for designing, building messaging and integration systems, as well as to provide a common language for teams to use when architecting solutions. For details, see the [Enterprise Integration Patterns Using Mule](https://docs.mulesoft.com/mule-runtime/4.11/understanding-enterprise-integration-patterns-using-mule) documentation. ## Configure Business Events Tracking Mule applications can collect business event information about flows and message processors that handle your business transactions. You can configure default event tracking for supported components or entire flows, and you can also configure custom event tracking using the Custom Business Events component. For details, see the [Business Events](https://docs.mulesoft.com/mule-runtime/4.11/business-events) documentation. ## Share Applications Share Mule applications for splitting work across teams, whether these teams work on the same project or on different projects that they intent for reuse. For details, see the [Share Applications](https://docs.mulesoft.com/mule-runtime/4.11/sharing-applications) documentation. ## Best Practices to Build Mule Applications As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. For details, see the [Best Practices to Build Mule Apps](https://docs.mulesoft.com/mule-runtime/4.11/build-app-practices) documentation. --- product: Mule Runtime version: 4.12 keywords: anypoint, development, strategies, application, pattern, reliability, modularize, transaction, integration, orchestration --- # Common Development Strategies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you develop your Mule applications, consider common development strategies and practices such as creating reproducible builds, modularizing your configuration files, and implementing reliability patterns, transaction management, continuous integration, orchestration in Mule, and enterprise integration patterns. ## Create Reproducible Builds Create reproducible builds to facilitate application maintenance, by running a particular version of your Mule projects at any time. You can achieve this goal by: - Using source control for your Mule projects - Managing dependencies by using Apache Maven and an in-house manager. For details, see the [Reproducible Builds](https://docs.mulesoft.com/mule-runtime/4.12/reproducible-builds) documentation. ## Implement Reliability Patterns Implement a reliability pattern in your application design so your application is capable of reliable messaging, even if receives messages from a nontransactional connector. A reliability pattern design couples a reliable acquisition flow with an application logic flow. For details, see the [Reliability Patterns](https://docs.mulesoft.com/mule-runtime/4.12/reliability-patterns) documentation. ## Implement Transaction Management Implement transaction operations in a Mule app for which the result cannot remain indeterminate. When a series of steps in a flow must succeed or fail as one unit, Mule uses a transaction to demarcate that unit. For details on the different transaction types, transaction actions operations and how you can configure a transaction in a Mule event source or Try Scope in the [Transaction Management](https://docs.mulesoft.com/mule-runtime/4.12/transaction-management) documentation. Additionally, you can implement [Single Source Transactions](https://docs.mulesoft.com/mule-runtime/4.12/single-resource-transaction), [XA Transactions](https://docs.mulesoft.com/mule-runtime/4.12/xa-transactions) and [Using Bitronix to manage transactions](https://docs.mulesoft.com/mule-runtime/4.12/using-bitronix-to-manage-transactions). ## Modularize Configurations Files Modularize configuration files by splitting monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Although it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. Modularizing Mule configurations is an opportunity for splitting work across teams, whether these teams work on the same project or on different projects with an accent put on reuse. There are two options to load multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. For details see the [Modularize Configurations Files](https://docs.mulesoft.com/mule-runtime/4.12/modularizing-your-configuration-files-for-team-development) documentation. ## Implement Continuous Integration Implement continuous integration (CI) for your projects by using Maven as your build tool. Create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. By doing so you can: - Get early notification of issues in the software development lifecycle. - Ensure code gets fully tested before release. - Confirm that successfully tested branches ensure better success when merging to the main branch. For details, see the [Continuous Integration](https://docs.mulesoft.com/mule-runtime/4.12/continuous-integration) documentation. ## Implement Orchestration in Mule Implement orchestration in Mule to facilitate the process of moving data through a Mule implementation based on flows. The orchestration implements business-level processes combining business-specific services across applications and information systems. Flows uses cases that orchestrate are: - Simple integration. - Scheduling data processing. - Connecting cloud and on-premise applications. - Event processing, where multiple services must be composed and must operate simultaneously. For details, see the [Orchestration Using Mule](https://docs.mulesoft.com/mule-runtime/4.12/understanding-orchestration-using-mule) documentation. ## Implement Enterprise Integration Patterns Implement enterprise integration patterns as solutions for designing, building messaging and integration systems, as well as to provide a common language for teams to use when architecting solutions. For details, see the [Enterprise Integration Patterns Using Mule](https://docs.mulesoft.com/mule-runtime/4.12/understanding-enterprise-integration-patterns-using-mule) documentation. ## Configure Business Events Tracking Mule applications can collect business event information about flows and message processors that handle your business transactions. You can configure default event tracking for supported components or entire flows, and you can also configure custom event tracking using the Custom Business Events component. For details, see the [Business Events](https://docs.mulesoft.com/mule-runtime/4.12/business-events) documentation. ## Share Applications Share Mule applications for splitting work across teams, whether these teams work on the same project or on different projects that they intent for reuse. For details, see the [Share Applications](https://docs.mulesoft.com/mule-runtime/4.12/sharing-applications) documentation. ## Best Practices to Build Mule Applications As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. For details, see the [Best Practices to Build Mule Apps](https://docs.mulesoft.com/mule-runtime/4.12/build-app-practices) documentation. --- product: Mule Runtime version: 4.3 keywords: anypoint, development, strategies, application, pattern, reliability, modularize, transaction, integration, orchestration --- # Common Development Strategies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you develop your Mule applications, consider common development strategies and practices such as creating reproducible builds, modularizing your configuration files, and implementing reliability patterns, transaction management, continuous integration, orchestration in Mule, and enterprise integration patterns. ## Create Reproducible Builds Create reproducible builds to facilitate application maintenance, by running a particular version of your Mule projects at any time. You can achieve this goal by: - Using source control for your Mule projects - Managing dependencies by using Apache Maven and an in-house manager. For details, see the [Reproducible Builds](https://docs.mulesoft.com/mule-runtime/4.3/reproducible-builds) documentation. ## Implement Reliability Patterns Implement a reliability pattern in your application design so your application is capable of reliable messaging, even if receives messages from a nontransactional connector. A reliability pattern design couples a reliable acquisition flow with an application logic flow. For details, see the [Reliability Patterns](https://docs.mulesoft.com/mule-runtime/4.3/reliability-patterns) documentation. ## Implement Transaction Management Implement transaction operations in a Mule app for which the result cannot remain indeterminate. When a series of steps in a flow must succeed or fail as one unit, Mule uses a transaction to demarcate that unit. For details on the different transaction types, transaction actions operations and how you can configure a transaction in a message source or Try Scope in the [Transaction Management](https://docs.mulesoft.com/mule-runtime/4.3/transaction-management) documentation. Additionally, you can implement [Single Source Transactions](https://docs.mulesoft.com/mule-runtime/4.3/single-resource-transaction), [XA Transactions](https://docs.mulesoft.com/mule-runtime/4.3/xa-transactions) and [Using Bitronix to manage transactions](https://docs.mulesoft.com/mule-runtime/4.3/using-bitronix-to-manage-transactions). ## Modularize Configurations Files Modularize configuration files by splitting monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Although it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. Modularizing Mule configurations is an opportunity for splitting work across teams, whether these teams work on the same project or on different projects with an accent put on reuse. There are two options to load multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. For details see the [Modularize Configurations Files](https://docs.mulesoft.com/mule-runtime/4.3/modularizing-your-configuration-files-for-team-development) documentation. ## Implement Continuous Integration Implement continuous integration (CI) for your projects by using Maven as your build tool. Create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. By doing so you can: - Get early notification of issues in the software development lifecycle. - Ensure code gets fully tested before release. - Confirm that successfully tested branches ensure better success when merging to the main branch. For details, see the [Continuous Integration](https://docs.mulesoft.com/mule-runtime/4.3/continuous-integration) documentation. ## Implement Orchestration in Mule Implement orchestration in Mule to facilitate the process of moving data through a Mule implementation based on flows. The orchestration implements business-level processes combining business-specific services across applications and information systems. Flows uses cases that orchestrate are: - Simple integration. - Scheduling data processing. - Connecting cloud and on-premise applications. - Event processing, where multiple services must be composed and must operate simultaneously. For details, see the [Orchestration Using Mule](https://docs.mulesoft.com/mule-runtime/4.3/understanding-orchestration-using-mule) documentation. ## Implement Enterprise Integration Patterns Implement enterprise integration patterns as solutions for designing, building messaging and integration systems, as well as to provide a common language for teams to use when architecting solutions. For details, see the [Enterprise Integration Patterns Using Mule](https://docs.mulesoft.com/mule-runtime/4.3/understanding-enterprise-integration-patterns-using-mule) documentation. ## Configure Business Events Tracking Mule applications can collect business event information about flows and message processors that handle your business transactions. You can configure default event tracking for supported components or entire flows, and you can also configure custom event tracking using the Custom Business Events component. For details, see the [Business Events](https://docs.mulesoft.com/mule-runtime/4.3/business-events) documentation. ## Share Applications Share Mule applications for splitting work across teams, whether these teams work on the same project or on different projects that they intent for reuse. For details, see the [Share Applications](https://docs.mulesoft.com/mule-runtime/4.3/sharing-applications) documentation. ## Best Practices to Build Mule Applications As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. For details, see the [Best Practices to Build Mule Apps](https://docs.mulesoft.com/mule-runtime/4.3/build-app-practices) documentation. --- product: Mule Runtime version: 4.4 keywords: anypoint, development, strategies, application, pattern, reliability, modularize, transaction, integration, orchestration --- # Common Development Strategies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you develop your Mule applications, consider common development strategies and practices such as creating reproducible builds, modularizing your configuration files, and implementing reliability patterns, transaction management, continuous integration, orchestration in Mule, and enterprise integration patterns. ## Create Reproducible Builds Create reproducible builds to facilitate application maintenance, by running a particular version of your Mule projects at any time. You can achieve this goal by: - Using source control for your Mule projects - Managing dependencies by using Apache Maven and an in-house manager. For details, see the [Reproducible Builds](https://docs.mulesoft.com/mule-runtime/4.4/reproducible-builds) documentation. ## Implement Reliability Patterns Implement a reliability pattern in your application design so your application is capable of reliable messaging, even if receives messages from a nontransactional connector. A reliability pattern design couples a reliable acquisition flow with an application logic flow. For details, see the [Reliability Patterns](https://docs.mulesoft.com/mule-runtime/4.4/reliability-patterns) documentation. ## Implement Transaction Management Implement transaction operations in a Mule app for which the result cannot remain indeterminate. When a series of steps in a flow must succeed or fail as one unit, Mule uses a transaction to demarcate that unit. For details on the different transaction types, transaction actions operations and how you can configure a transaction in a Mule event source or Try Scope in the [Transaction Management](https://docs.mulesoft.com/mule-runtime/4.4/transaction-management) documentation. Additionally, you can implement [Single Source Transactions](https://docs.mulesoft.com/mule-runtime/4.4/single-resource-transaction), [XA Transactions](https://docs.mulesoft.com/mule-runtime/4.4/xa-transactions) and [Using Bitronix to manage transactions](https://docs.mulesoft.com/mule-runtime/4.4/using-bitronix-to-manage-transactions). ## Modularize Configurations Files Modularize configuration files by splitting monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Although it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. Modularizing Mule configurations is an opportunity for splitting work across teams, whether these teams work on the same project or on different projects with an accent put on reuse. There are two options to load multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. For details see the [Modularize Configurations Files](https://docs.mulesoft.com/mule-runtime/4.4/modularizing-your-configuration-files-for-team-development) documentation. ## Implement Continuous Integration Implement continuous integration (CI) for your projects by using Maven as your build tool. Create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. By doing so you can: - Get early notification of issues in the software development lifecycle. - Ensure code gets fully tested before release. - Confirm that successfully tested branches ensure better success when merging to the main branch. For details, see the [Continuous Integration](https://docs.mulesoft.com/mule-runtime/4.4/continuous-integration) documentation. ## Implement Orchestration in Mule Implement orchestration in Mule to facilitate the process of moving data through a Mule implementation based on flows. The orchestration implements business-level processes combining business-specific services across applications and information systems. Flows uses cases that orchestrate are: - Simple integration. - Scheduling data processing. - Connecting cloud and on-premise applications. - Event processing, where multiple services must be composed and must operate simultaneously. For details, see the [Orchestration Using Mule](https://docs.mulesoft.com/mule-runtime/4.4/understanding-orchestration-using-mule) documentation. ## Implement Enterprise Integration Patterns Implement enterprise integration patterns as solutions for designing, building messaging and integration systems, as well as to provide a common language for teams to use when architecting solutions. For details, see the [Enterprise Integration Patterns Using Mule](https://docs.mulesoft.com/mule-runtime/4.4/understanding-enterprise-integration-patterns-using-mule) documentation. ## Configure Business Events Tracking Mule applications can collect business event information about flows and message processors that handle your business transactions. You can configure default event tracking for supported components or entire flows, and you can also configure custom event tracking using the Custom Business Events component. For details, see the [Business Events](https://docs.mulesoft.com/mule-runtime/4.4/business-events) documentation. ## Share Applications Share Mule applications for splitting work across teams, whether these teams work on the same project or on different projects that they intent for reuse. For details, see the [Share Applications](https://docs.mulesoft.com/mule-runtime/4.4/sharing-applications) documentation. ## Best Practices to Build Mule Applications As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. For details, see the [Best Practices to Build Mule Apps](https://docs.mulesoft.com/mule-runtime/4.4/build-app-practices) documentation. --- product: Mule Runtime version: 4.6 keywords: anypoint, development, strategies, application, pattern, reliability, modularize, transaction, integration, orchestration --- # Common Development Strategies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you develop your Mule applications, consider common development strategies and practices such as creating reproducible builds, modularizing your configuration files, and implementing reliability patterns, transaction management, continuous integration, orchestration in Mule, and enterprise integration patterns. ## Create Reproducible Builds Create reproducible builds to facilitate application maintenance, by running a particular version of your Mule projects at any time. You can achieve this goal by: - Using source control for your Mule projects - Managing dependencies by using Apache Maven and an in-house manager. For details, see the [Reproducible Builds](https://docs.mulesoft.com/mule-runtime/4.6/reproducible-builds) documentation. ## Implement Reliability Patterns Implement a reliability pattern in your application design so your application is capable of reliable messaging, even if receives messages from a nontransactional connector. A reliability pattern design couples a reliable acquisition flow with an application logic flow. For details, see the [Reliability Patterns](https://docs.mulesoft.com/mule-runtime/4.6/reliability-patterns) documentation. ## Implement Transaction Management Implement transaction operations in a Mule app for which the result cannot remain indeterminate. When a series of steps in a flow must succeed or fail as one unit, Mule uses a transaction to demarcate that unit. For details on the different transaction types, transaction actions operations and how you can configure a transaction in a Mule event source or Try Scope in the [Transaction Management](https://docs.mulesoft.com/mule-runtime/4.6/transaction-management) documentation. Additionally, you can implement [Single Source Transactions](https://docs.mulesoft.com/mule-runtime/4.6/single-resource-transaction), [XA Transactions](https://docs.mulesoft.com/mule-runtime/4.6/xa-transactions) and [Using Bitronix to manage transactions](https://docs.mulesoft.com/mule-runtime/4.6/using-bitronix-to-manage-transactions). ## Modularize Configurations Files Modularize configuration files by splitting monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Although it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. Modularizing Mule configurations is an opportunity for splitting work across teams, whether these teams work on the same project or on different projects with an accent put on reuse. There are two options to load multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. For details see the [Modularize Configurations Files](https://docs.mulesoft.com/mule-runtime/4.6/modularizing-your-configuration-files-for-team-development) documentation. ## Implement Continuous Integration Implement continuous integration (CI) for your projects by using Maven as your build tool. Create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. By doing so you can: - Get early notification of issues in the software development lifecycle. - Ensure code gets fully tested before release. - Confirm that successfully tested branches ensure better success when merging to the main branch. For details, see the [Continuous Integration](https://docs.mulesoft.com/mule-runtime/4.6/continuous-integration) documentation. ## Implement Orchestration in Mule Implement orchestration in Mule to facilitate the process of moving data through a Mule implementation based on flows. The orchestration implements business-level processes combining business-specific services across applications and information systems. Flows uses cases that orchestrate are: - Simple integration. - Scheduling data processing. - Connecting cloud and on-premise applications. - Event processing, where multiple services must be composed and must operate simultaneously. For details, see the [Orchestration Using Mule](https://docs.mulesoft.com/mule-runtime/4.6/understanding-orchestration-using-mule) documentation. ## Implement Enterprise Integration Patterns Implement enterprise integration patterns as solutions for designing, building messaging and integration systems, as well as to provide a common language for teams to use when architecting solutions. For details, see the [Enterprise Integration Patterns Using Mule](https://docs.mulesoft.com/mule-runtime/4.6/understanding-enterprise-integration-patterns-using-mule) documentation. ## Configure Business Events Tracking Mule applications can collect business event information about flows and message processors that handle your business transactions. You can configure default event tracking for supported components or entire flows, and you can also configure custom event tracking using the Custom Business Events component. For details, see the [Business Events](https://docs.mulesoft.com/mule-runtime/4.6/business-events) documentation. ## Share Applications Share Mule applications for splitting work across teams, whether these teams work on the same project or on different projects that they intent for reuse. For details, see the [Share Applications](https://docs.mulesoft.com/mule-runtime/4.6/sharing-applications) documentation. ## Best Practices to Build Mule Applications As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. For details, see the [Best Practices to Build Mule Apps](https://docs.mulesoft.com/mule-runtime/4.6/build-app-practices) documentation. --- product: Mule Runtime version: 4.9 keywords: anypoint, development, strategies, application, pattern, reliability, modularize, transaction, integration, orchestration --- # Common Development Strategies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you develop your Mule applications, consider common development strategies and practices such as creating reproducible builds, modularizing your configuration files, and implementing reliability patterns, transaction management, continuous integration, orchestration in Mule, and enterprise integration patterns. ## Create Reproducible Builds Create reproducible builds to facilitate application maintenance, by running a particular version of your Mule projects at any time. You can achieve this goal by: - Using source control for your Mule projects - Managing dependencies by using Apache Maven and an in-house manager. For details, see the [Reproducible Builds](https://docs.mulesoft.com/mule-runtime/4.9/reproducible-builds) documentation. ## Implement Reliability Patterns Implement a reliability pattern in your application design so your application is capable of reliable messaging, even if receives messages from a nontransactional connector. A reliability pattern design couples a reliable acquisition flow with an application logic flow. For details, see the [Reliability Patterns](https://docs.mulesoft.com/mule-runtime/4.9/reliability-patterns) documentation. ## Implement Transaction Management Implement transaction operations in a Mule app for which the result cannot remain indeterminate. When a series of steps in a flow must succeed or fail as one unit, Mule uses a transaction to demarcate that unit. For details on the different transaction types, transaction actions operations and how you can configure a transaction in a Mule event source or Try Scope in the [Transaction Management](https://docs.mulesoft.com/mule-runtime/4.9/transaction-management) documentation. Additionally, you can implement [Single Source Transactions](https://docs.mulesoft.com/mule-runtime/4.9/single-resource-transaction), [XA Transactions](https://docs.mulesoft.com/mule-runtime/4.9/xa-transactions) and [Using Bitronix to manage transactions](https://docs.mulesoft.com/mule-runtime/4.9/using-bitronix-to-manage-transactions). ## Modularize Configurations Files Modularize configuration files by splitting monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Although it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. Modularizing Mule configurations is an opportunity for splitting work across teams, whether these teams work on the same project or on different projects with an accent put on reuse. There are two options to load multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. For details see the [Modularize Configurations Files](https://docs.mulesoft.com/mule-runtime/4.9/modularizing-your-configuration-files-for-team-development) documentation. ## Implement Continuous Integration Implement continuous integration (CI) for your projects by using Maven as your build tool. Create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. By doing so you can: - Get early notification of issues in the software development lifecycle. - Ensure code gets fully tested before release. - Confirm that successfully tested branches ensure better success when merging to the main branch. For details, see the [Continuous Integration](https://docs.mulesoft.com/mule-runtime/4.9/continuous-integration) documentation. ## Implement Orchestration in Mule Implement orchestration in Mule to facilitate the process of moving data through a Mule implementation based on flows. The orchestration implements business-level processes combining business-specific services across applications and information systems. Flows uses cases that orchestrate are: - Simple integration. - Scheduling data processing. - Connecting cloud and on-premise applications. - Event processing, where multiple services must be composed and must operate simultaneously. For details, see the [Orchestration Using Mule](https://docs.mulesoft.com/mule-runtime/4.9/understanding-orchestration-using-mule) documentation. ## Implement Enterprise Integration Patterns Implement enterprise integration patterns as solutions for designing, building messaging and integration systems, as well as to provide a common language for teams to use when architecting solutions. For details, see the [Enterprise Integration Patterns Using Mule](https://docs.mulesoft.com/mule-runtime/4.9/understanding-enterprise-integration-patterns-using-mule) documentation. ## Configure Business Events Tracking Mule applications can collect business event information about flows and message processors that handle your business transactions. You can configure default event tracking for supported components or entire flows, and you can also configure custom event tracking using the Custom Business Events component. For details, see the [Business Events](https://docs.mulesoft.com/mule-runtime/4.9/business-events) documentation. ## Share Applications Share Mule applications for splitting work across teams, whether these teams work on the same project or on different projects that they intent for reuse. For details, see the [Share Applications](https://docs.mulesoft.com/mule-runtime/4.9/sharing-applications) documentation. ## Best Practices to Build Mule Applications As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. For details, see the [Best Practices to Build Mule Apps](https://docs.mulesoft.com/mule-runtime/4.9/build-app-practices) documentation. --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: anypoint, development, strategies, application, pattern, reliability, modularize, transaction, integration, orchestration --- # Common Development Strategies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you develop your Mule applications, consider common development strategies and practices such as creating reproducible builds, modularizing your configuration files, and implementing reliability patterns, transaction management, continuous integration, orchestration in Mule, and enterprise integration patterns. ## Create Reproducible Builds Create reproducible builds to facilitate application maintenance, by running a particular version of your Mule projects at any time. You can achieve this goal by: - Using source control for your Mule projects - Managing dependencies by using Apache Maven and an in-house manager. For details, see the [Reproducible Builds](https://docs.mulesoft.com/mule-runtime/latest/reproducible-builds) documentation. ## Implement Reliability Patterns Implement a reliability pattern in your application design so your application is capable of reliable messaging, even if receives messages from a nontransactional connector. A reliability pattern design couples a reliable acquisition flow with an application logic flow. For details, see the [Reliability Patterns](https://docs.mulesoft.com/mule-runtime/latest/reliability-patterns) documentation. ## Implement Transaction Management Implement transaction operations in a Mule app for which the result cannot remain indeterminate. When a series of steps in a flow must succeed or fail as one unit, Mule uses a transaction to demarcate that unit. For details on the different transaction types, transaction actions operations and how you can configure a transaction in a Mule event source or Try Scope in the [Transaction Management](https://docs.mulesoft.com/mule-runtime/latest/transaction-management) documentation. Additionally, you can implement [Single Source Transactions](https://docs.mulesoft.com/mule-runtime/latest/single-resource-transaction), [XA Transactions](https://docs.mulesoft.com/mule-runtime/latest/xa-transactions) and [Using Bitronix to manage transactions](https://docs.mulesoft.com/mule-runtime/latest/using-bitronix-to-manage-transactions). ## Modularize Configurations Files Modularize configuration files by splitting monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Although it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. Modularizing Mule configurations is an opportunity for splitting work across teams, whether these teams work on the same project or on different projects with an accent put on reuse. There are two options to load multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. For details see the [Modularize Configurations Files](https://docs.mulesoft.com/mule-runtime/latest/modularizing-your-configuration-files-for-team-development) documentation. ## Implement Continuous Integration Implement continuous integration (CI) for your projects by using Maven as your build tool. Create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. By doing so you can: - Get early notification of issues in the software development lifecycle. - Ensure code gets fully tested before release. - Confirm that successfully tested branches ensure better success when merging to the main branch. For details, see the [Continuous Integration](https://docs.mulesoft.com/mule-runtime/latest/continuous-integration) documentation. ## Implement Orchestration in Mule Implement orchestration in Mule to facilitate the process of moving data through a Mule implementation based on flows. The orchestration implements business-level processes combining business-specific services across applications and information systems. Flows uses cases that orchestrate are: - Simple integration. - Scheduling data processing. - Connecting cloud and on-premise applications. - Event processing, where multiple services must be composed and must operate simultaneously. For details, see the [Orchestration Using Mule](https://docs.mulesoft.com/mule-runtime/latest/understanding-orchestration-using-mule) documentation. ## Implement Enterprise Integration Patterns Implement enterprise integration patterns as solutions for designing, building messaging and integration systems, as well as to provide a common language for teams to use when architecting solutions. For details, see the [Enterprise Integration Patterns Using Mule](https://docs.mulesoft.com/mule-runtime/latest/understanding-enterprise-integration-patterns-using-mule) documentation. ## Configure Business Events Tracking Mule applications can collect business event information about flows and message processors that handle your business transactions. You can configure default event tracking for supported components or entire flows, and you can also configure custom event tracking using the Custom Business Events component. For details, see the [Business Events](https://docs.mulesoft.com/mule-runtime/latest/business-events) documentation. ## Share Applications Share Mule applications for splitting work across teams, whether these teams work on the same project or on different projects that they intent for reuse. For details, see the [Share Applications](https://docs.mulesoft.com/mule-runtime/latest/sharing-applications) documentation. ## Best Practices to Build Mule Applications As you build your applications, consider the following best practices for creating a clean, organized, and sustainable project. These practices include guidelines on using Anypoint Studio, avoiding certain app-building issues, and specific settings for using Mule runtime engine (Mule) components and connectors. For details, see the [Best Practices to Build Mule Apps](https://docs.mulesoft.com/mule-runtime/latest/build-app-practices) documentation. --- product: Mule Runtime version: 4.11 keywords: authorization, spring, spring security --- # Component Authorization Using Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Learn how to configure authorization using Spring Security features on your Mule components, so that users with different roles can only invoke certain methods. ## Configure Spring Security Authentication Manager The Spring Security interface Authentication Manager is responsible for passing requests through a chain of Authentication Provider objects. To secure calls to flow components, you must add the configured `authenticationManager` to the application context. The following example defines roles with different levels of access to protected processors: ```xml ``` The following example references the previously defined `authenticationManager` to allow only users with `ROLE_ADMIN` roles in the `requiredAuthorities` field to access the operation: ```xml ``` ## Configure Secure Components in Asynchronous Systems Spring Security is useful for asynchronous systems because to set the authentication on more than one thread you have to add a security property to the security provider. In the following example, the value `MODE_GLOBAL` is the security property added: ```xml ``` --- product: Mule Runtime version: 4.12 keywords: authorization, spring, spring security --- # Component Authorization Using Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Learn how to configure authorization using Spring Security features on your Mule components, so that users with different roles can only invoke certain methods. ## Configure Spring Security Authentication Manager The Spring Security interface Authentication Manager is responsible for passing requests through a chain of Authentication Provider objects. To secure calls to flow components, you must add the configured `authenticationManager` to the application context. The following example defines roles with different levels of access to protected processors: ```xml ``` The following example references the previously defined `authenticationManager` to allow only users with `ROLE_ADMIN` roles in the `requiredAuthorities` field to access the operation: ```xml ``` ## Configure Secure Components in Asynchronous Systems Spring Security is useful for asynchronous systems because to set the authentication on more than one thread you have to add a security property to the security provider. In the following example, the value `MODE_GLOBAL` is the security property added: ```xml ``` --- product: Mule Runtime version: 4.3 keywords: authorization, spring, spring security --- # Component Authorization Using Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Learn how to configure authorization using Spring Security features on your Mule components, so that users with different roles can only invoke certain methods. ## Configure Spring Security Authentication Manager The Spring Security interface Authentication Manager is responsible for passing requests through a chain of Authentication Provider objects. To secure calls to flow components, you must add the configured `authenticationManager` to the application context. The following example defines roles with different levels of access to protected processors: ```xml ``` The following example references the previously defined `authenticationManager` to allow only users with `ROLE_ADMIN` roles in the `requiredAuthorities` field to access the operation: ```xml ``` ## Configure Secure Components in Asynchronous Systems Spring Security is useful for asynchronous systems because to set the authentication on more than one thread you have to add a security property to the security provider. In the following example, the value `MODE_GLOBAL` is the security property added: ```xml ``` --- product: Mule Runtime version: 4.4 keywords: authorization, spring, spring security --- # Component Authorization Using Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Learn how to configure authorization using Spring Security features on your Mule components, so that users with different roles can only invoke certain methods. ## Configure Spring Security Authentication Manager The Spring Security interface Authentication Manager is responsible for passing requests through a chain of Authentication Provider objects. To secure calls to flow components, you must add the configured `authenticationManager` to the application context. The following example defines roles with different levels of access to protected processors: ```xml ``` The following example references the previously defined `authenticationManager` to allow only users with `ROLE_ADMIN` roles in the `requiredAuthorities` field to access the operation: ```xml ``` ## Configure Secure Components in Asynchronous Systems Spring Security is useful for asynchronous systems because to set the authentication on more than one thread you have to add a security property to the security provider. In the following example, the value `MODE_GLOBAL` is the security property added: ```xml ``` --- product: Mule Runtime version: 4.6 keywords: authorization, spring, spring security --- # Component Authorization Using Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Learn how to configure authorization using Spring Security features on your Mule components, so that users with different roles can only invoke certain methods. ## Configure Spring Security Authentication Manager The Spring Security interface Authentication Manager is responsible for passing requests through a chain of Authentication Provider objects. To secure calls to flow components, you must add the configured `authenticationManager` to the application context. The following example defines roles with different levels of access to protected processors: ```xml ``` The following example references the previously defined `authenticationManager` to allow only users with `ROLE_ADMIN` roles in the `requiredAuthorities` field to access the operation: ```xml ``` ## Configure Secure Components in Asynchronous Systems Spring Security is useful for asynchronous systems because to set the authentication on more than one thread you have to add a security property to the security provider. In the following example, the value `MODE_GLOBAL` is the security property added: ```xml ``` --- product: Mule Runtime version: 4.9 keywords: authorization, spring, spring security --- # Component Authorization Using Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Learn how to configure authorization using Spring Security features on your Mule components, so that users with different roles can only invoke certain methods. ## Configure Spring Security Authentication Manager The Spring Security interface Authentication Manager is responsible for passing requests through a chain of Authentication Provider objects. To secure calls to flow components, you must add the configured `authenticationManager` to the application context. The following example defines roles with different levels of access to protected processors: ```xml ``` The following example references the previously defined `authenticationManager` to allow only users with `ROLE_ADMIN` roles in the `requiredAuthorities` field to access the operation: ```xml ``` ## Configure Secure Components in Asynchronous Systems Spring Security is useful for asynchronous systems because to set the authentication on more than one thread you have to add a security property to the security provider. In the following example, the value `MODE_GLOBAL` is the security property added: ```xml ``` --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: authorization, spring, spring security --- # Component Authorization Using Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Learn how to configure authorization using Spring Security features on your Mule components, so that users with different roles can only invoke certain methods. ## Configure Spring Security Authentication Manager The Spring Security interface Authentication Manager is responsible for passing requests through a chain of Authentication Provider objects. To secure calls to flow components, you must add the configured `authenticationManager` to the application context. The following example defines roles with different levels of access to protected processors: ```xml ``` The following example references the previously defined `authenticationManager` to allow only users with `ROLE_ADMIN` roles in the `requiredAuthorities` field to access the operation: ```xml ``` ## Configure Secure Components in Asynchronous Systems Spring Security is useful for asynchronous systems because to set the authentication on more than one thread you have to add a security property to the security provider. In the following example, the value `MODE_GLOBAL` is the security property added: ```xml ``` --- product: Mule Runtime version: 4.11 keywords: anypoint studio, flow, redelivery, policy --- # Configure a Redelivery Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A redelivery policy is a filter that helps you conserve resources by limiting the number of times the Mule runtime engine (Mule) executes messages that generate errors. You can add a redelivery policy to any source in a flow. When you add a redelivery policy to a flow’s source, Mule evaluates the received data before it executes the flow’s components. If a message delivery fails a specified number of times, the redelivery policy prevents the flow from processing the received data and raises a REDELIVERY\_EXHAUSTED error. ## Redelivery Policy Configuration Parameters
FieldTypeDefault ValueDescription

Max Redelivery Count

Number

5

Maximum number of times that a message can be redelivered to the flow and processed unsuccessfully before raising a MULE:REDELIVERY_EXHAUSTED error.

Use Secure Hash

Boolean

True

Indicates whether to use a secure hash algorithm to identify a redelivered message.

Message Digest Algorithm

String

SHA-256

Secure hashing algorithm to use for the message. If the payload of the message is a Java object, Mule ignores the Message Digest Algorithm value and returns the value that the payload’s hashCode() returned.

ID Expression

Expression

-

Defines one or more expressions that determine when a message has been redelivered. This property can be set only if the value of Use Secure Hash is False.

Object Store

String

Object Store created by Mule’s default ObjectStoreManager. Nonpersistent, with an entryTtl of 300 seconds and an expirationInterval of 6 seconds.

Object Store in which the redelivery counter for each message is stored. You can configure the Object Store as a reference or an inner element.

For information, see the Object Store connector documentation.

## How the Redelivery Policy Works Each time the source receives a new message, Mule identifies the message by generating its key. - If the processing flow causes an exception, Mule increments the counter associated with the message key. When the counter reaches a value greater than the configured **maxRedeliveryCount** value, Mule throws a MULE:REDELIVERY\_EXHAUSTED error. - If the processing flow does not cause an exception, its counter is reset. ## Errors - MULE:REDELIVERY\_EXHAUSTED Thrown when the number of executions that raise an error is greater than the configured **maxRedeliveryCount** value. ## Example In this example, Mule logs an error with a `Redelivery exhausted in http listener` message when the **maxRedeliveryCount** of 2 is exceeded: ```xml ``` ## See Also - [Mule Overview](https://docs.mulesoft.com/mule-runtime/4.11/) - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/4.11/flow-component) --- product: Mule Runtime version: 4.12 keywords: anypoint studio, flow, redelivery, policy --- # Configure a Redelivery Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A redelivery policy is a filter that helps you conserve resources by limiting the number of times the Mule runtime engine (Mule) executes messages that generate errors. You can add a redelivery policy to any source in a flow. When you add a redelivery policy to a flow’s source, Mule evaluates the received data before it executes the flow’s components. If a message delivery fails a specified number of times, the redelivery policy prevents the flow from processing the received data and raises a REDELIVERY\_EXHAUSTED error. ## Redelivery Policy Configuration Parameters
FieldTypeDefault ValueDescription

Max Redelivery Count

Number

5

Maximum number of times that a message can be redelivered to the flow and processed unsuccessfully before raising a MULE:REDELIVERY_EXHAUSTED error.

Use Secure Hash

Boolean

True

Indicates whether to use a secure hash algorithm to identify a redelivered message.

Message Digest Algorithm

String

SHA-256

Secure hashing algorithm to use for the message. If the payload of the message is a Java object, Mule ignores the Message Digest Algorithm value and returns the value that the payload’s hashCode() returned.

ID Expression

Expression

-

Defines one or more expressions that determine when a message has been redelivered. This property can be set only if the value of Use Secure Hash is False.

Object Store

String

Object Store created by Mule’s default ObjectStoreManager. Nonpersistent, with an entryTtl of 300 seconds and an expirationInterval of 6 seconds.

Object Store in which the redelivery counter for each message is stored. You can configure the Object Store as a reference or an inner element.

For information, see the Object Store connector documentation.

## How the Redelivery Policy Works Each time the source receives a new message, Mule identifies the message by generating its key. - If the processing flow causes an exception, Mule increments the counter associated with the message key. When the counter reaches a value greater than the configured **maxRedeliveryCount** value, Mule throws a MULE:REDELIVERY\_EXHAUSTED error. - If the processing flow does not cause an exception, its counter is reset. ## Errors - MULE:REDELIVERY\_EXHAUSTED Thrown when the number of executions that raise an error is greater than the configured **maxRedeliveryCount** value. ## Example In this example, Mule logs an error with a `Redelivery exhausted in http listener` message when the **maxRedeliveryCount** of 2 is exceeded: ```xml ``` ## See Also - [Mule Overview](https://docs.mulesoft.com/mule-runtime/4.12/) - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/4.12/flow-component) --- product: Mule Runtime version: 4.3 keywords: anypoint studio, flow, redelivery, policy --- # Configure a Redelivery Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A redelivery policy is a filter that helps you conserve resources by limiting the number of times the Mule runtime engine (Mule) executes messages that generate errors. You can add a redelivery policy to any source in a flow. When you add a redelivery policy to a flow’s source, Mule evaluates the received data before it executes the flow’s components. If a message delivery fails a specified number of times, the redelivery policy prevents the flow from processing the received data and raises a REDELIVERY\_EXHAUSTED error. ## Redelivery Policy Configuration Parameters
FieldTypeDefault ValueDescription

Max Redelivery Count

Number

5

Maximum number of times that a message can be redelivered to the flow and processed unsuccessfully before raising a MULE:REDELIVERY_EXHAUSTED error.

Use Secure Hash

Boolean

True

Indicates whether to use a secure hash algorithm to identify a redelivered message.

Message Digest Algorithm

String

SHA-256

Secure hashing algorithm to use for the message. If the payload of the message is a Java object, Mule ignores the Message Digest Algorithm value and returns the value that the payload’s hashCode() returned.

ID Expression

Expression

-

Defines one or more expressions that determine when a message has been redelivered. This property can be set only if the value of Use Secure Hash is False.

Object Store

String

Object Store created by Mule’s default ObjectStoreManager. Nonpersistent, with an entryTtl of 300 seconds and an expirationInterval of 6 seconds.

Object Store in which the redelivery counter for each message is stored. You can configure the Object Store as a reference or an inner element.

For information, see the Object Store connector documentation.

## How the Redelivery Policy Works Each time the source receives a new message, Mule identifies the message by generating its key. - If the processing flow causes an exception, Mule increments the counter associated with the message key. When the counter reaches a value greater than the configured **maxRedeliveryCount** value, Mule throws a MULE:REDELIVERY\_EXHAUSTED error. - If the processing flow does not cause an exception, its counter is reset. ## Errors - MULE:REDELIVERY\_EXHAUSTED Thrown when the number of executions that raise an error is greater than the configured **maxRedeliveryCount** value. ## Example In this example, Mule logs an error with a `Redelivery exhausted in http listener` message when the **maxRedeliveryCount** of 2 is exceeded: ```xml ``` ## See Also - [Mule Overview](https://docs.mulesoft.com/mule-runtime/4.3/) - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/4.3/flow-component) --- product: Mule Runtime version: 4.4 keywords: anypoint studio, flow, redelivery, policy --- # Configure a Redelivery Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A redelivery policy is a filter that helps you conserve resources by limiting the number of times the Mule runtime engine (Mule) executes messages that generate errors. You can add a redelivery policy to any source in a flow. When you add a redelivery policy to a flow’s source, Mule evaluates the received data before it executes the flow’s components. If a message delivery fails a specified number of times, the redelivery policy prevents the flow from processing the received data and raises a REDELIVERY\_EXHAUSTED error. ## Redelivery Policy Configuration Parameters
FieldTypeDefault ValueDescription

Max Redelivery Count

Number

5

Maximum number of times that a message can be redelivered to the flow and processed unsuccessfully before raising a MULE:REDELIVERY_EXHAUSTED error.

Use Secure Hash

Boolean

True

Indicates whether to use a secure hash algorithm to identify a redelivered message.

Message Digest Algorithm

String

SHA-256

Secure hashing algorithm to use for the message. If the payload of the message is a Java object, Mule ignores the Message Digest Algorithm value and returns the value that the payload’s hashCode() returned.

ID Expression

Expression

-

Defines one or more expressions that determine when a message has been redelivered. This property can be set only if the value of Use Secure Hash is False.

Object Store

String

Object Store created by Mule’s default ObjectStoreManager. Nonpersistent, with an entryTtl of 300 seconds and an expirationInterval of 6 seconds.

Object Store in which the redelivery counter for each message is stored. You can configure the Object Store as a reference or an inner element.

For information, see the Object Store connector documentation.

## How the Redelivery Policy Works Each time the source receives a new message, Mule identifies the message by generating its key. - If the processing flow causes an exception, Mule increments the counter associated with the message key. When the counter reaches a value greater than the configured **maxRedeliveryCount** value, Mule throws a MULE:REDELIVERY\_EXHAUSTED error. - If the processing flow does not cause an exception, its counter is reset. ## Errors - MULE:REDELIVERY\_EXHAUSTED Thrown when the number of executions that raise an error is greater than the configured **maxRedeliveryCount** value. ## Example In this example, Mule logs an error with a `Redelivery exhausted in http listener` message when the **maxRedeliveryCount** of 2 is exceeded: ```xml ``` ## See Also - [Mule Overview](https://docs.mulesoft.com/mule-runtime/4.4/) - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/4.4/flow-component) --- product: Mule Runtime version: 4.6 keywords: anypoint studio, flow, redelivery, policy --- # Configure a Redelivery Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A redelivery policy is a filter that helps you conserve resources by limiting the number of times the Mule runtime engine (Mule) executes messages that generate errors. You can add a redelivery policy to any source in a flow. When you add a redelivery policy to a flow’s source, Mule evaluates the received data before it executes the flow’s components. If a message delivery fails a specified number of times, the redelivery policy prevents the flow from processing the received data and raises a REDELIVERY\_EXHAUSTED error. ## Redelivery Policy Configuration Parameters
FieldTypeDefault ValueDescription

Max Redelivery Count

Number

5

Maximum number of times that a message can be redelivered to the flow and processed unsuccessfully before raising a MULE:REDELIVERY_EXHAUSTED error.

Use Secure Hash

Boolean

True

Indicates whether to use a secure hash algorithm to identify a redelivered message.

Message Digest Algorithm

String

SHA-256

Secure hashing algorithm to use for the message. If the payload of the message is a Java object, Mule ignores the Message Digest Algorithm value and returns the value that the payload’s hashCode() returned.

ID Expression

Expression

-

Defines one or more expressions that determine when a message has been redelivered. This property can be set only if the value of Use Secure Hash is False.

Object Store

String

Object Store created by Mule’s default ObjectStoreManager. Nonpersistent, with an entryTtl of 300 seconds and an expirationInterval of 6 seconds.

Object Store in which the redelivery counter for each message is stored. You can configure the Object Store as a reference or an inner element.

For information, see the Object Store connector documentation.

## How the Redelivery Policy Works Each time the source receives a new message, Mule identifies the message by generating its key. - If the processing flow causes an exception, Mule increments the counter associated with the message key. When the counter reaches a value greater than the configured **maxRedeliveryCount** value, Mule throws a MULE:REDELIVERY\_EXHAUSTED error. - If the processing flow does not cause an exception, its counter is reset. ## Errors - MULE:REDELIVERY\_EXHAUSTED Thrown when the number of executions that raise an error is greater than the configured **maxRedeliveryCount** value. ## Example In this example, Mule logs an error with a `Redelivery exhausted in http listener` message when the **maxRedeliveryCount** of 2 is exceeded: ```xml ``` ## See Also - [Mule Overview](https://docs.mulesoft.com/mule-runtime/4.6/) - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/4.6/flow-component) --- product: Mule Runtime version: 4.9 keywords: anypoint studio, flow, redelivery, policy --- # Configure a Redelivery Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A redelivery policy is a filter that helps you conserve resources by limiting the number of times the Mule runtime engine (Mule) executes messages that generate errors. You can add a redelivery policy to any source in a flow. When you add a redelivery policy to a flow’s source, Mule evaluates the received data before it executes the flow’s components. If a message delivery fails a specified number of times, the redelivery policy prevents the flow from processing the received data and raises a REDELIVERY\_EXHAUSTED error. ## Redelivery Policy Configuration Parameters
FieldTypeDefault ValueDescription

Max Redelivery Count

Number

5

Maximum number of times that a message can be redelivered to the flow and processed unsuccessfully before raising a MULE:REDELIVERY_EXHAUSTED error.

Use Secure Hash

Boolean

True

Indicates whether to use a secure hash algorithm to identify a redelivered message.

Message Digest Algorithm

String

SHA-256

Secure hashing algorithm to use for the message. If the payload of the message is a Java object, Mule ignores the Message Digest Algorithm value and returns the value that the payload’s hashCode() returned.

ID Expression

Expression

-

Defines one or more expressions that determine when a message has been redelivered. This property can be set only if the value of Use Secure Hash is False.

Object Store

String

Object Store created by Mule’s default ObjectStoreManager. Nonpersistent, with an entryTtl of 300 seconds and an expirationInterval of 6 seconds.

Object Store in which the redelivery counter for each message is stored. You can configure the Object Store as a reference or an inner element.

For information, see the Object Store connector documentation.

## How the Redelivery Policy Works Each time the source receives a new message, Mule identifies the message by generating its key. - If the processing flow causes an exception, Mule increments the counter associated with the message key. When the counter reaches a value greater than the configured **maxRedeliveryCount** value, Mule throws a MULE:REDELIVERY\_EXHAUSTED error. - If the processing flow does not cause an exception, its counter is reset. ## Errors - MULE:REDELIVERY\_EXHAUSTED Thrown when the number of executions that raise an error is greater than the configured **maxRedeliveryCount** value. ## Example In this example, Mule logs an error with a `Redelivery exhausted in http listener` message when the **maxRedeliveryCount** of 2 is exceeded: ```xml ``` ## See Also - [Mule Overview](https://docs.mulesoft.com/mule-runtime/4.9/) - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/4.9/flow-component) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: anypoint studio, flow, redelivery, policy --- # Configure a Redelivery Policy > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A redelivery policy is a filter that helps you conserve resources by limiting the number of times the Mule runtime engine (Mule) executes messages that generate errors. You can add a redelivery policy to any source in a flow. When you add a redelivery policy to a flow’s source, Mule evaluates the received data before it executes the flow’s components. If a message delivery fails a specified number of times, the redelivery policy prevents the flow from processing the received data and raises a REDELIVERY\_EXHAUSTED error. ## Redelivery Policy Configuration Parameters
FieldTypeDefault ValueDescription

Max Redelivery Count

Number

5

Maximum number of times that a message can be redelivered to the flow and processed unsuccessfully before raising a MULE:REDELIVERY_EXHAUSTED error.

Use Secure Hash

Boolean

True

Indicates whether to use a secure hash algorithm to identify a redelivered message.

Message Digest Algorithm

String

SHA-256

Secure hashing algorithm to use for the message. If the payload of the message is a Java object, Mule ignores the Message Digest Algorithm value and returns the value that the payload’s hashCode() returned.

ID Expression

Expression

-

Defines one or more expressions that determine when a message has been redelivered. This property can be set only if the value of Use Secure Hash is False.

Object Store

String

Object Store created by Mule’s default ObjectStoreManager. Nonpersistent, with an entryTtl of 300 seconds and an expirationInterval of 6 seconds.

Object Store in which the redelivery counter for each message is stored. You can configure the Object Store as a reference or an inner element.

For information, see the Object Store connector documentation.

## How the Redelivery Policy Works Each time the source receives a new message, Mule identifies the message by generating its key. - If the processing flow causes an exception, Mule increments the counter associated with the message key. When the counter reaches a value greater than the configured **maxRedeliveryCount** value, Mule throws a MULE:REDELIVERY\_EXHAUSTED error. - If the processing flow does not cause an exception, its counter is reset. ## Errors - MULE:REDELIVERY\_EXHAUSTED Thrown when the number of executions that raise an error is greater than the configured **maxRedeliveryCount** value. ## Example In this example, Mule logs an error with a `Redelivery exhausted in http listener` message when the **maxRedeliveryCount** of 2 is exceeded: ```xml ``` ## See Also - [Mule Overview](https://docs.mulesoft.com/mule-runtime/latest/) - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/latest/flow-component) --- product: Mule Runtime version: 4.11 --- # Configure Custom Serializers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, Mule runtime engine (Mule) uses ordinary Java serialization. However, you can configure `defaultObjectSerializer` in your Mule application to specify a different serialization mechanism, such as the Kryo serializer or any other custom serializer. Using a custom serializer can improve functionality and performance when Mule executes any of the following processes: - Read from or write to a persistent object store - Read from or write to a persistent VM or JMS queue - Distribute an object through a Mule cluster - Read from or write to an object from a file Customization does not affect the behavior of the Batch module, which always uses the Kryo serializer. ## Compatibility Between Serializers and Mule If you are running Mule runtime engine (Enterprise Edition), you can configure the Kryo serializer to improve performance. If you are using Mule Kernel (Community Edition), you can create a custom serializer using the Serialization API. ## Configure the Kryo Serializer Mule provides an implementation of `ObjectSerializer` that relies on the Kryo framework. Using Kryo provides the following benefits: - Better performance Kryo is much faster than Java serialization. - Support for a wider range of Java types Kryo is not bound by most of the limitations that Java serialization imposes, such as requiring the implementation of the `Serializable` interface, having a default constructor, and so on. - Support for compression You can use either Deflate or GZip compression algorithms. The Kryo namespace enables you to configure this serializer inside your Mule application, without defining a custom Spring bean. The following configuration example sets the default serializer to a Kryo-based one: ```xml ``` You can also include the `compressionMode` XML attribute to configure compression: ```xml ``` ## Create a Custom Serializer Using the Serialization API The open-source Serialization API provides the `ObjectSerializer.java` interface, which enables you to serialize or deserialize objects into a byte array. See [ObjectSerializer.java in GitHub](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/ObjectSerializer.java). The Serialization API has the following features: - Is thread-safe - Passes an OutputStream when serializing and streaming - Allows an InputStream as an input source If you are going to serialize and deserialize in Mule, then you must define the `getInternalProtocol()` method. If you are going to use the serialized object in an external system, define that in the `getExternalProtocol()` method. A [Serialization Protocol](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/SerializationProtocol.java) is the object used to serialize and deserialize. ## Configure a Custom Serializer Configure the default `ObjectSerializer` for your Mule application using the Mule `` tag: ```xml ``` Then, configure the bean in the `serializer.xml` file: ```xml ``` ## Obtain a Configured ObjectSerializer There are different ways to obtain an `ObjectSerializer` inside Java code. Generally, the recommended approach is through dependency injection. The following code example shows you how to get the currently configured `ObjectSerializer`: ```java public class MyClass { @Inject private ObjectSerializer objectSerializer; } ``` If you want a specifically named serializer (whether it’s the default or not), you can access the serializer by name: ```java public class MyClass { @Inject @Named ("mySerializer") private ObjectSerializer objectSerializer; } ``` ## Performance Improvements with Kryo Using Kryo provides particular performance improvements over ordinary Java serialization when you are using these components: - Persistent or clustered object stores - Persistent or distributed VM queues - JMS connector The Kryo serializer without compression is significantly faster than the ordinary Java serializer in all cases. However, compression mode provides an improvement only in high availability (HA) cases. For compression to be worthwhile, the amount of time the CPU spends compressing and decompressing has to be significantly lower than the amount of I/O time saved by reducing the payload size. Because network operations are typically slower than disk operations, and because HA clustering requires node replication (which translates to more traffic), compression is useful only in HA environments. This is not a universal constant. You might be running Mule on machines with slower disks or higher I/O demands in which compression might be worthwhile in any case. Also, tests were performed using 1 MB payloads. If your data stream is larger, compression becomes more worthwhile. ## Considerations When Using Serialization Ensure that you are aware of the following limitations and considerations when using serialization. ### Changing Serializers Requires a Clean Slate Serializers are not interoperable nor interchangeable. That means that if you decide to change the serializer your application uses, ensure that all messages in VM and JMS queues have been consumed and that those queues are empty by the time the new serializer takes over. The Kryo serializer won’t be able to read datagrams written by the Java serializer, and vice-versa. The same thing applies to persistent object stores; you cannot read with one serializer an entry generated with a different serializer. ### Shared VM Connectors Use the Domain’s Default Serializer Domains provide a way to share resources between applications. For example, you can define a VM connector on a domain to allow inter-app communication through VM message queues. However, serializers can be configured only at an application level; they cannot be configured at a domain level. If applications A and B communicate with each other through a VM connector defined on a domain to which both belong, but A serializes using Java and B using Kryo, the serialization works because that particular message is not serialized with the application’s serializer but the one the VM connector uses (the default serializer at domain level). This is good for a "plug-and-play experience", but you won’t be able to realize a performance improvement by having that shared VM connector use Kryo. ### Java 17 Support Starting with version 4.6, Mule runtime supports Java 17, which enforces JPMS. To achieve this capability, Mulesoft introduces several custom serializers that replace the default Kryo frameworks, because the default frameworks rely on mechanisms that break JPMS encapsulation. When migrating to Mule runtime 4.6 and Java 17, the Kryo serializer may not serialize an HTTP Connector certificate. This issue occurs if you are using the Kryo serializer together with an HTTP Connector that has a certificate among its attributes. ### Low Improvement For Local Persistent Object Stores The local persistent object store has no performance advantage because of high contention on the object store implementation. ### Low Improvement For JMS Queues The JSM API specifies that queues need to provide an instance of the `javax.jms.Message` class, the queues don’t work with raw payload objects. The broker client is responsible for serializing the message, not Mule. So, configuring Kryo has minimun impact in this scenario. The only performance gain of using Kryo with JMS is that Mule serializes the MuleSession and uses it as a header in Base64 format. Serializing the MuleSession with Kryo can give you up to a 10% performance increase, but this is primarily attributable to the JMS broker instead of Mule. ### Problematic Types Although Kryo is capable of serializing objects that don’t implement the `Serializable` interface, setting Kryo as the default serializer doesn’t mean that components such as the VM connector, ObjectSerializer, or cluster can handle objects that don’t implement such an interface. Although Kryo can work with those objects, the Java APIs for those components still expect instances of `Serializable` in their method signatures. Ordinary Java serialization fails with an object that doesn’t implement the `Serializable` interface. However, if serialization contains another object which doesn’t implement the Serializable interface, Kryo is likely (but not guaranteed) to succeed. A typical case is a POJO containing an `org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl,` which is in use in the [NetSuite](https://anypoint.mulesoft.com/exchange/?search=netsuite) or [Microsoft Dynamics CRM](https://anypoint.mulesoft.com/exchange/?search=Microsoft+Dynamics+CRM&type=connector) connectors. ## See Also - [Kryo information](https://github.com/EsotericSoftware/kryo) --- product: Mule Runtime version: 4.12 --- # Configure Custom Serializers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, Mule runtime engine (Mule) uses ordinary Java serialization. However, you can configure `defaultObjectSerializer` in your Mule application to specify a different serialization mechanism, such as the Kryo serializer or any other custom serializer. Using a custom serializer can improve functionality and performance when Mule executes any of the following processes: - Read from or write to a persistent object store - Read from or write to a persistent VM or JMS queue - Distribute an object through a Mule cluster - Read from or write to an object from a file Customization does not affect the behavior of the Batch module, which always uses the Kryo serializer. ## Compatibility Between Serializers and Mule If you are running Mule runtime engine (Enterprise Edition), you can configure the Kryo serializer to improve performance. If you are using Mule Kernel (Community Edition), you can create a custom serializer using the Serialization API. ## Configure the Kryo Serializer Mule provides an implementation of `ObjectSerializer` that relies on the Kryo framework. Using Kryo provides the following benefits: - Better performance Kryo is much faster than Java serialization. - Support for a wider range of Java types Kryo is not bound by most of the limitations that Java serialization imposes, such as requiring the implementation of the `Serializable` interface, having a default constructor, and so on. - Support for compression You can use either Deflate or GZip compression algorithms. The Kryo namespace enables you to configure this serializer inside your Mule application, without defining a custom Spring bean. The following configuration example sets the default serializer to a Kryo-based one: ```xml ``` You can also include the `compressionMode` XML attribute to configure compression: ```xml ``` ## Create a Custom Serializer Using the Serialization API The open-source Serialization API provides the `ObjectSerializer.java` interface, which enables you to serialize or deserialize objects into a byte array. See [ObjectSerializer.java in GitHub](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/ObjectSerializer.java). The Serialization API has the following features: - Is thread-safe - Passes an OutputStream when serializing and streaming - Allows an InputStream as an input source If you are going to serialize and deserialize in Mule, then you must define the `getInternalProtocol()` method. If you are going to use the serialized object in an external system, define that in the `getExternalProtocol()` method. A [Serialization Protocol](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/SerializationProtocol.java) is the object used to serialize and deserialize. ## Configure a Custom Serializer Configure the default `ObjectSerializer` for your Mule application using the Mule `` tag: ```xml ``` Then, configure the bean in the `serializer.xml` file: ```xml ``` ## Obtain a Configured ObjectSerializer There are different ways to obtain an `ObjectSerializer` inside Java code. Generally, the recommended approach is through dependency injection. The following code example shows you how to get the currently configured `ObjectSerializer`: ```java public class MyClass { @Inject private ObjectSerializer objectSerializer; } ``` If you want a specifically named serializer (whether it’s the default or not), you can access the serializer by name: ```java public class MyClass { @Inject @Named ("mySerializer") private ObjectSerializer objectSerializer; } ``` ## Performance Improvements with Kryo Using Kryo provides particular performance improvements over ordinary Java serialization when you are using these components: - Persistent or clustered object stores - Persistent or distributed VM queues - JMS connector The Kryo serializer without compression is significantly faster than the ordinary Java serializer in all cases. However, compression mode provides an improvement only in high availability (HA) cases. For compression to be worthwhile, the amount of time the CPU spends compressing and decompressing has to be significantly lower than the amount of I/O time saved by reducing the payload size. Because network operations are typically slower than disk operations, and because HA clustering requires node replication (which translates to more traffic), compression is useful only in HA environments. This is not a universal constant. You might be running Mule on machines with slower disks or higher I/O demands in which compression might be worthwhile in any case. Also, tests were performed using 1 MB payloads. If your data stream is larger, compression becomes more worthwhile. ## Considerations When Using Serialization Ensure that you are aware of the following limitations and considerations when using serialization. ### Changing Serializers Requires a Clean Slate Serializers are not interoperable nor interchangeable. That means that if you decide to change the serializer your application uses, ensure that all messages in VM and JMS queues have been consumed and that those queues are empty by the time the new serializer takes over. The Kryo serializer won’t be able to read datagrams written by the Java serializer, and vice-versa. The same thing applies to persistent object stores; you cannot read with one serializer an entry generated with a different serializer. ### Shared VM Connectors Use the Domain’s Default Serializer Domains provide a way to share resources between applications. For example, you can define a VM connector on a domain to allow inter-app communication through VM message queues. However, serializers can be configured only at an application level; they cannot be configured at a domain level. If applications A and B communicate with each other through a VM connector defined on a domain to which both belong, but A serializes using Java and B using Kryo, the serialization works because that particular message is not serialized with the application’s serializer but the one the VM connector uses (the default serializer at domain level). This is good for a "plug-and-play experience", but you won’t be able to realize a performance improvement by having that shared VM connector use Kryo. ### Java 17 Support Starting with version 4.6, Mule runtime supports Java 17, which enforces JPMS. To achieve this capability, Mulesoft introduces several custom serializers that replace the default Kryo frameworks, because the default frameworks rely on mechanisms that break JPMS encapsulation. When migrating to Mule runtime 4.6 and Java 17, the Kryo serializer may not serialize an HTTP Connector certificate. This issue occurs if you are using the Kryo serializer together with an HTTP Connector that has a certificate among its attributes. ### Low Improvement For Local Persistent Object Stores The local persistent object store has no performance advantage because of high contention on the object store implementation. ### Low Improvement For JMS Queues The JSM API specifies that queues need to provide an instance of the `javax.jms.Message` class, the queues don’t work with raw payload objects. The broker client is responsible for serializing the message, not Mule. So, configuring Kryo has minimun impact in this scenario. The only performance gain of using Kryo with JMS is that Mule serializes the MuleSession and uses it as a header in Base64 format. Serializing the MuleSession with Kryo can give you up to a 10% performance increase, but this is primarily attributable to the JMS broker instead of Mule. ### Problematic Types Although Kryo is capable of serializing objects that don’t implement the `Serializable` interface, setting Kryo as the default serializer doesn’t mean that components such as the VM connector, ObjectSerializer, or cluster can handle objects that don’t implement such an interface. Although Kryo can work with those objects, the Java APIs for those components still expect instances of `Serializable` in their method signatures. Ordinary Java serialization fails with an object that doesn’t implement the `Serializable` interface. However, if serialization contains another object which doesn’t implement the Serializable interface, Kryo is likely (but not guaranteed) to succeed. A typical case is a POJO containing an `org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl,` which is in use in the [NetSuite](https://anypoint.mulesoft.com/exchange/?search=netsuite) or [Microsoft Dynamics CRM](https://anypoint.mulesoft.com/exchange/?search=Microsoft+Dynamics+CRM&type=connector) connectors. ## See Also - [Kryo information](https://github.com/EsotericSoftware/kryo) --- product: Mule Runtime version: 4.3 --- # Configure Custom Serializers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, Mule runtime engine (Mule) uses ordinary Java serialization. However, you can configure `defaultObjectSerializer` in your Mule application to specify a different serialization mechanism, such as the Kryo serializer or any other custom serializer. Using a custom serializer can improve functionality and performance when Mule executes any of the following processes: - Read from or write to a persistent object store - Read from or write to a persistent VM or JMS queue - Distribute an object through a Mule cluster - Read from or write to an object from a file Customization does not affect the behavior of the Batch module, which always uses the Kryo serializer. ## Compatibility Between Serializers and Mule If you are running Mule runtime engine (Enterprise Edition), you can configure the Kryo serializer to improve performance. If you are using Mule Kernel (Community Edition), you can create a custom serializer using the Serialization API. ## Configure the Kryo Serializer Mule provides an implementation of `ObjectSerializer` that relies on the Kryo framework. Using Kryo provides the following benefits: - Better performance Kryo is much faster than Java serialization. - Support for a wider range of Java types Kryo is not bound by most of the limitations that Java serialization imposes, such as requiring the implementation of the `Serializable` interface, having a default constructor, and so on. - Support for compression You can use either Deflate or GZip compression algorithms. The Kryo namespace enables you to configure this serializer inside your Mule application, without defining a custom Spring bean. The following configuration example sets the default serializer to a Kryo-based one: ```xml ``` You can also include the `compressionMode` XML attribute to configure compression: ```xml ``` ## Create a Custom Serializer Using the Serialization API The open-source Serialization API provides the `ObjectSerializer.java` interface, which enables you to serialize or deserialize objects into a byte array. See [ObjectSerializer.java in GitHub](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/ObjectSerializer.java). The Serialization API has the following features: - Is thread-safe - Passes an OutputStream when serializing and streaming - Allows an InputStream as an input source If you are going to serialize and deserialize in Mule, then you must define the `getInternalProtocol()` method. If you are going to use the serialized object in an external system, define that in the `getExternalProtocol()` method. A [Serialization Protocol](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/SerializationProtocol.java) is the object used to serialize and deserialize. ## Configure a Custom Serializer Configure the default `ObjectSerializer` for your Mule application using the Mule `` tag: ```xml ``` Then, configure the bean in the `serializer.xml` file: ```xml ``` ## Obtain a Configured ObjectSerializer There are different ways to obtain an `ObjectSerializer` inside Java code. Generally, the recommended approach is through dependency injection. The following code example shows you how to get the currently configured `ObjectSerializer`: ```java public class MyClass { @Inject private ObjectSerializer objectSerializer; } ``` If you want a specifically named serializer (whether it’s the default or not), you can access the serializer by name: ```java public class MyClass { @Inject @Named ("mySerializer") private ObjectSerializer objectSerializer; } ``` ## Performance Improvements with Kryo Using Kryo provides particular performance improvements over ordinary Java serialization when you are using these components: - Persistent or clustered object stores - Persistent or distributed VM queues - JMS connector The Kryo serializer without compression is significantly faster than the ordinary Java serializer in all cases. However, compression mode provides an improvement only in high availability (HA) cases. For compression to be worthwhile, the amount of time the CPU spends compressing and decompressing has to be significantly lower than the amount of I/O time saved by reducing the payload size. Because network operations are typically slower than disk operations, and because HA clustering requires node replication (which translates to more traffic), compression is useful only in HA environments. This is not a universal constant. You might be running Mule on machines with slower disks or higher I/O demands in which compression might be worthwhile in any case. Also, tests were performed using 1 MB payloads. If your data stream is larger, compression becomes more worthwhile. ## Considerations When Using Serialization Ensure that you are aware of the following limitations and considerations when using serialization. ### Changing Serializers Requires a Clean Slate Serializers are not interoperable nor interchangeable. That means that if you decide to change the serializer your application uses, ensure that all messages in VM and JMS queues have been consumed and that those queues are empty by the time the new serializer takes over. The Kryo serializer won’t be able to read datagrams written by the Java serializer, and vice-versa. The same thing applies to persistent object stores; you cannot read with one serializer an entry generated with a different serializer. ### Shared VM Connectors Use the Domain’s Default Serializer Domains provide a way to share resources between applications. For example, you can define a VM connector on a domain to allow inter-app communication through VM message queues. However, serializers can be configured only at an application level; they cannot be configured at a domain level. If applications A and B communicate with each other through a VM connector defined on a domain to which both belong, but A serializes using Java and B using Kryo, the serialization works because that particular message is not serialized with the application’s serializer but the one the VM connector uses (the default serializer at domain level). This is good for a "plug-and-play experience," but you won’t be able to realize a performance improvement by having that shared VM connector use Kryo. ### Low Improvement For Local Persistent Object Stores The local persistent object store has no performance advantage because of high contention on the object store implementation. ### Low Improvement For JMS Queues The JSM API specifies that queues need to provide an instance of the `javax.jms.Message` class, the queues don’t work with raw payload objects. The broker client is responsible for serializing the message, not Mule. So, configuring Kryo has minimun impact in this scenario. The only performance gain of using Kryo with JMS is that Mule serializes the MuleSession and uses it as a header in Base64 format. Serializing the MuleSession with Kryo can give you up to a 10% performance increase, but this is primarily attributable to the JMS broker instead of Mule. ### Problematic Types Although Kryo is capable of serializing objects that don’t implement the `Serializable` interface, setting Kryo as the default serializer doesn’t mean that components such as the VM connector, ObjectSerializer, or cluster can handle objects that don’t implement such an interface. Although Kryo can work with those objects, the Java APIs for those components still expect instances of `Serializable` in their method signatures. Ordinary Java serialization fails with an object that doesn’t implement the `Serializable` interface. However, if serialization contains another object which doesn’t implement the Serializable interface, Kryo is likely (but not guaranteed) to succeed. A typical case is a POJO containing an `org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl,` which is in use in the [NetSuite](https://anypoint.mulesoft.com/exchange/?search=netsuite) or [Microsoft Dynamics CRM](https://anypoint.mulesoft.com/exchange/?search=Microsoft+Dynamics+CRM&type=connector) connectors. ## See Also - [Kryo information](https://github.com/EsotericSoftware/kryo) --- product: Mule Runtime version: 4.4 --- # Configure Custom Serializers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, Mule runtime engine (Mule) uses ordinary Java serialization. However, you can configure `defaultObjectSerializer` in your Mule application to specify a different serialization mechanism, such as the Kryo serializer or any other custom serializer. Using a custom serializer can improve functionality and performance when Mule executes any of the following processes: - Read from or write to a persistent object store - Read from or write to a persistent VM or JMS queue - Distribute an object through a Mule cluster - Read from or write to an object from a file Customization does not affect the behavior of the Batch module, which always uses the Kryo serializer. ## Compatibility Between Serializers and Mule If you are running Mule runtime engine (Enterprise Edition), you can configure the Kryo serializer to improve performance. If you are using Mule Kernel (Community Edition), you can create a custom serializer using the Serialization API. ## Configure the Kryo Serializer Mule provides an implementation of `ObjectSerializer` that relies on the Kryo framework. Using Kryo provides the following benefits: - Better performance Kryo is much faster than Java serialization. - Support for a wider range of Java types Kryo is not bound by most of the limitations that Java serialization imposes, such as requiring the implementation of the `Serializable` interface, having a default constructor, and so on. - Support for compression You can use either Deflate or GZip compression algorithms. The Kryo namespace enables you to configure this serializer inside your Mule application, without defining a custom Spring bean. The following configuration example sets the default serializer to a Kryo-based one: ```xml ``` You can also include the `compressionMode` XML attribute to configure compression: ```xml ``` ## Create a Custom Serializer Using the Serialization API The open-source Serialization API provides the `ObjectSerializer.java` interface, which enables you to serialize or deserialize objects into a byte array. See [ObjectSerializer.java in GitHub](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/ObjectSerializer.java). The Serialization API has the following features: - Is thread-safe - Passes an OutputStream when serializing and streaming - Allows an InputStream as an input source If you are going to serialize and deserialize in Mule, then you must define the `getInternalProtocol()` method. If you are going to use the serialized object in an external system, define that in the `getExternalProtocol()` method. A [Serialization Protocol](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/SerializationProtocol.java) is the object used to serialize and deserialize. ## Configure a Custom Serializer Configure the default `ObjectSerializer` for your Mule application using the Mule `` tag: ```xml ``` Then, configure the bean in the `serializer.xml` file: ```xml ``` ## Obtain a Configured ObjectSerializer There are different ways to obtain an `ObjectSerializer` inside Java code. Generally, the recommended approach is through dependency injection. The following code example shows you how to get the currently configured `ObjectSerializer`: ```java public class MyClass { @Inject private ObjectSerializer objectSerializer; } ``` If you want a specifically named serializer (whether it’s the default or not), you can access the serializer by name: ```java public class MyClass { @Inject @Named ("mySerializer") private ObjectSerializer objectSerializer; } ``` ## Performance Improvements with Kryo Using Kryo provides particular performance improvements over ordinary Java serialization when you are using these components: - Persistent or clustered object stores - Persistent or distributed VM queues - JMS connector The Kryo serializer without compression is significantly faster than the ordinary Java serializer in all cases. However, compression mode provides an improvement only in high availability (HA) cases. For compression to be worthwhile, the amount of time the CPU spends compressing and decompressing has to be significantly lower than the amount of I/O time saved by reducing the payload size. Because network operations are typically slower than disk operations, and because HA clustering requires node replication (which translates to more traffic), compression is useful only in HA environments. This is not a universal constant. You might be running Mule on machines with slower disks or higher I/O demands in which compression might be worthwhile in any case. Also, tests were performed using 1 MB payloads. If your data stream is larger, compression becomes more worthwhile. ## Considerations When Using Serialization Ensure that you are aware of the following limitations and considerations when using serialization. ### Changing Serializers Requires a Clean Slate Serializers are not interoperable nor interchangeable. That means that if you decide to change the serializer your application uses, ensure that all messages in VM and JMS queues have been consumed and that those queues are empty by the time the new serializer takes over. The Kryo serializer won’t be able to read datagrams written by the Java serializer, and vice-versa. The same thing applies to persistent object stores; you cannot read with one serializer an entry generated with a different serializer. ### Shared VM Connectors Use the Domain’s Default Serializer Domains provide a way to share resources between applications. For example, you can define a VM connector on a domain to allow inter-app communication through VM message queues. However, serializers can be configured only at an application level; they cannot be configured at a domain level. If applications A and B communicate with each other through a VM connector defined on a domain to which both belong, but A serializes using Java and B using Kryo, the serialization works because that particular message is not serialized with the application’s serializer but the one the VM connector uses (the default serializer at domain level). This is good for a "plug-and-play experience," but you won’t be able to realize a performance improvement by having that shared VM connector use Kryo. ### Low Improvement For Local Persistent Object Stores The local persistent object store has no performance advantage because of high contention on the object store implementation. ### Low Improvement For JMS Queues The JSM API specifies that queues need to provide an instance of the `javax.jms.Message` class, the queues don’t work with raw payload objects. The broker client is responsible for serializing the message, not Mule. So, configuring Kryo has minimun impact in this scenario. The only performance gain of using Kryo with JMS is that Mule serializes the MuleSession and uses it as a header in Base64 format. Serializing the MuleSession with Kryo can give you up to a 10% performance increase, but this is primarily attributable to the JMS broker instead of Mule. ### Problematic Types Although Kryo is capable of serializing objects that don’t implement the `Serializable` interface, setting Kryo as the default serializer doesn’t mean that components such as the VM connector, ObjectSerializer, or cluster can handle objects that don’t implement such an interface. Although Kryo can work with those objects, the Java APIs for those components still expect instances of `Serializable` in their method signatures. Ordinary Java serialization fails with an object that doesn’t implement the `Serializable` interface. However, if serialization contains another object which doesn’t implement the Serializable interface, Kryo is likely (but not guaranteed) to succeed. A typical case is a POJO containing an `org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl,` which is in use in the [NetSuite](https://anypoint.mulesoft.com/exchange/?search=netsuite) or [Microsoft Dynamics CRM](https://anypoint.mulesoft.com/exchange/?search=Microsoft+Dynamics+CRM&type=connector) connectors. ## See Also - [Kryo information](https://github.com/EsotericSoftware/kryo) --- product: Mule Runtime version: 4.6 --- # Configure Custom Serializers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, Mule runtime engine (Mule) uses ordinary Java serialization. However, you can configure `defaultObjectSerializer` in your Mule application to specify a different serialization mechanism, such as the Kryo serializer or any other custom serializer. Using a custom serializer can improve functionality and performance when Mule executes any of the following processes: - Read from or write to a persistent object store - Read from or write to a persistent VM or JMS queue - Distribute an object through a Mule cluster - Read from or write to an object from a file Customization does not affect the behavior of the Batch module, which always uses the Kryo serializer. ## Compatibility Between Serializers and Mule If you are running Mule runtime engine (Enterprise Edition), you can configure the Kryo serializer to improve performance. If you are using Mule Kernel (Community Edition), you can create a custom serializer using the Serialization API. ## Configure the Kryo Serializer Mule provides an implementation of `ObjectSerializer` that relies on the Kryo framework. Using Kryo provides the following benefits: - Better performance Kryo is much faster than Java serialization. - Support for a wider range of Java types Kryo is not bound by most of the limitations that Java serialization imposes, such as requiring the implementation of the `Serializable` interface, having a default constructor, and so on. - Support for compression You can use either Deflate or GZip compression algorithms. The Kryo namespace enables you to configure this serializer inside your Mule application, without defining a custom Spring bean. The following configuration example sets the default serializer to a Kryo-based one: ```xml ``` You can also include the `compressionMode` XML attribute to configure compression: ```xml ``` ## Create a Custom Serializer Using the Serialization API The open-source Serialization API provides the `ObjectSerializer.java` interface, which enables you to serialize or deserialize objects into a byte array. See [ObjectSerializer.java in GitHub](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/ObjectSerializer.java). The Serialization API has the following features: - Is thread-safe - Passes an OutputStream when serializing and streaming - Allows an InputStream as an input source If you are going to serialize and deserialize in Mule, then you must define the `getInternalProtocol()` method. If you are going to use the serialized object in an external system, define that in the `getExternalProtocol()` method. A [Serialization Protocol](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/SerializationProtocol.java) is the object used to serialize and deserialize. ## Configure a Custom Serializer Configure the default `ObjectSerializer` for your Mule application using the Mule `` tag: ```xml ``` Then, configure the bean in the `serializer.xml` file: ```xml ``` ## Obtain a Configured ObjectSerializer There are different ways to obtain an `ObjectSerializer` inside Java code. Generally, the recommended approach is through dependency injection. The following code example shows you how to get the currently configured `ObjectSerializer`: ```java public class MyClass { @Inject private ObjectSerializer objectSerializer; } ``` If you want a specifically named serializer (whether it’s the default or not), you can access the serializer by name: ```java public class MyClass { @Inject @Named ("mySerializer") private ObjectSerializer objectSerializer; } ``` ## Performance Improvements with Kryo Using Kryo provides particular performance improvements over ordinary Java serialization when you are using these components: - Persistent or clustered object stores - Persistent or distributed VM queues - JMS connector The Kryo serializer without compression is significantly faster than the ordinary Java serializer in all cases. However, compression mode provides an improvement only in high availability (HA) cases. For compression to be worthwhile, the amount of time the CPU spends compressing and decompressing has to be significantly lower than the amount of I/O time saved by reducing the payload size. Because network operations are typically slower than disk operations, and because HA clustering requires node replication (which translates to more traffic), compression is useful only in HA environments. This is not a universal constant. You might be running Mule on machines with slower disks or higher I/O demands in which compression might be worthwhile in any case. Also, tests were performed using 1 MB payloads. If your data stream is larger, compression becomes more worthwhile. ## Considerations When Using Serialization Ensure that you are aware of the following limitations and considerations when using serialization. ### Changing Serializers Requires a Clean Slate Serializers are not interoperable nor interchangeable. That means that if you decide to change the serializer your application uses, ensure that all messages in VM and JMS queues have been consumed and that those queues are empty by the time the new serializer takes over. The Kryo serializer won’t be able to read datagrams written by the Java serializer, and vice-versa. The same thing applies to persistent object stores; you cannot read with one serializer an entry generated with a different serializer. ### Shared VM Connectors Use the Domain’s Default Serializer Domains provide a way to share resources between applications. For example, you can define a VM connector on a domain to allow inter-app communication through VM message queues. However, serializers can be configured only at an application level; they cannot be configured at a domain level. If applications A and B communicate with each other through a VM connector defined on a domain to which both belong, but A serializes using Java and B using Kryo, the serialization works because that particular message is not serialized with the application’s serializer but the one the VM connector uses (the default serializer at domain level). This is good for a "plug-and-play experience", but you won’t be able to realize a performance improvement by having that shared VM connector use Kryo. ### Java 17 Support Starting with version 4.6, Mule runtime supports Java 17, which enforces JPMS. To achieve this capability, Mulesoft introduces several custom serializers that replace the default Kryo frameworks, because the default frameworks rely on mechanisms that break JPMS encapsulation. When migrating to Mule runtime 4.6 and Java 17, the Kryo serializer may not serialize an HTTP Connector certificate. This issue occurs if you are using the Kryo serializer together with an HTTP Connector that has a certificate among its attributes. ### Low Improvement For Local Persistent Object Stores The local persistent object store has no performance advantage because of high contention on the object store implementation. ### Low Improvement For JMS Queues The JSM API specifies that queues need to provide an instance of the `javax.jms.Message` class, the queues don’t work with raw payload objects. The broker client is responsible for serializing the message, not Mule. So, configuring Kryo has minimun impact in this scenario. The only performance gain of using Kryo with JMS is that Mule serializes the MuleSession and uses it as a header in Base64 format. Serializing the MuleSession with Kryo can give you up to a 10% performance increase, but this is primarily attributable to the JMS broker instead of Mule. ### Problematic Types Although Kryo is capable of serializing objects that don’t implement the `Serializable` interface, setting Kryo as the default serializer doesn’t mean that components such as the VM connector, ObjectSerializer, or cluster can handle objects that don’t implement such an interface. Although Kryo can work with those objects, the Java APIs for those components still expect instances of `Serializable` in their method signatures. Ordinary Java serialization fails with an object that doesn’t implement the `Serializable` interface. However, if serialization contains another object which doesn’t implement the Serializable interface, Kryo is likely (but not guaranteed) to succeed. A typical case is a POJO containing an `org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl,` which is in use in the [NetSuite](https://anypoint.mulesoft.com/exchange/?search=netsuite) or [Microsoft Dynamics CRM](https://anypoint.mulesoft.com/exchange/?search=Microsoft+Dynamics+CRM&type=connector) connectors. ## See Also - [Kryo information](https://github.com/EsotericSoftware/kryo) --- product: Mule Runtime version: 4.9 --- # Configure Custom Serializers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, Mule runtime engine (Mule) uses ordinary Java serialization. However, you can configure `defaultObjectSerializer` in your Mule application to specify a different serialization mechanism, such as the Kryo serializer or any other custom serializer. Using a custom serializer can improve functionality and performance when Mule executes any of the following processes: - Read from or write to a persistent object store - Read from or write to a persistent VM or JMS queue - Distribute an object through a Mule cluster - Read from or write to an object from a file Customization does not affect the behavior of the Batch module, which always uses the Kryo serializer. ## Compatibility Between Serializers and Mule If you are running Mule runtime engine (Enterprise Edition), you can configure the Kryo serializer to improve performance. If you are using Mule Kernel (Community Edition), you can create a custom serializer using the Serialization API. ## Configure the Kryo Serializer Mule provides an implementation of `ObjectSerializer` that relies on the Kryo framework. Using Kryo provides the following benefits: - Better performance Kryo is much faster than Java serialization. - Support for a wider range of Java types Kryo is not bound by most of the limitations that Java serialization imposes, such as requiring the implementation of the `Serializable` interface, having a default constructor, and so on. - Support for compression You can use either Deflate or GZip compression algorithms. The Kryo namespace enables you to configure this serializer inside your Mule application, without defining a custom Spring bean. The following configuration example sets the default serializer to a Kryo-based one: ```xml ``` You can also include the `compressionMode` XML attribute to configure compression: ```xml ``` ## Create a Custom Serializer Using the Serialization API The open-source Serialization API provides the `ObjectSerializer.java` interface, which enables you to serialize or deserialize objects into a byte array. See [ObjectSerializer.java in GitHub](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/ObjectSerializer.java). The Serialization API has the following features: - Is thread-safe - Passes an OutputStream when serializing and streaming - Allows an InputStream as an input source If you are going to serialize and deserialize in Mule, then you must define the `getInternalProtocol()` method. If you are going to use the serialized object in an external system, define that in the `getExternalProtocol()` method. A [Serialization Protocol](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/SerializationProtocol.java) is the object used to serialize and deserialize. ## Configure a Custom Serializer Configure the default `ObjectSerializer` for your Mule application using the Mule `` tag: ```xml ``` Then, configure the bean in the `serializer.xml` file: ```xml ``` ## Obtain a Configured ObjectSerializer There are different ways to obtain an `ObjectSerializer` inside Java code. Generally, the recommended approach is through dependency injection. The following code example shows you how to get the currently configured `ObjectSerializer`: ```java public class MyClass { @Inject private ObjectSerializer objectSerializer; } ``` If you want a specifically named serializer (whether it’s the default or not), you can access the serializer by name: ```java public class MyClass { @Inject @Named ("mySerializer") private ObjectSerializer objectSerializer; } ``` ## Performance Improvements with Kryo Using Kryo provides particular performance improvements over ordinary Java serialization when you are using these components: - Persistent or clustered object stores - Persistent or distributed VM queues - JMS connector The Kryo serializer without compression is significantly faster than the ordinary Java serializer in all cases. However, compression mode provides an improvement only in high availability (HA) cases. For compression to be worthwhile, the amount of time the CPU spends compressing and decompressing has to be significantly lower than the amount of I/O time saved by reducing the payload size. Because network operations are typically slower than disk operations, and because HA clustering requires node replication (which translates to more traffic), compression is useful only in HA environments. This is not a universal constant. You might be running Mule on machines with slower disks or higher I/O demands in which compression might be worthwhile in any case. Also, tests were performed using 1 MB payloads. If your data stream is larger, compression becomes more worthwhile. ## Considerations When Using Serialization Ensure that you are aware of the following limitations and considerations when using serialization. ### Changing Serializers Requires a Clean Slate Serializers are not interoperable nor interchangeable. That means that if you decide to change the serializer your application uses, ensure that all messages in VM and JMS queues have been consumed and that those queues are empty by the time the new serializer takes over. The Kryo serializer won’t be able to read datagrams written by the Java serializer, and vice-versa. The same thing applies to persistent object stores; you cannot read with one serializer an entry generated with a different serializer. ### Shared VM Connectors Use the Domain’s Default Serializer Domains provide a way to share resources between applications. For example, you can define a VM connector on a domain to allow inter-app communication through VM message queues. However, serializers can be configured only at an application level; they cannot be configured at a domain level. If applications A and B communicate with each other through a VM connector defined on a domain to which both belong, but A serializes using Java and B using Kryo, the serialization works because that particular message is not serialized with the application’s serializer but the one the VM connector uses (the default serializer at domain level). This is good for a "plug-and-play experience", but you won’t be able to realize a performance improvement by having that shared VM connector use Kryo. ### Java 17 Support Starting with version 4.6, Mule runtime supports Java 17, which enforces JPMS. To achieve this capability, Mulesoft introduces several custom serializers that replace the default Kryo frameworks, because the default frameworks rely on mechanisms that break JPMS encapsulation. When migrating to Mule runtime 4.6 and Java 17, the Kryo serializer may not serialize an HTTP Connector certificate. This issue occurs if you are using the Kryo serializer together with an HTTP Connector that has a certificate among its attributes. ### Low Improvement For Local Persistent Object Stores The local persistent object store has no performance advantage because of high contention on the object store implementation. ### Low Improvement For JMS Queues The JSM API specifies that queues need to provide an instance of the `javax.jms.Message` class, the queues don’t work with raw payload objects. The broker client is responsible for serializing the message, not Mule. So, configuring Kryo has minimun impact in this scenario. The only performance gain of using Kryo with JMS is that Mule serializes the MuleSession and uses it as a header in Base64 format. Serializing the MuleSession with Kryo can give you up to a 10% performance increase, but this is primarily attributable to the JMS broker instead of Mule. ### Problematic Types Although Kryo is capable of serializing objects that don’t implement the `Serializable` interface, setting Kryo as the default serializer doesn’t mean that components such as the VM connector, ObjectSerializer, or cluster can handle objects that don’t implement such an interface. Although Kryo can work with those objects, the Java APIs for those components still expect instances of `Serializable` in their method signatures. Ordinary Java serialization fails with an object that doesn’t implement the `Serializable` interface. However, if serialization contains another object which doesn’t implement the Serializable interface, Kryo is likely (but not guaranteed) to succeed. A typical case is a POJO containing an `org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl,` which is in use in the [NetSuite](https://anypoint.mulesoft.com/exchange/?search=netsuite) or [Microsoft Dynamics CRM](https://anypoint.mulesoft.com/exchange/?search=Microsoft+Dynamics+CRM&type=connector) connectors. ## See Also - [Kryo information](https://github.com/EsotericSoftware/kryo) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Configure Custom Serializers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, Mule runtime engine (Mule) uses ordinary Java serialization. However, you can configure `defaultObjectSerializer` in your Mule application to specify a different serialization mechanism, such as the Kryo serializer or any other custom serializer. Using a custom serializer can improve functionality and performance when Mule executes any of the following processes: - Read from or write to a persistent object store - Read from or write to a persistent VM or JMS queue - Distribute an object through a Mule cluster - Read from or write to an object from a file Customization does not affect the behavior of the Batch module, which always uses the Kryo serializer. ## Compatibility Between Serializers and Mule If you are running Mule runtime engine (Enterprise Edition), you can configure the Kryo serializer to improve performance. If you are using Mule Kernel (Community Edition), you can create a custom serializer using the Serialization API. ## Configure the Kryo Serializer Mule provides an implementation of `ObjectSerializer` that relies on the Kryo framework. Using Kryo provides the following benefits: - Better performance Kryo is much faster than Java serialization. - Support for a wider range of Java types Kryo is not bound by most of the limitations that Java serialization imposes, such as requiring the implementation of the `Serializable` interface, having a default constructor, and so on. - Support for compression You can use either Deflate or GZip compression algorithms. The Kryo namespace enables you to configure this serializer inside your Mule application, without defining a custom Spring bean. The following configuration example sets the default serializer to a Kryo-based one: ```xml ``` You can also include the `compressionMode` XML attribute to configure compression: ```xml ``` ## Create a Custom Serializer Using the Serialization API The open-source Serialization API provides the `ObjectSerializer.java` interface, which enables you to serialize or deserialize objects into a byte array. See [ObjectSerializer.java in GitHub](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/ObjectSerializer.java). The Serialization API has the following features: - Is thread-safe - Passes an OutputStream when serializing and streaming - Allows an InputStream as an input source If you are going to serialize and deserialize in Mule, then you must define the `getInternalProtocol()` method. If you are going to use the serialized object in an external system, define that in the `getExternalProtocol()` method. A [Serialization Protocol](https://github.com/mulesoft/mule-api/blob/master/src/main/java/org/mule/runtime/api/serialization/SerializationProtocol.java) is the object used to serialize and deserialize. ## Configure a Custom Serializer Configure the default `ObjectSerializer` for your Mule application using the Mule `` tag: ```xml ``` Then, configure the bean in the `serializer.xml` file: ```xml ``` ## Obtain a Configured ObjectSerializer There are different ways to obtain an `ObjectSerializer` inside Java code. Generally, the recommended approach is through dependency injection. The following code example shows you how to get the currently configured `ObjectSerializer`: ```java public class MyClass { @Inject private ObjectSerializer objectSerializer; } ``` If you want a specifically named serializer (whether it’s the default or not), you can access the serializer by name: ```java public class MyClass { @Inject @Named ("mySerializer") private ObjectSerializer objectSerializer; } ``` ## Performance Improvements with Kryo Using Kryo provides particular performance improvements over ordinary Java serialization when you are using these components: - Persistent or clustered object stores - Persistent or distributed VM queues - JMS connector The Kryo serializer without compression is significantly faster than the ordinary Java serializer in all cases. However, compression mode provides an improvement only in high availability (HA) cases. For compression to be worthwhile, the amount of time the CPU spends compressing and decompressing has to be significantly lower than the amount of I/O time saved by reducing the payload size. Because network operations are typically slower than disk operations, and because HA clustering requires node replication (which translates to more traffic), compression is useful only in HA environments. This is not a universal constant. You might be running Mule on machines with slower disks or higher I/O demands in which compression might be worthwhile in any case. Also, tests were performed using 1 MB payloads. If your data stream is larger, compression becomes more worthwhile. ## Considerations When Using Serialization Ensure that you are aware of the following limitations and considerations when using serialization. ### Changing Serializers Requires a Clean Slate Serializers are not interoperable nor interchangeable. That means that if you decide to change the serializer your application uses, ensure that all messages in VM and JMS queues have been consumed and that those queues are empty by the time the new serializer takes over. The Kryo serializer won’t be able to read datagrams written by the Java serializer, and vice-versa. The same thing applies to persistent object stores; you cannot read with one serializer an entry generated with a different serializer. ### Shared VM Connectors Use the Domain’s Default Serializer Domains provide a way to share resources between applications. For example, you can define a VM connector on a domain to allow inter-app communication through VM message queues. However, serializers can be configured only at an application level; they cannot be configured at a domain level. If applications A and B communicate with each other through a VM connector defined on a domain to which both belong, but A serializes using Java and B using Kryo, the serialization works because that particular message is not serialized with the application’s serializer but the one the VM connector uses (the default serializer at domain level). This is good for a "plug-and-play experience", but you won’t be able to realize a performance improvement by having that shared VM connector use Kryo. ### Java 17 Support Starting with version 4.6, Mule runtime supports Java 17, which enforces JPMS. To achieve this capability, Mulesoft introduces several custom serializers that replace the default Kryo frameworks, because the default frameworks rely on mechanisms that break JPMS encapsulation. When migrating to Mule runtime 4.6 and Java 17, the Kryo serializer may not serialize an HTTP Connector certificate. This issue occurs if you are using the Kryo serializer together with an HTTP Connector that has a certificate among its attributes. ### Low Improvement For Local Persistent Object Stores The local persistent object store has no performance advantage because of high contention on the object store implementation. ### Low Improvement For JMS Queues The JSM API specifies that queues need to provide an instance of the `javax.jms.Message` class, the queues don’t work with raw payload objects. The broker client is responsible for serializing the message, not Mule. So, configuring Kryo has minimun impact in this scenario. The only performance gain of using Kryo with JMS is that Mule serializes the MuleSession and uses it as a header in Base64 format. Serializing the MuleSession with Kryo can give you up to a 10% performance increase, but this is primarily attributable to the JMS broker instead of Mule. ### Problematic Types Although Kryo is capable of serializing objects that don’t implement the `Serializable` interface, setting Kryo as the default serializer doesn’t mean that components such as the VM connector, ObjectSerializer, or cluster can handle objects that don’t implement such an interface. Although Kryo can work with those objects, the Java APIs for those components still expect instances of `Serializable` in their method signatures. Ordinary Java serialization fails with an object that doesn’t implement the `Serializable` interface. However, if serialization contains another object which doesn’t implement the Serializable interface, Kryo is likely (but not guaranteed) to succeed. A typical case is a POJO containing an `org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl,` which is in use in the [NetSuite](https://anypoint.mulesoft.com/exchange/?search=netsuite) or [Microsoft Dynamics CRM](https://anypoint.mulesoft.com/exchange/?search=Microsoft+Dynamics+CRM&type=connector) connectors. ## See Also - [Kryo information](https://github.com/EsotericSoftware/kryo) --- product: Mule Runtime version: 4.11 --- # Configure Default Events Tracking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Because event tracking requires processing and network overhead to aggregate and store the events that Mule runtime engine generates, it is disabled by default. However, you can enable and configure default events tracking for connectors or message processors that support it, at one of two levels: - At the flow level - At the message processor (connector or component) level, which takes precedence over the flow-level setting After you enable event tracking, customize the transaction ID to identify specific tracked events so that you can analyze them at runtime. ## Flow-Level Event Tracking Use this option in the [Flow](https://docs.mulesoft.com/mule-runtime/4.11/flow-component) component to enable default event tracking for all elements in a flow that support event tracking. You can disable tracking for specific processors or connectors to override the flow level setting. Steps to enable default events tracking for all components in a flow: 1. Select your flow component to open the properties view. 2. Enable default business events using either the UI or XML: - In the UI, select **Enable default events tracking**: ![A flow configuration interface for JMS processing with options to enable event tracking](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-business-event-flow.png) - In the XML, add attribute `tracking:enable-default-events="true"` to the `flow` element: ```xml ``` 3. Save your settings. ## Message Processor-Level Event Tracking You can enable event tracking on individual connectors and Mule components that support event tracking. The following Mule components provide a configuration for enabling business events: - [Choice](https://docs.mulesoft.com/mule-runtime/4.11/choice-router-concept) router - [Round Robin](https://docs.mulesoft.com/mule-runtime/4.11/round-robin) router - [First Successful](https://docs.mulesoft.com/mule-runtime/4.11/first-successful) router Steps to enable default events tracking for an individual component: 1. Open the connector or component properties view. 2. Enable default business events using any of the following options: - In the UI, select **Enable default events tracking**: ![A business event tracking within a choice component](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-business-event-component.png) - In the XML, add attribute `tracking:enable-default-events="true"` inside your component element: ```xml ... ... ``` 3. Save your settings. ## Customize the Transaction ID The Set Transaction Id component enables you to set an identifier for all tracked events so that meaningful information, such as an order number, is displayed for a transaction when analyzing tracked events at runtime, whether using Anypoint Runtime Manager or CloudHub. The transaction ID supports DataWeave expressions, which enables you to create an ID dynamically and include information related to the event into the ID. Follow these steps to set a transaction ID either in Anypoint Studio or by editing the configuration XML: - In the Studio UI: 1. Drag the **Set Transaction Id** component to your flow. 2. In the **Set Transaction ID** configuration screen, set an ID value for the **Transaction ID** field: ![Configuration for setting a transaction ID in a Mule flow](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-custom-transaction-id.png) - In the XML editor: - Add a child element to the `flow` element: ```xml ... ... ``` ## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/4.11/business-events) --- product: Mule Runtime version: 4.12 --- # Configure Default Events Tracking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Because event tracking requires processing and network overhead to aggregate and store the events that Mule runtime engine generates, it is disabled by default. However, you can enable and configure default events tracking for connectors or message processors that support it, at one of two levels: - At the flow level - At the message processor (connector or component) level, which takes precedence over the flow-level setting After you enable event tracking, customize the transaction ID to identify specific tracked events so that you can analyze them at runtime. ## Flow-Level Event Tracking Use this option in the [Flow](https://docs.mulesoft.com/mule-runtime/4.12/flow-component) component to enable default event tracking for all elements in a flow that support event tracking. You can disable tracking for specific processors or connectors to override the flow level setting. Steps to enable default events tracking for all components in a flow: 1. Select your flow component to open the properties view. 2. Enable default business events using either the UI or XML: - In the UI, select **Enable default events tracking**: ![A flow configuration interface for JMS processing with options to enable event tracking](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-business-event-flow.png) - In the XML, add attribute `tracking:enable-default-events="true"` to the `flow` element: ```xml ``` 3. Save your settings. ## Message Processor-Level Event Tracking You can enable event tracking on individual connectors and Mule components that support event tracking. The following Mule components provide a configuration for enabling business events: - [Choice](https://docs.mulesoft.com/mule-runtime/4.12/choice-router-concept) router - [Round Robin](https://docs.mulesoft.com/mule-runtime/4.12/round-robin) router - [First Successful](https://docs.mulesoft.com/mule-runtime/4.12/first-successful) router Steps to enable default events tracking for an individual component: 1. Open the connector or component properties view. 2. Enable default business events using any of the following options: - In the UI, select **Enable default events tracking**: ![A business event tracking within a choice component](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-business-event-component.png) - In the XML, add attribute `tracking:enable-default-events="true"` inside your component element: ```xml ... ... ``` 3. Save your settings. ## Customize the Transaction ID The Set Transaction Id component enables you to set an identifier for all tracked events so that meaningful information, such as an order number, is displayed for a transaction when analyzing tracked events at runtime, whether using Anypoint Runtime Manager or CloudHub. The transaction ID supports DataWeave expressions, which enables you to create an ID dynamically and include information related to the event into the ID. Follow these steps to set a transaction ID either in Anypoint Studio or by editing the configuration XML: - In the Studio UI: 1. Drag the **Set Transaction Id** component to your flow. 2. In the **Set Transaction ID** configuration screen, set an ID value for the **Transaction ID** field: ![Configuration for setting a transaction ID in a Mule flow](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-custom-transaction-id.png) - In the XML editor: - Add a child element to the `flow` element: ```xml ... ... ``` ## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/4.12/business-events) --- product: Mule Runtime version: 4.3 --- # Configure Default Events Tracking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Because event tracking requires processing and network overhead to aggregate and store the events that Mule runtime engine generates, it is disabled by default. However, you can enable and configure default events tracking for connectors or message processors that support it, at one of two levels: - At the flow level - At the message processor (connector or component) level, which takes precedence over the flow level setting After you enable event tracking, customize the transaction ID to identify specific tracked events so that you can analyze them at runtime. ## Flow-Level Event Tracking Use this option to enable default event tracking for all elements in a flow that support event tracking. You can disable tracking for specific processors or connectors to override the flow level setting. Steps to enable default events tracking for all components in a flow: 1. Select your flow component to open the properties view. 2. Enable default business events using either the UI or XML: - In the UI, select **Enable default events tracking**: ![default-event-tracking-flow](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-business-event-flow.png) - In the XML, add attribute `tracking:enable-default-events="true"` to the `flow` element: ```xml ``` 3. Save your settings. ## Message Processor-Level Event Tracking You can enable event tracking on individual connectors and components that support event tracking. Steps to enable enable default events tracking for an individual component: 1. Open the connector or component properties view. 2. Enable default business events using any of the following options: - In the UI, select **Enable default events tracking**: ![default-event-tracking-component](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-business-event-component.png) - In the XML, add attribute `tracking:enable-default-events="true"` inside your component element: ```xml ... ... ``` 3. Save your settings. ## Customize the Transaction ID The Set Transaction Id component enables you to set an identifier for all tracked events so that meaningful information, such as an order number, is displayed for a transaction when analyzing tracked events at runtime, whether using Anypoint Runtime Manager or CloudHub. The transaction ID supports DataWeave expressions, which enables you to create an ID dynamically and include information related to the event into the ID. Follow these steps to set a transaction ID either in Anypoint Studio or by editing the configuration XML: - In the Studio UI: 1. Drag the **Set Transaction Id** component to your flow. 2. In the **Set Transaction ID** configuration screen, set an ID value for the **Transaction ID** field: ![custom-transaction-id](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-custom-transaction-id.png) - In the XML editor: - Add a child element to the `flow` element: ```xml ... ... ``` ## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/4.3/business-events) --- product: Mule Runtime version: 4.4 --- # Configure Default Events Tracking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Because event tracking requires processing and network overhead to aggregate and store the events that Mule runtime engine generates, it is disabled by default. However, you can enable and configure default events tracking for connectors or message processors that support it, at one of two levels: - At the flow level - At the message processor (connector or component) level, which takes precedence over the flow-level setting After you enable event tracking, customize the transaction ID to identify specific tracked events so that you can analyze them at runtime. ## Flow-Level Event Tracking Use this option in the [Flow](https://docs.mulesoft.com/mule-runtime/4.4/flow-component) component to enable default event tracking for all elements in a flow that support event tracking. You can disable tracking for specific processors or connectors to override the flow level setting. Steps to enable default events tracking for all components in a flow: 1. Select your flow component to open the properties view. 2. Enable default business events using either the UI or XML: - In the UI, select **Enable default events tracking**: ![default-event-tracking-flow](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-business-event-flow.png) - In the XML, add attribute `tracking:enable-default-events="true"` to the `flow` element: ```xml ``` 3. Save your settings. ## Message Processor-Level Event Tracking You can enable event tracking on individual connectors and Mule components that support event tracking. The following Mule components provide a configuration for enabling business events: - [Choice](https://docs.mulesoft.com/mule-runtime/4.4/choice-router-concept) router - [Round Robin](https://docs.mulesoft.com/mule-runtime/4.4/round-robin) router - [First Successful](https://docs.mulesoft.com/mule-runtime/4.4/first-successful) router Steps to enable enable default events tracking for an individual component: 1. Open the connector or component properties view. 2. Enable default business events using any of the following options: - In the UI, select **Enable default events tracking**: ![default-event-tracking-component](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-business-event-component.png) - In the XML, add attribute `tracking:enable-default-events="true"` inside your component element: ```xml ... ... ``` 3. Save your settings. ## Customize the Transaction ID The Set Transaction Id component enables you to set an identifier for all tracked events so that meaningful information, such as an order number, is displayed for a transaction when analyzing tracked events at runtime, whether using Anypoint Runtime Manager or CloudHub. The transaction ID supports DataWeave expressions, which enables you to create an ID dynamically and include information related to the event into the ID. Follow these steps to set a transaction ID either in Anypoint Studio or by editing the configuration XML: - In the Studio UI: 1. Drag the **Set Transaction Id** component to your flow. 2. In the **Set Transaction ID** configuration screen, set an ID value for the **Transaction ID** field: ![custom-transaction-id](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-custom-transaction-id.png) - In the XML editor: - Add a child element to the `flow` element: ```xml ... ... ``` ## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/4.4/business-events) --- product: Mule Runtime version: 4.6 --- # Configure Default Events Tracking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Because event tracking requires processing and network overhead to aggregate and store the events that Mule runtime engine generates, it is disabled by default. However, you can enable and configure default events tracking for connectors or message processors that support it, at one of two levels: - At the flow level - At the message processor (connector or component) level, which takes precedence over the flow-level setting After you enable event tracking, customize the transaction ID to identify specific tracked events so that you can analyze them at runtime. ## Flow-Level Event Tracking Use this option in the [Flow](https://docs.mulesoft.com/mule-runtime/4.6/flow-component) component to enable default event tracking for all elements in a flow that support event tracking. You can disable tracking for specific processors or connectors to override the flow level setting. Steps to enable default events tracking for all components in a flow: 1. Select your flow component to open the properties view. 2. Enable default business events using either the UI or XML: - In the UI, select **Enable default events tracking**: ![default-event-tracking-flow](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-business-event-flow.png) - In the XML, add attribute `tracking:enable-default-events="true"` to the `flow` element: ```xml ``` 3. Save your settings. ## Message Processor-Level Event Tracking You can enable event tracking on individual connectors and Mule components that support event tracking. The following Mule components provide a configuration for enabling business events: - [Choice](https://docs.mulesoft.com/mule-runtime/4.6/choice-router-concept) router - [Round Robin](https://docs.mulesoft.com/mule-runtime/4.6/round-robin) router - [First Successful](https://docs.mulesoft.com/mule-runtime/4.6/first-successful) router Steps to enable enable default events tracking for an individual component: 1. Open the connector or component properties view. 2. Enable default business events using any of the following options: - In the UI, select **Enable default events tracking**: ![default-event-tracking-component](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-business-event-component.png) - In the XML, add attribute `tracking:enable-default-events="true"` inside your component element: ```xml ... ... ``` 3. Save your settings. ## Customize the Transaction ID The Set Transaction Id component enables you to set an identifier for all tracked events so that meaningful information, such as an order number, is displayed for a transaction when analyzing tracked events at runtime, whether using Anypoint Runtime Manager or CloudHub. The transaction ID supports DataWeave expressions, which enables you to create an ID dynamically and include information related to the event into the ID. Follow these steps to set a transaction ID either in Anypoint Studio or by editing the configuration XML: - In the Studio UI: 1. Drag the **Set Transaction Id** component to your flow. 2. In the **Set Transaction ID** configuration screen, set an ID value for the **Transaction ID** field: ![custom-transaction-id](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-custom-transaction-id.png) - In the XML editor: - Add a child element to the `flow` element: ```xml ... ... ``` ## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/4.6/business-events) --- product: Mule Runtime version: 4.9 --- # Configure Default Events Tracking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Because event tracking requires processing and network overhead to aggregate and store the events that Mule runtime engine generates, it is disabled by default. However, you can enable and configure default events tracking for connectors or message processors that support it, at one of two levels: - At the flow level - At the message processor (connector or component) level, which takes precedence over the flow-level setting After you enable event tracking, customize the transaction ID to identify specific tracked events so that you can analyze them at runtime. ## Flow-Level Event Tracking Use this option in the [Flow](https://docs.mulesoft.com/mule-runtime/4.9/flow-component) component to enable default event tracking for all elements in a flow that support event tracking. You can disable tracking for specific processors or connectors to override the flow level setting. Steps to enable default events tracking for all components in a flow: 1. Select your flow component to open the properties view. 2. Enable default business events using either the UI or XML: - In the UI, select **Enable default events tracking**: ![A flow configuration interface for JMS processing with options to enable event tracking](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-business-event-flow.png) - In the XML, add attribute `tracking:enable-default-events="true"` to the `flow` element: ```xml ``` 3. Save your settings. ## Message Processor-Level Event Tracking You can enable event tracking on individual connectors and Mule components that support event tracking. The following Mule components provide a configuration for enabling business events: - [Choice](https://docs.mulesoft.com/mule-runtime/4.9/choice-router-concept) router - [Round Robin](https://docs.mulesoft.com/mule-runtime/4.9/round-robin) router - [First Successful](https://docs.mulesoft.com/mule-runtime/4.9/first-successful) router Steps to enable default events tracking for an individual component: 1. Open the connector or component properties view. 2. Enable default business events using any of the following options: - In the UI, select **Enable default events tracking**: ![A business event tracking within a choice component](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-business-event-component.png) - In the XML, add attribute `tracking:enable-default-events="true"` inside your component element: ```xml ... ... ``` 3. Save your settings. ## Customize the Transaction ID The Set Transaction Id component enables you to set an identifier for all tracked events so that meaningful information, such as an order number, is displayed for a transaction when analyzing tracked events at runtime, whether using Anypoint Runtime Manager or CloudHub. The transaction ID supports DataWeave expressions, which enables you to create an ID dynamically and include information related to the event into the ID. Follow these steps to set a transaction ID either in Anypoint Studio or by editing the configuration XML: - In the Studio UI: 1. Drag the **Set Transaction Id** component to your flow. 2. In the **Set Transaction ID** configuration screen, set an ID value for the **Transaction ID** field: ![Configuration for setting a transaction ID in a Mule flow](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-custom-transaction-id.png) - In the XML editor: - Add a child element to the `flow` element: ```xml ... ... ``` ## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/4.9/business-events) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Configure Default Events Tracking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Because event tracking requires processing and network overhead to aggregate and store the events that Mule runtime engine generates, it is disabled by default. However, you can enable and configure default events tracking for connectors or message processors that support it, at one of two levels: - At the flow level - At the message processor (connector or component) level, which takes precedence over the flow-level setting After you enable event tracking, customize the transaction ID to identify specific tracked events so that you can analyze them at runtime. ## Flow-Level Event Tracking Use this option in the [Flow](https://docs.mulesoft.com/mule-runtime/latest/flow-component) component to enable default event tracking for all elements in a flow that support event tracking. You can disable tracking for specific processors or connectors to override the flow level setting. Steps to enable default events tracking for all components in a flow: 1. Select your flow component to open the properties view. 2. Enable default business events using either the UI or XML: - In the UI, select **Enable default events tracking**: ![A flow configuration interface for JMS processing with options to enable event tracking](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-business-event-flow.png) - In the XML, add attribute `tracking:enable-default-events="true"` to the `flow` element: ```xml ``` 3. Save your settings. ## Message Processor-Level Event Tracking You can enable event tracking on individual connectors and Mule components that support event tracking. The following Mule components provide a configuration for enabling business events: - [Choice](https://docs.mulesoft.com/mule-runtime/latest/choice-router-concept) router - [Round Robin](https://docs.mulesoft.com/mule-runtime/latest/round-robin) router - [First Successful](https://docs.mulesoft.com/mule-runtime/latest/first-successful) router Steps to enable default events tracking for an individual component: 1. Open the connector or component properties view. 2. Enable default business events using any of the following options: - In the UI, select **Enable default events tracking**: ![A business event tracking within a choice component](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-business-event-component.png) - In the XML, add attribute `tracking:enable-default-events="true"` inside your component element: ```xml ... ... ``` 3. Save your settings. ## Customize the Transaction ID The Set Transaction Id component enables you to set an identifier for all tracked events so that meaningful information, such as an order number, is displayed for a transaction when analyzing tracked events at runtime, whether using Anypoint Runtime Manager or CloudHub. The transaction ID supports DataWeave expressions, which enables you to create an ID dynamically and include information related to the event into the ID. Follow these steps to set a transaction ID either in Anypoint Studio or by editing the configuration XML: - In the Studio UI: 1. Drag the **Set Transaction Id** component to your flow. 2. In the **Set Transaction ID** configuration screen, set an ID value for the **Transaction ID** field: ![Configuration for setting a transaction ID in a Mule flow](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-custom-transaction-id.png) - In the XML editor: - Add a child element to the `flow` element: ```xml ... ... ``` ## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/latest/business-events) --- product: Mule Runtime version: 4.11 keywords: anypoint studio, esb, connector, spring security, spring, ldap, authentication --- # Configure LDAP Provider for Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, you can either use a Spring Security LDAP provider to perform component authorization, or use it as a Mule security provider via the Spring module. Before you configure the LDAP provider, obtain the Spring JAR files and declare Spring beans. ## Obtain JAR Files The Mule software distribution provides the Spring JAR files you need in the `/lib/opt` directory: - `spring-ldap-core-2.3.2.RELEASE.jar` - `spring-security-config-4.2.6.RELEASE.jar` - `spring-security-core-4.2.6.RELEASE.jar` - `spring-security-ldap-4.2.6.RELEASE.jar` - `spring-security-web-4.2.6.RELEASE.jar` ## Declare Spring Beans The [DefaultSpringSecurityContextSource](https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/ldap/DefaultSpringSecurityContextSource.html) class is the access point for obtaining an LDAP context. You must declare the Spring bean for `DefaultSpringSecurityContextSource` in a separate `beans.xml` file in your resources folder. For example, you must set up an LDAP context source for use by the Spring Security authentication provider to search and authenticate your users. Also, you need to define an `authentication-manager` interface with an embedded `ldap-authentication-provider` class as in the following code sample: ```xml ``` ## Configure the Mule Security Provider The `SpringSecurityProviderAdapter` delegates to an `AuthenticationProvider` such as the `LdapAuthenticationProvider`. To configure the Mule security provider review the following example configuration that shows how you can achieve in Mule connector-level security and other security features that require one or more security providers. ```xml ``` The following example configuration references a basic HTTP security filter: ```xml ``` ## Configure the Component Authorization To configure the component authorization, declare the `authorization-filter` field as follows: ```xml ``` ## See also - [Spring Module](https://docs.mulesoft.com/spring-module/latest/) - [Component Authorization Using Spring Security](https://docs.mulesoft.com/mule-runtime/4.11/component-authorization-using-spring-security) - [LDAP Spring Security](https://docs.spring.io/spring-security/site/docs/3.1.x/reference/ldap.html) - [Spring Security Reference](https://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/html/) --- product: Mule Runtime version: 4.12 keywords: anypoint studio, esb, connector, spring security, spring, ldap, authentication --- # Configure LDAP Provider for Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, you can either use a Spring Security LDAP provider to perform component authorization, or use it as a Mule security provider via the Spring module. Before you configure the LDAP provider, obtain the Spring JAR files and declare Spring beans. ## Obtain JAR Files The Mule software distribution provides the Spring JAR files you need in the `/lib/opt` directory: - `spring-ldap-core-2.3.2.RELEASE.jar` - `spring-security-config-4.2.6.RELEASE.jar` - `spring-security-core-4.2.6.RELEASE.jar` - `spring-security-ldap-4.2.6.RELEASE.jar` - `spring-security-web-4.2.6.RELEASE.jar` ## Declare Spring Beans The [DefaultSpringSecurityContextSource](https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/ldap/DefaultSpringSecurityContextSource.html) class is the access point for obtaining an LDAP context. You must declare the Spring bean for `DefaultSpringSecurityContextSource` in a separate `beans.xml` file in your resources folder. For example, you must set up an LDAP context source for use by the Spring Security authentication provider to search and authenticate your users. Also, you need to define an `authentication-manager` interface with an embedded `ldap-authentication-provider` class as in the following code sample: ```xml ``` ## Configure the Mule Security Provider The `SpringSecurityProviderAdapter` delegates to an `AuthenticationProvider` such as the `LdapAuthenticationProvider`. To configure the Mule security provider review the following example configuration that shows how you can achieve in Mule connector-level security and other security features that require one or more security providers. ```xml ``` The following example configuration references a basic HTTP security filter: ```xml ``` ## Configure the Component Authorization To configure the component authorization, declare the `authorization-filter` field as follows: ```xml ``` ## See also - [Spring Module](https://docs.mulesoft.com/spring-module/latest/) - [Component Authorization Using Spring Security](https://docs.mulesoft.com/mule-runtime/4.12/component-authorization-using-spring-security) - [LDAP Spring Security](https://docs.spring.io/spring-security/site/docs/3.1.x/reference/ldap.html) - [Spring Security Reference](https://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/html/) --- product: Mule Runtime version: 4.3 keywords: anypoint studio, esb, connector, spring security, spring, ldap, authentication --- # Configure LDAP Provider for Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, you can either use a Spring Security LDAP provider to perform component authorization, or use it as a Mule security provider via the Spring module. Before you configure the LDAP provider, obtain the Spring JAR files and declare Spring beans. ## Obtain JAR Files The Mule software distribution provides the Spring JAR files you need in the `/lib/opt` directory: - `spring-ldap-core-2.3.2.RELEASE.jar` - `spring-security-config-4.2.6.RELEASE.jar` - `spring-security-core-4.2.6.RELEASE.jar` - `spring-security-ldap-4.2.6.RELEASE.jar` - `spring-security-web-4.2.6.RELEASE.jar` ## Declare Spring Beans The [DefaultSpringSecurityContextSource](https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/ldap/DefaultSpringSecurityContextSource.html) class is the access point for obtaining an LDAP context. You must declare the Spring bean for `DefaultSpringSecurityContextSource` in a separate `beans.xml` file in your resources folder. For example, you must set up an LDAP context source for use by the Spring Security authentication provider to search and authenticate your users. Also, you need to define an `authentication-manager` interface with an embedded `ldap-authentication-provider` class as in the following code sample: ```xml ``` ## Configure the Mule Security Provider The `SpringSecurityProviderAdapter` delegates to an `AuthenticationProvider` such as the `LdapAuthenticationProvider`. To configure the Mule security provider review the following example configuration that shows how you can achieve in Mule connector-level security and other security features that require one or more security providers. ```xml ``` The following example configuration references a basic HTTP security filter: ```xml ``` ## Configure the Component Authorization To configure the component authorization, declare the `authorization-filter` field as follows: ```xml ``` ## See also - [Spring Module](https://docs.mulesoft.com/spring-module/latest/) - [Component Authorization Using Spring Security](https://docs.mulesoft.com/mule-runtime/4.3/component-authorization-using-spring-security) - [LDAP Spring Security](https://docs.spring.io/spring-security/site/docs/3.1.x/reference/ldap.html) - [Spring Security Reference](https://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/html/) --- product: Mule Runtime version: 4.4 keywords: anypoint studio, esb, connector, spring security, spring, ldap, authentication --- # Configure LDAP Provider for Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, you can either use a Spring Security LDAP provider to perform component authorization, or use it as a Mule security provider via the Spring module. Before you configure the LDAP provider, obtain the Spring JAR files and declare Spring beans. ## Obtain JAR Files The Mule software distribution provides the Spring JAR files you need in the `/lib/opt` directory: - `spring-ldap-core-2.3.2.RELEASE.jar` - `spring-security-config-4.2.6.RELEASE.jar` - `spring-security-core-4.2.6.RELEASE.jar` - `spring-security-ldap-4.2.6.RELEASE.jar` - `spring-security-web-4.2.6.RELEASE.jar` ## Declare Spring Beans The [DefaultSpringSecurityContextSource](https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/ldap/DefaultSpringSecurityContextSource.html) class is the access point for obtaining an LDAP context. You must declare the Spring bean for `DefaultSpringSecurityContextSource` in a separate `beans.xml` file in your resources folder. For example, you must set up an LDAP context source for use by the Spring Security authentication provider to search and authenticate your users. Also, you need to define an `authentication-manager` interface with an embedded `ldap-authentication-provider` class as in the following code sample: ```xml ``` ## Configure the Mule Security Provider The `SpringSecurityProviderAdapter` delegates to an `AuthenticationProvider` such as the `LdapAuthenticationProvider`. To configure the Mule security provider review the following example configuration that shows how you can achieve in Mule connector-level security and other security features that require one or more security providers. ```xml ``` The following example configuration references a basic HTTP security filter: ```xml ``` ## Configure the Component Authorization To configure the component authorization, declare the `authorization-filter` field as follows: ```xml ``` ## See also - [Spring Module](https://docs.mulesoft.com/spring-module/latest/) - [Component Authorization Using Spring Security](https://docs.mulesoft.com/mule-runtime/4.4/component-authorization-using-spring-security) - [LDAP Spring Security](https://docs.spring.io/spring-security/site/docs/3.1.x/reference/ldap.html) - [Spring Security Reference](https://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/html/) --- product: Mule Runtime version: 4.6 keywords: anypoint studio, esb, connector, spring security, spring, ldap, authentication --- # Configure LDAP Provider for Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, you can either use a Spring Security LDAP provider to perform component authorization, or use it as a Mule security provider via the Spring module. Before you configure the LDAP provider, obtain the Spring JAR files and declare Spring beans. ## Obtain JAR Files The Mule software distribution provides the Spring JAR files you need in the `/lib/opt` directory: - `spring-ldap-core-2.3.2.RELEASE.jar` - `spring-security-config-4.2.6.RELEASE.jar` - `spring-security-core-4.2.6.RELEASE.jar` - `spring-security-ldap-4.2.6.RELEASE.jar` - `spring-security-web-4.2.6.RELEASE.jar` ## Declare Spring Beans The [DefaultSpringSecurityContextSource](https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/ldap/DefaultSpringSecurityContextSource.html) class is the access point for obtaining an LDAP context. You must declare the Spring bean for `DefaultSpringSecurityContextSource` in a separate `beans.xml` file in your resources folder. For example, you must set up an LDAP context source for use by the Spring Security authentication provider to search and authenticate your users. Also, you need to define an `authentication-manager` interface with an embedded `ldap-authentication-provider` class as in the following code sample: ```xml ``` ## Configure the Mule Security Provider The `SpringSecurityProviderAdapter` delegates to an `AuthenticationProvider` such as the `LdapAuthenticationProvider`. To configure the Mule security provider review the following example configuration that shows how you can achieve in Mule connector-level security and other security features that require one or more security providers. ```xml ``` The following example configuration references a basic HTTP security filter: ```xml ``` ## Configure the Component Authorization To configure the component authorization, declare the `authorization-filter` field as follows: ```xml ``` ## See also - [Spring Module](https://docs.mulesoft.com/spring-module/latest/) - [Component Authorization Using Spring Security](https://docs.mulesoft.com/mule-runtime/4.6/component-authorization-using-spring-security) - [LDAP Spring Security](https://docs.spring.io/spring-security/site/docs/3.1.x/reference/ldap.html) - [Spring Security Reference](https://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/html/) --- product: Mule Runtime version: 4.9 keywords: anypoint studio, esb, connector, spring security, spring, ldap, authentication --- # Configure LDAP Provider for Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, you can either use a Spring Security LDAP provider to perform component authorization, or use it as a Mule security provider via the Spring module. Before you configure the LDAP provider, obtain the Spring JAR files and declare Spring beans. ## Obtain JAR Files The Mule software distribution provides the Spring JAR files you need in the `/lib/opt` directory: - `spring-ldap-core-2.3.2.RELEASE.jar` - `spring-security-config-4.2.6.RELEASE.jar` - `spring-security-core-4.2.6.RELEASE.jar` - `spring-security-ldap-4.2.6.RELEASE.jar` - `spring-security-web-4.2.6.RELEASE.jar` ## Declare Spring Beans The [DefaultSpringSecurityContextSource](https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/ldap/DefaultSpringSecurityContextSource.html) class is the access point for obtaining an LDAP context. You must declare the Spring bean for `DefaultSpringSecurityContextSource` in a separate `beans.xml` file in your resources folder. For example, you must set up an LDAP context source for use by the Spring Security authentication provider to search and authenticate your users. Also, you need to define an `authentication-manager` interface with an embedded `ldap-authentication-provider` class as in the following code sample: ```xml ``` ## Configure the Mule Security Provider The `SpringSecurityProviderAdapter` delegates to an `AuthenticationProvider` such as the `LdapAuthenticationProvider`. To configure the Mule security provider review the following example configuration that shows how you can achieve in Mule connector-level security and other security features that require one or more security providers. ```xml ``` The following example configuration references a basic HTTP security filter: ```xml ``` ## Configure the Component Authorization To configure the component authorization, declare the `authorization-filter` field as follows: ```xml ``` ## See also - [Spring Module](https://docs.mulesoft.com/spring-module/latest/) - [Component Authorization Using Spring Security](https://docs.mulesoft.com/mule-runtime/4.9/component-authorization-using-spring-security) - [LDAP Spring Security](https://docs.spring.io/spring-security/site/docs/3.1.x/reference/ldap.html) - [Spring Security Reference](https://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/html/) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: anypoint studio, esb, connector, spring security, spring, ldap, authentication --- # Configure LDAP Provider for Spring Security > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, you can either use a Spring Security LDAP provider to perform component authorization, or use it as a Mule security provider via the Spring module. Before you configure the LDAP provider, obtain the Spring JAR files and declare Spring beans. ## Obtain JAR Files The Mule software distribution provides the Spring JAR files you need in the `/lib/opt` directory: - `spring-ldap-core-2.3.2.RELEASE.jar` - `spring-security-config-4.2.6.RELEASE.jar` - `spring-security-core-4.2.6.RELEASE.jar` - `spring-security-ldap-4.2.6.RELEASE.jar` - `spring-security-web-4.2.6.RELEASE.jar` ## Declare Spring Beans The [DefaultSpringSecurityContextSource](https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/ldap/DefaultSpringSecurityContextSource.html) class is the access point for obtaining an LDAP context. You must declare the Spring bean for `DefaultSpringSecurityContextSource` in a separate `beans.xml` file in your resources folder. For example, you must set up an LDAP context source for use by the Spring Security authentication provider to search and authenticate your users. Also, you need to define an `authentication-manager` interface with an embedded `ldap-authentication-provider` class as in the following code sample: ```xml ``` ## Configure the Mule Security Provider The `SpringSecurityProviderAdapter` delegates to an `AuthenticationProvider` such as the `LdapAuthenticationProvider`. To configure the Mule security provider review the following example configuration that shows how you can achieve in Mule connector-level security and other security features that require one or more security providers. ```xml ``` The following example configuration references a basic HTTP security filter: ```xml ``` ## Configure the Component Authorization To configure the component authorization, declare the `authorization-filter` field as follows: ```xml ``` ## See also - [Spring Module](https://docs.mulesoft.com/spring-module/latest/) - [Component Authorization Using Spring Security](https://docs.mulesoft.com/mule-runtime/latest/component-authorization-using-spring-security) - [LDAP Spring Security](https://docs.spring.io/spring-security/site/docs/3.1.x/reference/ldap.html) - [Spring Security Reference](https://docs.spring.io/spring-security/site/docs/4.0.1.RELEASE/reference/html/) --- product: Mule Runtime version: 4.11 --- # Configure Property Placeholders > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Instead of using static values for your Mule application configurations, such as connections, you can create a `.yaml` or a `.properties` file to contain your properties and then reference the properties from your application. Configuring a properties file improves the organization and maintainability of your applications. In a `.yaml` file, the properties take this form: ```yaml http: path: "/service" port: "10000" host: "my-api.cloudhub.io" ``` In a `.properties` file, the properties take this form: http.path=/service http.port=10000 http.host=my-api.cloudhub.io ## Create and Configure your Properties File 1. In Studio, go to the **Package Explorer** view and right-click the `/src/main/resources` folder in your project. 2. Select **New** > **File**: ![A Mule project structure with various source and test directories](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-properties-new-file.png) 3. Choose a name for your file and set the extension to `.yaml`, or `.properties` if you prefer to use this format. 4. Edit the file to define the properties and values you need. 5. Add the properties file to your Mule application. - From Studio: 1. Open the **Global Elements** tab, and click the **Create** button. 2. Search for the element called Configuration Properties and click **OK**. 3. Click on the **…​** button and navigate to your `.yaml` or `.properties` file. - From the XML Editor: 1. Include a `` element inside ``, and set its `file` parameter with your properties file name. For example: ```xml ` ... ``` ## Use the Properties in your Application Once you have configured your properties file and added it to your project, you can reference its attributes by using a syntax like this: `${propertyContainer.propertyName}`. Based on the examples configured in the previous section, to use the `path` and `port` values the syntax is `${http.path}` and `${http.port}` respectively. For example, you can configure your Global HTTP Request configuration to use the values defined in the properties file. - From Studio: ![HTTP Request configuration settings showing fields for URL, host, port, and connection settings](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-properties-file.png) - From the XML Editor ```xml ``` When the application is deployed, the property values are computed from the different possible sources and statically replace the placeholders as if they were written directly in the source code. Based on the previous example, the configuration looks like this: ```xml ``` There is no escaping special characters based on the context. The resulting values need to be valid in the context from which they are referenced. Consider the following example, which contains a DataWeave script: ```xml ``` The contents of the `.properties` file: message=I love $ After property replacements take place, the application looks like this: ```xml ``` The output is an invalid DataWeave script because the dollar sign ($) has a special meaning and needs to be escaped. See [Dataweave - Escaping Special Characters](https://docs.mulesoft.com/dataweave/latest/dataweave-types#escape-chars-string). Remember the property placeholders are replaced before the DataWeave script is parsed. To solve conflicts, you can escape the value in the properties file: message=I love \\$ Or use DataWeave [p function](https://docs.mulesoft.com/dataweave/latest/dw-mule-functions-p) instead of a property placeholder: ```xml ``` The property is evaluated when the script is executed and the script remains syntactically valid at the moment of parsing. ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.11/configuring-properties) --- product: Mule Runtime version: 4.12 --- # Configure Property Placeholders > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Instead of using static values for your Mule application configurations, such as connections, you can create a `.yaml` or a `.properties` file to contain your properties and then reference the properties from your application. Configuring a properties file improves the organization and maintainability of your applications. In a `.yaml` file, the properties take this form: ```yaml http: path: "/service" port: "10000" host: "my-api.cloudhub.io" ``` In a `.properties` file, the properties take this form: http.path=/service http.port=10000 http.host=my-api.cloudhub.io ## Create and Configure your Properties File 1. In Studio, go to the **Package Explorer** view and right-click the `/src/main/resources` folder in your project. 2. Select **New** > **File**: ![A Mule project structure with various source and test directories](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-properties-new-file.png) 3. Choose a name for your file and set the extension to `.yaml`, or `.properties` if you prefer to use this format. 4. Edit the file to define the properties and values you need. 5. Add the properties file to your Mule application. - From Studio: 1. Open the **Global Elements** tab, and click the **Create** button. 2. Search for the element called Configuration Properties and click **OK**. 3. Click on the **…​** button and navigate to your `.yaml` or `.properties` file. - From the XML Editor: 1. Include a `` element inside ``, and set its `file` parameter with your properties file name. For example: ```xml ` ... ``` ## Use the Properties in your Application Once you have configured your properties file and added it to your project, you can reference its attributes by using a syntax like this: `${propertyContainer.propertyName}`. Based on the examples configured in the previous section, to use the `path` and `port` values the syntax is `${http.path}` and `${http.port}` respectively. For example, you can configure your Global HTTP Request configuration to use the values defined in the properties file. - From Studio: ![HTTP Request configuration settings showing fields for URL, host, port, and connection settings](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-properties-file.png) - From the XML Editor ```xml ``` When the application is deployed, the property values are computed from the different possible sources and statically replace the placeholders as if they were written directly in the source code. Based on the previous example, the configuration looks like this: ```xml ``` There is no escaping special characters based on the context. The resulting values need to be valid in the context from which they are referenced. Consider the following example, which contains a DataWeave script: ```xml ``` The contents of the `.properties` file: message=I love $ After property replacements take place, the application looks like this: ```xml ``` The output is an invalid DataWeave script because the dollar sign ($) has a special meaning and needs to be escaped. See [Dataweave - Escaping Special Characters](https://docs.mulesoft.com/dataweave/latest/dataweave-types#escape-chars-string). Remember the property placeholders are replaced before the DataWeave script is parsed. To solve conflicts, you can escape the value in the properties file: message=I love \\$ Or use DataWeave [p function](https://docs.mulesoft.com/dataweave/latest/dw-mule-functions-p) instead of a property placeholder: ```xml ``` The property is evaluated when the script is executed and the script remains syntactically valid at the moment of parsing. ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.12/configuring-properties) --- product: Mule Runtime version: 4.3 --- # Configure Property Placeholders > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Instead of using static values for your Mule application configurations, such as connections, you can create a `.yaml` or a `.properties` file to contain your properties and then reference the properties from your application. Configuring a properties file improves the organization and maintainability of your applications. In a `.yaml` file, the properties take this form: ```yaml http: path: "/service" port: "10000" host: "my-api.cloudhub.io" ``` In a `.properties` file, the properties take this form: http.path=/service http.port=10000 http.host=my-api.cloudhub.io ## Create and Configure your Properties File 1. In Studio, go to the **Package Explorer** view and right-click the `/src/main/resources` folder in your project. 2. Select **New** > **File**: ![new-file-properties](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-properties-new-file.png) 3. Choose a name for your file and set the extension to `.yaml`, or `.properties` if you prefer to use this format. 4. Edit the file to define the properties and values you need. 5. Add the properties file to your Mule application. - From Studio: 1. Open the **Global Elements** tab, and click the **Create** button. 2. Search for the element called Configuration Properties and click **OK**. 3. Click on the **…​** button and navigate to your `.yaml` or `.properties` file. - From the XML Editor: 1. Include a `` element inside ``, and set its `file` parameter with your properties file name. For example: ```xml ` ... ``` ## Use the Properties in your Application Once you have configured your properties file and added it to your project, you can reference its attributes by using a syntax like this: `${propertyContainer.propertyName}`. Based on the examples configured in the previous section, to use the `path` and `port` values the syntax is `${http.path}` and `${http.port}` respectively. For example, you can configure your Global HTTP Request configuration to use the values defined in the properties file. - From Studio: ![properties-file](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-properties-file.png) - From the XML Editor ```xml ``` ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.3/configuring-properties) --- product: Mule Runtime version: 4.4 --- # Configure Property Placeholders > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Instead of using static values for your Mule application configurations, such as connections, you can create a `.yaml` or a `.properties` file to contain your properties and then reference the properties from your application. Configuring a properties file improves the organization and maintainability of your applications. In a `.yaml` file, the properties take this form: ```yaml http: path: "/service" port: "10000" host: "my-api.cloudhub.io" ``` In a `.properties` file, the properties take this form: http.path=/service http.port=10000 http.host=my-api.cloudhub.io ## Create and Configure your Properties File 1. In Studio, go to the **Package Explorer** view and right-click the `/src/main/resources` folder in your project. 2. Select **New** > **File**: ![new-file-properties](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-properties-new-file.png) 3. Choose a name for your file and set the extension to `.yaml`, or `.properties` if you prefer to use this format. 4. Edit the file to define the properties and values you need. 5. Add the properties file to your Mule application. - From Studio: 1. Open the **Global Elements** tab, and click the **Create** button. 2. Search for the element called Configuration Properties and click **OK**. 3. Click on the **…​** button and navigate to your `.yaml` or `.properties` file. - From the XML Editor: 1. Include a `` element inside ``, and set its `file` parameter with your properties file name. For example: ```xml ` ... ``` ## Use the Properties in your Application Once you have configured your properties file and added it to your project, you can reference its attributes by using a syntax like this: `${propertyContainer.propertyName}`. Based on the examples configured in the previous section, to use the `path` and `port` values the syntax is `${http.path}` and `${http.port}` respectively. For example, you can configure your Global HTTP Request configuration to use the values defined in the properties file. - From Studio: ![properties-file](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-properties-file.png) - From the XML Editor ```xml ``` ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.4/configuring-properties) --- product: Mule Runtime version: 4.6 --- # Configure Property Placeholders > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Instead of using static values for your Mule application configurations, such as connections, you can create a `.yaml` or a `.properties` file to contain your properties and then reference the properties from your application. Configuring a properties file improves the organization and maintainability of your applications. In a `.yaml` file, the properties take this form: ```yaml http: path: "/service" port: "10000" host: "my-api.cloudhub.io" ``` In a `.properties` file, the properties take this form: http.path=/service http.port=10000 http.host=my-api.cloudhub.io ## Create and Configure your Properties File 1. In Studio, go to the **Package Explorer** view and right-click the `/src/main/resources` folder in your project. 2. Select **New** > **File**: ![new-file-properties](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-properties-new-file.png) 3. Choose a name for your file and set the extension to `.yaml`, or `.properties` if you prefer to use this format. 4. Edit the file to define the properties and values you need. 5. Add the properties file to your Mule application. - From Studio: 1. Open the **Global Elements** tab, and click the **Create** button. 2. Search for the element called Configuration Properties and click **OK**. 3. Click on the **…​** button and navigate to your `.yaml` or `.properties` file. - From the XML Editor: 1. Include a `` element inside ``, and set its `file` parameter with your properties file name. For example: ```xml ` ... ``` ## Use the Properties in your Application Once you have configured your properties file and added it to your project, you can reference its attributes by using a syntax like this: `${propertyContainer.propertyName}`. Based on the examples configured in the previous section, to use the `path` and `port` values the syntax is `${http.path}` and `${http.port}` respectively. For example, you can configure your Global HTTP Request configuration to use the values defined in the properties file. - From Studio: ![properties-file](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-properties-file.png) - From the XML Editor ```xml ``` When the application is deployed, the property values are computed from the different possible sources and statically replace the placeholders as if they were written directly in the source code. Based on the previous example, the configuration looks like this: ```xml ``` There is no escaping special characters based on the context. The resulting values need to be valid in the context from which they are referenced. Consider the following example, which contains a DataWeave script: ```xml ``` The contents of the `.properties` file: message=I love $ After property replacements take place, the application looks like this: ```xml ``` The output is an invalid DataWeave script because the dollar sign ($) has a special meaning and needs to be escaped. See [Dataweave - Escaping Special Characters](https://docs.mulesoft.com/dataweave/latest/dataweave-types#escape-chars-string). Remember the property placeholders are replaced before the DataWeave script is parsed. To solve conflicts, you can escape the value in the properties file: message=I love \\$ Or use DataWeave [p function](https://docs.mulesoft.com/dataweave/latest/dw-mule-functions-p) instead of a property placeholder: ```xml ``` The property is evaluated when the script is executed and the script remains syntactically valid at the moment of parsing. ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.6/configuring-properties) --- product: Mule Runtime version: 4.9 --- # Configure Property Placeholders > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Instead of using static values for your Mule application configurations, such as connections, you can create a `.yaml` or a `.properties` file to contain your properties and then reference the properties from your application. Configuring a properties file improves the organization and maintainability of your applications. In a `.yaml` file, the properties take this form: ```yaml http: path: "/service" port: "10000" host: "my-api.cloudhub.io" ``` In a `.properties` file, the properties take this form: http.path=/service http.port=10000 http.host=my-api.cloudhub.io ## Create and Configure your Properties File 1. In Studio, go to the **Package Explorer** view and right-click the `/src/main/resources` folder in your project. 2. Select **New** > **File**: ![A Mule project structure with various source and test directories](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-properties-new-file.png) 3. Choose a name for your file and set the extension to `.yaml`, or `.properties` if you prefer to use this format. 4. Edit the file to define the properties and values you need. 5. Add the properties file to your Mule application. - From Studio: 1. Open the **Global Elements** tab, and click the **Create** button. 2. Search for the element called Configuration Properties and click **OK**. 3. Click on the **…​** button and navigate to your `.yaml` or `.properties` file. - From the XML Editor: 1. Include a `` element inside ``, and set its `file` parameter with your properties file name. For example: ```xml ` ... ``` ## Use the Properties in your Application Once you have configured your properties file and added it to your project, you can reference its attributes by using a syntax like this: `${propertyContainer.propertyName}`. Based on the examples configured in the previous section, to use the `path` and `port` values the syntax is `${http.path}` and `${http.port}` respectively. For example, you can configure your Global HTTP Request configuration to use the values defined in the properties file. - From Studio: ![HTTP Request configuration settings showing fields for URL, host, port, and connection settings](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-properties-file.png) - From the XML Editor ```xml ``` When the application is deployed, the property values are computed from the different possible sources and statically replace the placeholders as if they were written directly in the source code. Based on the previous example, the configuration looks like this: ```xml ``` There is no escaping special characters based on the context. The resulting values need to be valid in the context from which they are referenced. Consider the following example, which contains a DataWeave script: ```xml ``` The contents of the `.properties` file: message=I love $ After property replacements take place, the application looks like this: ```xml ``` The output is an invalid DataWeave script because the dollar sign ($) has a special meaning and needs to be escaped. See [Dataweave - Escaping Special Characters](https://docs.mulesoft.com/dataweave/latest/dataweave-types#escape-chars-string). Remember the property placeholders are replaced before the DataWeave script is parsed. To solve conflicts, you can escape the value in the properties file: message=I love \\$ Or use DataWeave [p function](https://docs.mulesoft.com/dataweave/latest/dw-mule-functions-p) instead of a property placeholder: ```xml ``` The property is evaluated when the script is executed and the script remains syntactically valid at the moment of parsing. ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.9/configuring-properties) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Configure Property Placeholders > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Instead of using static values for your Mule application configurations, such as connections, you can create a `.yaml` or a `.properties` file to contain your properties and then reference the properties from your application. Configuring a properties file improves the organization and maintainability of your applications. In a `.yaml` file, the properties take this form: ```yaml http: path: "/service" port: "10000" host: "my-api.cloudhub.io" ``` In a `.properties` file, the properties take this form: http.path=/service http.port=10000 http.host=my-api.cloudhub.io ## Create and Configure your Properties File 1. In Studio, go to the **Package Explorer** view and right-click the `/src/main/resources` folder in your project. 2. Select **New** > **File**: ![A Mule project structure with various source and test directories](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-properties-new-file.png) 3. Choose a name for your file and set the extension to `.yaml`, or `.properties` if you prefer to use this format. 4. Edit the file to define the properties and values you need. 5. Add the properties file to your Mule application. - From Studio: 1. Open the **Global Elements** tab, and click the **Create** button. 2. Search for the element called Configuration Properties and click **OK**. 3. Click on the **…​** button and navigate to your `.yaml` or `.properties` file. - From the XML Editor: 1. Include a `` element inside ``, and set its `file` parameter with your properties file name. For example: ```xml ` ... ``` ## Use the Properties in your Application Once you have configured your properties file and added it to your project, you can reference its attributes by using a syntax like this: `${propertyContainer.propertyName}`. Based on the examples configured in the previous section, to use the `path` and `port` values the syntax is `${http.path}` and `${http.port}` respectively. For example, you can configure your Global HTTP Request configuration to use the values defined in the properties file. - From Studio: ![HTTP Request configuration settings showing fields for URL, host, port, and connection settings](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-properties-file.png) - From the XML Editor ```xml ``` When the application is deployed, the property values are computed from the different possible sources and statically replace the placeholders as if they were written directly in the source code. Based on the previous example, the configuration looks like this: ```xml ``` There is no escaping special characters based on the context. The resulting values need to be valid in the context from which they are referenced. Consider the following example, which contains a DataWeave script: ```xml ``` The contents of the `.properties` file: message=I love $ After property replacements take place, the application looks like this: ```xml ``` The output is an invalid DataWeave script because the dollar sign ($) has a special meaning and needs to be escaped. See [Dataweave - Escaping Special Characters](https://docs.mulesoft.com/dataweave/latest/dataweave-types#escape-chars-string). Remember the property placeholders are replaced before the DataWeave script is parsed. To solve conflicts, you can escape the value in the properties file: message=I love \\$ Or use DataWeave [p function](https://docs.mulesoft.com/dataweave/latest/dw-mule-functions-p) instead of a property placeholder: ```xml ``` The property is evaluated when the script is executed and the script remains syntactically valid at the moment of parsing. ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/latest/configuring-properties) --- product: Mule Runtime version: 4.11 --- # Configure the Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt 1. In your Mule app, add a Cache scope to a flow. 2. Click to open the General tab for the Cache scope. 3. Configure the Cache scope: - Provide a Display Name. - Select a Caching Strategy. Examples: - From the UI: `My_Caching_Strategy` - In the Studio XML: `cachingStrategy-ref="My_Caching_Strategy"` MuleSoft recommends that you reference a Caching Strategy that uses an ObjectStore instead of using the default in a production environment. If you need to create a Caching Strategy, see the procedure in [See Also](#see-also). 4. Opt to set up a filter for specific payloads if you need one. Example that uses a DataWeave expression: `filterExpression="#[user.isPremium()]"` If the message matches the expression(s), Mule executes the Caching Strategy. If the message does not match expression(s), Mule processes the message through all message processors within the Cache scope but never saves or produces cached responses. ## Example Cache Scope Configuration The following example shows the configuration of a Caching Strategy, which is then referenced by a Cache Scope that contains a Database Select operation and a Transform component: ```xml ``` ## See Also [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.11/cache-scope-strategy) [Cache Scope](https://docs.mulesoft.com/mule-runtime/4.11/cache-scope) --- product: Mule Runtime version: 4.12 --- # Configure the Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt 1. In your Mule app, add a Cache scope to a flow. 2. Click to open the General tab for the Cache scope. 3. Configure the Cache scope: - Provide a Display Name. - Select a Caching Strategy. Examples: - From the UI: `My_Caching_Strategy` - In the Studio XML: `cachingStrategy-ref="My_Caching_Strategy"` MuleSoft recommends that you reference a Caching Strategy that uses an ObjectStore instead of using the default in a production environment. If you need to create a Caching Strategy, see the procedure in [See Also](#see-also). 4. Opt to set up a filter for specific payloads if you need one. Example that uses a DataWeave expression: `filterExpression="#[user.isPremium()]"` If the message matches the expression(s), Mule executes the Caching Strategy. If the message does not match expression(s), Mule processes the message through all message processors within the Cache scope but never saves or produces cached responses. ## Example Cache Scope Configuration The following example shows the configuration of a Caching Strategy, which is then referenced by a Cache Scope that contains a Database Select operation and a Transform component: ```xml ``` ## See Also [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.12/cache-scope-strategy) [Cache Scope](https://docs.mulesoft.com/mule-runtime/4.12/cache-scope) --- product: Mule Runtime version: 4.3 --- # Configure the Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt 1. In your Mule app, add a Cache scope to a flow. 2. Click to open the General tab for the Cache scope. 3. Configure the Cache scope: - Provide a Display Name. - Select a Caching Strategy. Examples: - From the UI: `My_Caching_Strategy` - In the Studio XML: `cachingStrategy-ref="My_Caching_Strategy"` MuleSoft recommends that you reference a Caching Strategy that uses an ObjectStore instead of using the default in a production environment. If you need to create a Caching Strategy, see the procedure in [See Also](#see-also). 4. Opt to set up a filter for specific payloads if you need one. Example that uses a DataWeave expression: `filterExpression="#[user.isPremium()]"` If the message matches the expression(s), Mule executes the Caching Strategy. If the message does not match expression(s), Mule processes the message through all message processors within the Cache scope but never saves or produces cached responses. ## Example Cache Scope Configuration The following example shows the configuration of a Caching Strategy, which is then referenced by a Cache Scope that contains a Database Select operation and a Transform component: ```xml ``` ## See Also [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.3/cache-scope-strategy) [Cache Scope](https://docs.mulesoft.com/mule-runtime/4.3/cache-scope) --- product: Mule Runtime version: 4.4 --- # Configure the Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt 1. In your Mule app, add a Cache scope to a flow. 2. Click to open the General tab for the Cache scope. 3. Configure the Cache scope: - Provide a Display Name. - Select a Caching Strategy. Examples: - From the UI: `My_Caching_Strategy` - In the Studio XML: `cachingStrategy-ref="My_Caching_Strategy"` MuleSoft recommends that you reference a Caching Strategy that uses an ObjectStore instead of using the default in a production environment. If you need to create a Caching Strategy, see the procedure in [See Also](#see-also). 4. Opt to set up a filter for specific payloads if you need one. Example that uses a DataWeave expression: `filterExpression="#[user.isPremium()]"` If the message matches the expression(s), Mule executes the Caching Strategy. If the message does not match expression(s), Mule processes the message through all message processors within the Cache scope but never saves or produces cached responses. ## Example Cache Scope Configuration The following example shows the configuration of a Caching Strategy, which is then referenced by a Cache Scope that contains a Database Select operation and a Transform component: ```xml ``` ## See Also [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.4/cache-scope-strategy) [Cache Scope](https://docs.mulesoft.com/mule-runtime/4.4/cache-scope) --- product: Mule Runtime version: 4.6 --- # Configure the Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt 1. In your Mule app, add a Cache scope to a flow. 2. Click to open the General tab for the Cache scope. 3. Configure the Cache scope: - Provide a Display Name. - Select a Caching Strategy. Examples: - From the UI: `My_Caching_Strategy` - In the Studio XML: `cachingStrategy-ref="My_Caching_Strategy"` MuleSoft recommends that you reference a Caching Strategy that uses an ObjectStore instead of using the default in a production environment. If you need to create a Caching Strategy, see the procedure in [See Also](#see-also). 4. Opt to set up a filter for specific payloads if you need one. Example that uses a DataWeave expression: `filterExpression="#[user.isPremium()]"` If the message matches the expression(s), Mule executes the Caching Strategy. If the message does not match expression(s), Mule processes the message through all message processors within the Cache scope but never saves or produces cached responses. ## Example Cache Scope Configuration The following example shows the configuration of a Caching Strategy, which is then referenced by a Cache Scope that contains a Database Select operation and a Transform component: ```xml ``` ## See Also [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.6/cache-scope-strategy) [Cache Scope](https://docs.mulesoft.com/mule-runtime/4.6/cache-scope) --- product: Mule Runtime version: 4.9 --- # Configure the Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt 1. In your Mule app, add a Cache scope to a flow. 2. Click to open the General tab for the Cache scope. 3. Configure the Cache scope: - Provide a Display Name. - Select a Caching Strategy. Examples: - From the UI: `My_Caching_Strategy` - In the Studio XML: `cachingStrategy-ref="My_Caching_Strategy"` MuleSoft recommends that you reference a Caching Strategy that uses an ObjectStore instead of using the default in a production environment. If you need to create a Caching Strategy, see the procedure in [See Also](#see-also). 4. Opt to set up a filter for specific payloads if you need one. Example that uses a DataWeave expression: `filterExpression="#[user.isPremium()]"` If the message matches the expression(s), Mule executes the Caching Strategy. If the message does not match expression(s), Mule processes the message through all message processors within the Cache scope but never saves or produces cached responses. ## Example Cache Scope Configuration The following example shows the configuration of a Caching Strategy, which is then referenced by a Cache Scope that contains a Database Select operation and a Transform component: ```xml ``` ## See Also [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.9/cache-scope-strategy) [Cache Scope](https://docs.mulesoft.com/mule-runtime/4.9/cache-scope) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Configure the Cache Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt 1. In your Mule app, add a Cache scope to a flow. 2. Click to open the General tab for the Cache scope. 3. Configure the Cache scope: - Provide a Display Name. - Select a Caching Strategy. Examples: - From the UI: `My_Caching_Strategy` - In the Studio XML: `cachingStrategy-ref="My_Caching_Strategy"` MuleSoft recommends that you reference a Caching Strategy that uses an ObjectStore instead of using the default in a production environment. If you need to create a Caching Strategy, see the procedure in [See Also](#see-also). 4. Opt to set up a filter for specific payloads if you need one. Example that uses a DataWeave expression: `filterExpression="#[user.isPremium()]"` If the message matches the expression(s), Mule executes the Caching Strategy. If the message does not match expression(s), Mule processes the message through all message processors within the Cache scope but never saves or produces cached responses. ## Example Cache Scope Configuration The following example shows the configuration of a Caching Strategy, which is then referenced by a Cache Scope that contains a Database Select operation and a Transform component: ```xml ``` ## See Also [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/latest/cache-scope-strategy) [Cache Scope](https://docs.mulesoft.com/mule-runtime/latest/cache-scope) --- product: Mule Runtime version: 4.11 keywords: tls, https, ssl, secure messages, encryption, keystore, truststore --- # Configure TLS with Keystores and Truststores > For the full documentation index, see: https://docs.mulesoft.com/llms.txt TLS is a cryptographic protocol that provides communications security for your Mule app. TLS offers many different ways of exchanging keys for authentication, encrypting data, and guaranteeing message integrity. This topic describes TLS as supported by Mule and how to configure TLS in Mule apps. ## TLS Compatibility Matrix TLS compatibility differs by Mule deployment model and TLS version.
TLS VersionOn-PremisesCloudHubAnypoint Runtime Fabric

1.3

Supported when running Mule on a JDK that supports TLS 1.3 but not enabled by default

Supported for Mule apps hosted in this deployment model

Supported and enabled when running on a JDK that supports TLS 1.3

1.2

Supported and enabled by all deployment models

## The tls:context Element The `tls:context` element is used for all connectors that support TLS. For example, you can configure TLS in HTTP (server and client), FTPS (client), Email (client) or Sockets (client) connectors, among others. > [!NOTE] If a connector supports TLS, Studio shows either: > > - A **TLS/SSL** tab on that connector’s Global Elements Properties. > > - A **TLS Configuration** field on the **General** tab of that connector’s Global Element > Properties. ## The TLS-Enabled Server and Client A TLS-enabled server contains a private key and a public certificate: - The private key never leaves the server. - The public certificate is exposed through TLS. TLS-enabled clients verify that they trust the server by validating the public certificate against their own set of trusted certificates. To use TLS communications security in Mule 4, import certificates and private keys into a keystore file. Truststore files are also keystores that by convention include only public certificates of trusted servers. While there’s a default Java truststore, there is no default Java keystore in the standard JRE distribution. Add your own keystore to the TLS context. You likely already have corporate certificates for your client apps and don’t need to create them. Often, these certificates work with the JRE truststore, so no setup is required in the TLS context. A well-known Certificate Authority (CA) can generate certificates, or you can generate a certificate locally without external approval (self-signed certificate). A truststore contains certificates from trusted CAs that the client uses to verify a certificate presented by the server. ## Keystores and Truststores In a Mule configuration, the `tls:trust-store` and `tls:key-store` elements allow you to reference specific certificates and keys. If you don’t specify a `tls:trust-store`, Mule uses the default Java truststore, which is maintained by Java and updated automatically when Java is updated. This helps make sure that certificates from Certificate Authorities (CAs) remain current. Using a custom Java Trust Store isn’t the standard approach in MuleSoft and can lead to connectivity issues with the MuleSoft control plane when MuleSoft certificates are renewed. > [!IMPORTANT] Use the default Java truststore to avoid connectivity issues. If you use a custom > truststore, you’re responsible for managing and updating it. Truststore and keystore contents differ depending on whether they are used for clients or servers: - For servers: the truststore contains certificates of the trusted clients, the keystore contains the private and public key of the server. - For clients: the truststore contains certificates of the trusted servers, the keystore contains the private and public key of the client. Adding both a keystore and a truststore to the configuration implements two-way TLS authentication also known as mutual authentication. The keystore contains one or two passwords: - `password` accesses the entire keystore file. - `keyPassword` accesses the server’s private key inside the keystore. ## Client Configuration If the `tls:context` has an empty truststore defined, then the default values of the JVM are used, which usually include a truststore with certificates for all the major certifying authorities. Consider the following scenarios: - When the truststore is defined inline: - When the truststore is defined with a global element: If the client requires a certificate from the server that it is trying to connect to, then add the `tls:trust-store` element. Set `path` to the location within the artifact of the truststore file that contains the certificates of the trusted servers. If the server validates certificates from the clients, then the `tls:key-store` element should be added with `path` set to the location within the artifact of the keystore file that contains the private/public keys of the client. See [Configure TLS in Mule 4](#configure-tls-in-mule-4) for configuration instructions. ## Server Configuration The `tls:context` must contain a `tls:key-store` element to listen for a request using a secure connection such as HTTPS. Set `path` to the location within the artifact of the keystore file that contains the private/public keys of the server. If the server needs to validate certificates from clients, add a `tls:trust-store` element and set `path` to the location within the artifact of the trust store file that contains the certificates of the trusted clients. Mule supports many types of keystores, including: - `JCEKS` - `PKCS12` - `JKS` Specify your keystore type in the JRE. To fully configure TLS for a Mule app: 1. [Generate a keystore and a truststore](#generate-a-keystore), using the Java Keytool from Oracle. 2. [Configure TLS globally for client or server in Mule](#configure-tls-in-mule-4). 3. [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). ## Keystore Generation The standard JDK distribution doesn’t include a keystore by default, use `keytool` to generate your keystores and certificates. The keystore you generate contains a private key and a public certificate. This certificate is self-signed so it isn’t to be trusted by clients unless you share the public certificate with them. ### Requirements Use Java 17 to generate your keystores. Using a different JDK version generates an incompatible keystore that causes an invalid keystore format runtime error when the Mule application tries to read the keystore. ### Generate a Keystore Follow these steps to generate a keystore and export a self-signed certificate. 1. Generate a keystore that exposes your server’s credentials. For example, run one of the following commands: keytool -genkey -keyalg RSA -alias -keystore .jks keytool -genkey -alias -keyalg RSA -keystore .jks -storepass Replace `` with a unique alias of your choice. Replace `` with a password of your choice. Replace `` with the name you want for your keystore. Optionally, you can set the encryption algorithm to ECDSA by specifying `-keyalg EC` instead of `-keyalg RSA`. > [!IMPORTANT] If you don’t specify the encryption algorithm, the tool uses DSA by default which > isn’t compatible with TLS 1.2 and causes the SSL handshake to fail when the Mule app receives > an HTTPS request. 2. Respond to the tool’s prompts. The following output shows example responses: Enter keystore password: mule123 Re-enter new password: mule123 3. Respond to prompts to enter other values. Enter your desired values. The following output shows example responses: What is your first and last name? \[Unknown\]: max What is the name of your organizational unit? \[Unknown\]: MuleSoft What is the name of your organization? \[Unknown\]: MuleSoft Inc What is the name of your City or Locality? \[Unknown\]: San Francisco What is the name of your State or Province? \[Unknown\]: CA What is the two-letter country code for this unit? \[Unknown\]: 01 4. In response to the following prompt, enter: `yes`. Is CN=max, OU=MuleSoft, O=MuleSoft Inc, L=San Francisco, ST=CA, C=01 correct? \[no\]: yes 5. Respond to the following prompt. For example, use the same password by pressing RETURN. Enter key password for (RETURN if same as keystore password): 6. Enter the following command to export a self-signed certificate authenticating the public key. keytool -export -alias -keystore .jks -file .cer Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate. 7. Enter the password you set up for the keystore associated with the certificate: Enter keystore password: mule123 ### Request Signing by a Certification Authority If you want your certificate signed by a Certification Authority (CA), follow these steps: 1. Export your certificate in the standard CSR format. To do so you can run this command: keytool -certreq -keystore .jks -alias -file .csr Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate sign request file. 2. Send the CSR file generated in the previous step to the Certification Authority and follow their instructions to obtain their signature. After you receive the CA’s signature, you can import the signed certificate file through the following command: keytool -import -keystore .jks -alias -file Replace `` with the new desired value. Make sure the alias you define isn’t linked to any existing key, or the process fails. Replace `` with the same value used in the previous steps. Replace `` with the name of the signed certificate you received from the Certification Authority. 1. Export your certificate in the standard PEM format. First verify the keystore type, then export the certificates: keytool -list -v -keystore .jks openssl -in .jks -out .key.pem -nocerts -nodes openssl -in .jks -out .crt.pem -nocerts -nodes Replace `` with the new desired value in keystore type format, for example PKCS12. Replace `` with the name you want for the keystore. Replace `` with the name you want for the PEM file. ## Truststore Generation The standard JRE distribution includes a default trust store with certificates for several major certificate authorities (CA’s) which is used by default in the 'tls:trust-store' element, but you can generate your own if you want greater security or if you use self-signed certificates. To create a trust store, you can use the Oracle Java keytool. The client trusts the server if a chain of trust can be established, either directly to the server (in case its certificate is in the truststore) or through a signing CA whose certificate is present in the truststore; otherwise, the connection fails. A trust store must be defined when using self-signed certificates. ## Configure TLS in Mule 4 To enable TLS for Mule apps, configure the `tls:context` element in the Mule XML configuration file in one of three ways: - [Edit the XML file directly.](#edit-xml-to-configure-tls) - [Use Anypoint Studio 7.](#use-anypoint-studio-to-configure-tls) - [Use Design Center.](#use-design-center-to-configure-tls) Whichever method you use, we recommend you review the information in [Edit XML to Configure TLS](#edit-xml-to-configure-tls) to understand how the attributes of `tls:context` function. ### Edit XML to Configure TLS The `tls:context` element defines TLS communication in a Mule app. Unless you have a special requirement, configure TLS globally and then apply it to each specific use, such as listening for or sending HTTPS requests. #### Globally Define a TLS Element The `tls:context` element defines a configuration for TLS, which can be used from both the client and server sides. The element can be referenced by other configuration objects of other modules or defined as a nested element of one of them. Include at least one of the nested elements: key-store and trust-store. ```xml ``` #### Optional Attributes of the `tls-context` Element Optionally, specify the protocol and cipher suite to enable them: - `enabledProtocols`: The protocols in the global TLS configuration - `enabledCipherSuites`: The cipher suites in global TLS configuration These values are used if there is nothing specified in the global TLS configuration, or if the values are enabled in a global TLS configuration, as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). #### Attributes of the `trust-store` Element The `password` attribute is required if you specify a `path`. Otherwise, the attributes are optional.
AttributeDescription

path

The path to the file within the artifact that contains the trust store.

type

The type of the trust store. Default is JKS.

password

The trust store password. Required if you specify path.

algorithm

The algorithm the trust store uses. Default is SunX509.

insecure

Boolean that determines whether to validate the trust store. If set to true, no validation occurs. Default is false.

> [!IMPORTANT] Setting `insecure` to `true` renders connections vulnerable to attack. Use it only > for prototyping or testing. Never use it in production environments. #### Attributes of the `key-store` Element The attributes other than `path` are optional.
AttributeDescription

path

The path to the file within the artifact that contains the keystore. Required.

type

The type of the keystore. Default is JKS.

password

The keystore password.

keyPassword

The key manager password, which is the password for the private key inside the keystore.

algorithm

The algorithm used in the keystore. Default is SunX509.

> [!NOTE] By default, the `path` attribute loads trust and keystore files as classloader resources. > For on-premises deployments (hybrid or standalone), set the system property > `mule.tlsStores.filesystemLookup.enable` to `true` to enable file system access. ### Use Design Center to Configure TLS You can configure TLS for your app in Design Center. For example, to configure TLS in HTTP Listener: 1. Log into Design Center. 2. Open the project. 3. Open HTTP Listener. 4. In the Configuration tab, click **Edit**. 5. In the TLS tab, fill in the TLS Configuration fields as described above. 6. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ### Use Anypoint Studio to Configure TLS You can configure TLS for your app in Anypoint Studio (Studio). For example, to configure TLS in HTTP Listener: 1. Open Studio Center. 2. Open the project. 3. Open HTTP Listener. 4. In the General tab, select an existing configuration or create a new one. 5. In the HTTP Listener config dialog, select the TLS tab. 6. In the TLS tab, choose the TLS Configuration type **Edit Inline**, and supply the values. 7. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields in the Advanced section as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ## Optional: Specify Protocols and Cipher Suites When a TLS communication takes place between two systems, a negotiation determines which protocol and cipher suite are used. Optionally, administrators can specify the protocols and cipher suites to use, and then app developers can specify which cipher suites and protocols to use in `tls:context`. > [!NOTE] Protocols and cipher suites must be enabled in Mule runtime and individual apps to be > used. If the protocols and cipher suites aren’t enabled in both places, the default Java > environment protocol and cipher suites are used. To configure protocols and cipher suites in the Mule runtime: 1. The Mule admin edits the `/conf` directory in `$MULE_HOME`. `$MULE_HOME` points to the directory where your Mule installation resides, for example `/opt/mule-4.0`. Select the appropriate file where you specify the cipher suites and protocols: - `tls-default.conf` allows fine-tuning when Mule isn’t configured to run in Federal Information Processing Standards (FIPS) security mode. - `tls-fips140-2.conf` allows fine-tuning when Mule is running in FIPS security mode. Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and TLS protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols for an app. 2. The list of protocols and cipher suites that the admin sets in these configuration files can then be constrained locally by what the app developer specifies in an individual `tls:context` element. The app developer specifies a subset of the configured or default values in the `tls:context` element for use by TLS. Configure the protocols and cipher suites in `enabledProtocols` and `enabledCipherSuites` in the `tls:context` element. In the `tls:context` element, you can only reference protocols or cipher suites that are included in the Mule global TLS configuration file or defaults. In `tls:context`, set `enabledProtocols` and `enabledCipherSuite` for a Mule app to the value `default`. After these values are set, TLS uses the following protocols and cipher suites: - Those configured in your global TLS configuration if it exists - The defaults provided by your Java environment if a global TLS configuration doesn’t exist Cipher suite names can be long and reduce the readability of your XML code. To improve readability, keep these names in an external properties file in your Mule project. You can then reference the properties. For example: ```xml ``` ## Test after deployment Example time curl -i -k --cert ./.crt.pem --cert-type PEM --key ./.key.pem https://: Replace `` with the value name defined. Replace `` with the value name defined by Anypoint Platform. Replace `` with the value name defined in the Mule application. ## TLS Configuration Examples You can set up TLS in a Mule XML configuration file for a client or a server. ### Example: Configuring TLS for a Client This example secures an FTPS client by setting up a truststore: ```xml ``` ### Example: Configuring TLS for a Server This example secures an HTTP listener by setting up a keystore: ```xml ``` ### Example: Configuring TLS for Two-Way Authentication This example sets up two-way authentication (also called mutual authentication), for an HTTP listener: ```xml ``` ### Example: Disabling TLS Validations This example uses the `insecure` property to disable validations for prototyping and development. > [!IMPORTANT] Don’t use the `insecure` property in production environments. ```xml ``` ### Example: Adding Additional Cipher Suites and Protocol Restrictions This example enables a protocol and cipher suite for an app, assuming a Mule admin has either specified nothing in the global TLS configuration or enabled the cipher suites and protocols being specified here. Use IANA (Internet Assigned Numbers Authority) naming convention for the cipher suites. Check the [OpenSSL - IANA mapping](https://testssl.sh/openssl-iana.mapping.html) for reference. ```xml ``` ## See Also - [Oracle security](https://docs.oracle.com/javase/8/docs/technotes/tools/) - [Oracle Java keytool](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html) --- product: Mule Runtime version: 4.12 keywords: tls, https, ssl, secure messages, encryption, keystore, truststore --- # Configure TLS with Keystores and Truststores > For the full documentation index, see: https://docs.mulesoft.com/llms.txt TLS is a cryptographic protocol that provides communications security for your Mule app. TLS offers many different ways of exchanging keys for authentication, encrypting data, and guaranteeing message integrity. This topic describes TLS as supported by Mule and how to configure TLS in Mule apps. ## TLS Compatibility Matrix TLS compatibility differs by Mule deployment model and TLS version.
TLS VersionOn-PremisesCloudHubAnypoint Runtime Fabric

1.3

Supported when running Mule on a JDK that supports TLS 1.3 but not enabled by default

Supported for Mule apps hosted in this deployment model

Supported and enabled when running on a JDK that supports TLS 1.3

1.2

Supported and enabled by all deployment models

## The tls:context Element The `tls:context` element is used for all connectors that support TLS. For example, you can configure TLS in HTTP (server and client), FTPS (client), Email (client) or Sockets (client) connectors, among others. > [!NOTE] If a connector supports TLS, Studio shows either: > > - A **TLS/SSL** tab on that connector’s Global Elements Properties. > > - A **TLS Configuration** field on the **General** tab of that connector’s Global Element > Properties. ## The TLS-Enabled Server and Client A TLS-enabled server contains a private key and a public certificate: - The private key never leaves the server. - The public certificate is exposed through TLS. TLS-enabled clients verify that they trust the server by validating the public certificate against their own set of trusted certificates. To use TLS communications security in Mule 4, import certificates and private keys into a keystore file. Truststore files are also keystores that by convention include only public certificates of trusted servers. While there’s a default Java truststore, there is no default Java keystore in the standard JRE distribution. Add your own keystore to the TLS context. You likely already have corporate certificates for your client apps and don’t need to create them. Often, these certificates work with the JRE truststore, so no setup is required in the TLS context. A well-known Certificate Authority (CA) can generate certificates, or you can generate a certificate locally without external approval (self-signed certificate). A truststore contains certificates from trusted CAs that the client uses to verify a certificate presented by the server. ## Keystores and Truststores In a Mule configuration, the `tls:trust-store` and `tls:key-store` elements allow you to reference specific certificates and keys. If you don’t specify a `tls:trust-store`, Mule uses the default Java truststore, which is maintained by Java and updated automatically when Java is updated. This helps make sure that certificates from Certificate Authorities (CAs) remain current. Using a custom Java Trust Store isn’t the standard approach in MuleSoft and can lead to connectivity issues with the MuleSoft control plane when MuleSoft certificates are renewed. > [!IMPORTANT] Use the default Java truststore to avoid connectivity issues. If you use a custom > truststore, you’re responsible for managing and updating it. Truststore and keystore contents differ depending on whether they are used for clients or servers: - For servers: the truststore contains certificates of the trusted clients, the keystore contains the private and public key of the server. - For clients: the truststore contains certificates of the trusted servers, the keystore contains the private and public key of the client. Adding both a keystore and a truststore to the configuration implements two-way TLS authentication also known as mutual authentication. The keystore contains one or two passwords: - `password` accesses the entire keystore file. - `keyPassword` accesses the server’s private key inside the keystore. ## Client Configuration If the `tls:context` has an empty truststore defined, then the default values of the JVM are used, which usually include a truststore with certificates for all the major certifying authorities. Consider the following scenarios: - When the truststore is defined inline: - When the truststore is defined with a global element: If the client requires a certificate from the server that it is trying to connect to, then add the `tls:trust-store` element. Set `path` to the location within the artifact of the truststore file that contains the certificates of the trusted servers. If the server validates certificates from the clients, then the `tls:key-store` element should be added with `path` set to the location within the artifact of the keystore file that contains the private/public keys of the client. See [Configure TLS in Mule 4](#configure-tls-in-mule-4) for configuration instructions. ## Server Configuration The `tls:context` must contain a `tls:key-store` element to listen for a request using a secure connection such as HTTPS. Set `path` to the location within the artifact of the keystore file that contains the private/public keys of the server. If the server needs to validate certificates from clients, add a `tls:trust-store` element and set `path` to the location within the artifact of the trust store file that contains the certificates of the trusted clients. Mule supports many types of keystores, including: - `JCEKS` - `PKCS12` - `JKS` Specify your keystore type in the JRE. To fully configure TLS for a Mule app: 1. [Generate a keystore and a truststore](#generate-a-keystore), using the Java Keytool from Oracle. 2. [Configure TLS globally for client or server in Mule](#configure-tls-in-mule-4). 3. [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). ## Keystore Generation The standard JDK distribution doesn’t include a keystore by default, use `keytool` to generate your keystores and certificates. The keystore you generate contains a private key and a public certificate. This certificate is self-signed so it isn’t to be trusted by clients unless you share the public certificate with them. ### Requirements Use Java 17 to generate your keystores. Using a different JDK version generates an incompatible keystore that causes an invalid keystore format runtime error when the Mule application tries to read the keystore. ### Generate a Keystore Follow these steps to generate a keystore and export a self-signed certificate. 1. Generate a keystore that exposes your server’s credentials. For example, run one of the following commands: keytool -genkey -keyalg RSA -alias -keystore .jks keytool -genkey -alias -keyalg RSA -keystore .jks -storepass Replace `` with a unique alias of your choice. Replace `` with a password of your choice. Replace `` with the name you want for your keystore. Optionally, you can set the encryption algorithm to ECDSA by specifying `-keyalg EC` instead of `-keyalg RSA`. > [!IMPORTANT] If you don’t specify the encryption algorithm, the tool uses DSA by default which > isn’t compatible with TLS 1.2 and causes the SSL handshake to fail when the Mule app receives > an HTTPS request. 2. Respond to the tool’s prompts. The following output shows example responses: Enter keystore password: mule123 Re-enter new password: mule123 3. Respond to prompts to enter other values. Enter your desired values. The following output shows example responses: What is your first and last name? \[Unknown\]: max What is the name of your organizational unit? \[Unknown\]: MuleSoft What is the name of your organization? \[Unknown\]: MuleSoft Inc What is the name of your City or Locality? \[Unknown\]: San Francisco What is the name of your State or Province? \[Unknown\]: CA What is the two-letter country code for this unit? \[Unknown\]: 01 4. In response to the following prompt, enter: `yes`. Is CN=max, OU=MuleSoft, O=MuleSoft Inc, L=San Francisco, ST=CA, C=01 correct? \[no\]: yes 5. Respond to the following prompt. For example, use the same password by pressing RETURN. Enter key password for (RETURN if same as keystore password): 6. Enter the following command to export a self-signed certificate authenticating the public key. keytool -export -alias -keystore .jks -file .cer Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate. 7. Enter the password you set up for the keystore associated with the certificate: Enter keystore password: mule123 ### Request Signing by a Certification Authority If you want your certificate signed by a Certification Authority (CA), follow these steps: 1. Export your certificate in the standard CSR format. To do so you can run this command: keytool -certreq -keystore .jks -alias -file .csr Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate sign request file. 2. Send the CSR file generated in the previous step to the Certification Authority and follow their instructions to obtain their signature. After you receive the CA’s signature, you can import the signed certificate file through the following command: keytool -import -keystore .jks -alias -file Replace `` with the new desired value. Make sure the alias you define isn’t linked to any existing key, or the process fails. Replace `` with the same value used in the previous steps. Replace `` with the name of the signed certificate you received from the Certification Authority. 1. Export your certificate in the standard PEM format. First verify the keystore type, then export the certificates: keytool -list -v -keystore .jks openssl -in .jks -out .key.pem -nocerts -nodes openssl -in .jks -out .crt.pem -nocerts -nodes Replace `` with the new desired value in keystore type format, for example PKCS12. Replace `` with the name you want for the keystore. Replace `` with the name you want for the PEM file. ## Truststore Generation The standard JRE distribution includes a default trust store with certificates for several major certificate authorities (CA’s) which is used by default in the 'tls:trust-store' element, but you can generate your own if you want greater security or if you use self-signed certificates. To create a trust store, you can use the Oracle Java keytool. The client trusts the server if a chain of trust can be established, either directly to the server (in case its certificate is in the truststore) or through a signing CA whose certificate is present in the truststore; otherwise, the connection fails. A trust store must be defined when using self-signed certificates. ## Configure TLS in Mule 4 To enable TLS for Mule apps, configure the `tls:context` element in the Mule XML configuration file in one of three ways: - [Edit the XML file directly.](#edit-xml-to-configure-tls) - [Use Anypoint Studio 7.](#use-anypoint-studio-to-configure-tls) - [Use Design Center.](#use-design-center-to-configure-tls) Whichever method you use, we recommend you review the information in [Edit XML to Configure TLS](#edit-xml-to-configure-tls) to understand how the attributes of `tls:context` function. ### Edit XML to Configure TLS The `tls:context` element defines TLS communication in a Mule app. Unless you have a special requirement, configure TLS globally and then apply it to each specific use, such as listening for or sending HTTPS requests. #### Globally Define a TLS Element The `tls:context` element defines a configuration for TLS, which can be used from both the client and server sides. The element can be referenced by other configuration objects of other modules or defined as a nested element of one of them. Include at least one of the nested elements: key-store and trust-store. ```xml ``` #### Optional Attributes of the `tls-context` Element Optionally, specify the protocol and cipher suite to enable them: - `enabledProtocols`: The protocols in the global TLS configuration - `enabledCipherSuites`: The cipher suites in global TLS configuration These values are used if there is nothing specified in the global TLS configuration, or if the values are enabled in a global TLS configuration, as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). #### Attributes of the `trust-store` Element The `password` attribute is required if you specify a `path`. Otherwise, the attributes are optional.
AttributeDescription

path

The path to the file within the artifact that contains the trust store.

type

The type of the trust store. Default is JKS.

password

The trust store password. Required if you specify path.

algorithm

The algorithm the trust store uses. Default is SunX509.

insecure

Boolean that determines whether to validate the trust store. If set to true, no validation occurs. Default is false.

> [!IMPORTANT] Setting `insecure` to `true` renders connections vulnerable to attack. Use it only > for prototyping or testing. Never use it in production environments. #### Attributes of the `key-store` Element The attributes other than `path` are optional.
AttributeDescription

path

The path to the file within the artifact that contains the keystore. Required.

type

The type of the keystore. Default is JKS.

password

The keystore password.

keyPassword

The key manager password, which is the password for the private key inside the keystore.

algorithm

The algorithm used in the keystore. Default is SunX509.

> [!NOTE] By default, the `path` attribute loads trust and keystore files as classloader resources. > For on-premises deployments (hybrid or standalone), set the system property > `mule.tlsStores.filesystemLookup.enable` to `true` to enable file system access. ### Use Design Center to Configure TLS You can configure TLS for your app in Design Center. For example, to configure TLS in HTTP Listener: 1. Log into Design Center. 2. Open the project. 3. Open HTTP Listener. 4. In the Configuration tab, click **Edit**. 5. In the TLS tab, fill in the TLS Configuration fields as described above. 6. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ### Use Anypoint Studio to Configure TLS You can configure TLS for your app in Anypoint Studio (Studio). For example, to configure TLS in HTTP Listener: 1. Open Studio Center. 2. Open the project. 3. Open HTTP Listener. 4. In the General tab, select an existing configuration or create a new one. 5. In the HTTP Listener config dialog, select the TLS tab. 6. In the TLS tab, choose the TLS Configuration type **Edit Inline**, and supply the values. 7. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields in the Advanced section as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ## Optional: Specify Protocols and Cipher Suites When a TLS communication takes place between two systems, a negotiation determines which protocol and cipher suite are used. Optionally, administrators can specify the protocols and cipher suites to use, and then app developers can specify which cipher suites and protocols to use in `tls:context`. > [!NOTE] Protocols and cipher suites must be enabled in Mule runtime and individual apps to be > used. If the protocols and cipher suites aren’t enabled in both places, the default Java > environment protocol and cipher suites are used. To configure protocols and cipher suites in the Mule runtime: 1. The Mule admin edits the `/conf` directory in `$MULE_HOME`. `$MULE_HOME` points to the directory where your Mule installation resides, for example `/opt/mule-4.0`. Select the appropriate file where you specify the cipher suites and protocols: - `tls-default.conf` allows fine-tuning when Mule isn’t configured to run in Federal Information Processing Standards (FIPS) security mode. - `tls-fips140-2.conf` allows fine-tuning when Mule is running in FIPS security mode. Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and TLS protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols for an app. 2. The list of protocols and cipher suites that the admin sets in these configuration files can then be constrained locally by what the app developer specifies in an individual `tls:context` element. The app developer specifies a subset of the configured or default values in the `tls:context` element for use by TLS. Configure the protocols and cipher suites in `enabledProtocols` and `enabledCipherSuites` in the `tls:context` element. In the `tls:context` element, you can only reference protocols or cipher suites that are included in the Mule global TLS configuration file or defaults. In `tls:context`, set `enabledProtocols` and `enabledCipherSuite` for a Mule app to the value `default`. After these values are set, TLS uses the following protocols and cipher suites: - Those configured in your global TLS configuration if it exists - The defaults provided by your Java environment if a global TLS configuration doesn’t exist Cipher suite names can be long and reduce the readability of your XML code. To improve readability, keep these names in an external properties file in your Mule project. You can then reference the properties. For example: ```xml ``` ## Test after deployment Example time curl -i -k --cert ./.crt.pem --cert-type PEM --key ./.key.pem https://: Replace `` with the value name defined. Replace `` with the value name defined by Anypoint Platform. Replace `` with the value name defined in the Mule application. ## TLS Configuration Examples You can set up TLS in a Mule XML configuration file for a client or a server. ### Example: Configuring TLS for a Client This example secures an FTPS client by setting up a truststore: ```xml ``` ### Example: Configuring TLS for a Server This example secures an HTTP listener by setting up a keystore: ```xml ``` ### Example: Configuring TLS for Two-Way Authentication This example sets up two-way authentication (also called mutual authentication), for an HTTP listener: ```xml ``` ### Example: Disabling TLS Validations This example uses the `insecure` property to disable validations for prototyping and development. > [!IMPORTANT] Don’t use the `insecure` property in production environments. ```xml ``` ### Example: Adding Additional Cipher Suites and Protocol Restrictions This example enables a protocol and cipher suite for an app, assuming a Mule admin has either specified nothing in the global TLS configuration or enabled the cipher suites and protocols being specified here. Use IANA (Internet Assigned Numbers Authority) naming convention for the cipher suites. Check the [OpenSSL - IANA mapping](https://testssl.sh/openssl-iana.mapping.html) for reference. ```xml ``` ## See Also - [Oracle security](https://docs.oracle.com/javase/8/docs/technotes/tools/) - [Oracle Java keytool](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html) --- product: Mule Runtime version: 4.3 keywords: tls, https, ssl, secure messages, encryption, keystore, truststore --- # Configure TLS with Keystores and Truststores > For the full documentation index, see: https://docs.mulesoft.com/llms.txt TLS is a cryptographic protocol that provides communications security for your Mule app. TLS offers many different ways of exchanging keys for authentication, encrypting data, and guaranteeing message integrity. This topic describes TLS as supported by Mule and how to configure TLS in Mule apps. ## TLS Compatibility Matrix TLS compatibility differs by Mule deployment model and TLS version.
TLS VersionOn-PremisesCloudHubAnypoint Runtime Fabric

1.3

Supported when running Mule on a JDK that supports TLS 1.3 but not enabled by default

Not supported

Supported and enabled when running on a JDK that supports TLS 1.3

1.2

Supported and enabled by all deployment models

1.1

Supported and enabled by all deployment models

## The tls:context Element The `tls:context` element is used for all connectors that support TLS. For example, you can configure TLS in HTTP (server and client), FTPS (client), Email (client) or Sockets (client) connectors, among others. > [!NOTE] If a connector supports TLS, Studio shows either: > > - A **TLS/SSL** tab on that connector’s Global Elements Properties. > > - A **TLS Configuration** field on the **General** tab of that connector’s Global Element > Properties. ## The TLS-Enabled Server and Client A TLS-enabled server contains a private key and a public certificate: - The private key never leaves the server. - The public certificate is exposed through TLS. TLS-enabled clients verify that they trust the server by validating the public certificate against their own set of trusted certificates. To use TLS communications security in Mule 4, import certificates and private keys into a keystore file. Truststore files are also keystores that by convention include only public certificates of trusted servers. While there’s a default Java truststore, there is no default Java keystore in the standard JRE distribution. Add your own keystore to the TLS context. You likely already have corporate certificates for your client apps and don’t need to create them. Often, these certificates work with the JRE truststore, so no setup is required in the TLS context. A well-known Certificate Authority (CA) can generate certificates, or you can generate a certificate locally without external approval (self-signed certificate). A truststore contains certificates from trusted CAs that the client uses to verify a certificate presented by the server. ## Keystores and Truststores In a Mule configuration, the `tls:trust-store` and `tls:key-store` elements allow you to reference specific certificates and keys. If you don’t specify a `tls:trust-store`, Mule uses the default Java truststore, which is maintained by Java and updated automatically when Java is updated. This helps make sure that certificates from Certificate Authorities (CAs) remain current. Using a custom Java Trust Store isn’t the standard approach in MuleSoft and can lead to connectivity issues with the MuleSoft control plane when MuleSoft certificates are renewed. > [!IMPORTANT] Use the default Java truststore to avoid connectivity issues. If you use a custom > truststore, you’re responsible for managing and updating it. Truststore and keystore contents differ depending on whether they are used for clients or servers: - For servers: the truststore contains certificates of the trusted clients, the keystore contains the private and public key of the server. - For clients: the truststore contains certificates of the trusted servers, the keystore contains the private and public key of the client. Adding both a keystore and a truststore to the configuration implements two-way TLS authentication also known as mutual authentication. The keystore contains one or two passwords: - `password` accesses the entire keystore file. - `keyPassword` accesses the server’s private key inside the keystore. ## Client Configuration If the `tls:context` has an empty truststore defined, then the default values of the JVM are used, which usually include a truststore with certificates for all the major certifying authorities. Consider the following scenarios: - When the truststore is defined inline: - When the truststore is defined with a global element: If the client requires a certificate from the server that it is trying to connect to, then add the `tls:trust-store` element. Set `path` to the location of the truststore file that contains the certificates of the trusted servers. If the server validates certificates from the clients, then the `tls:key-store` element should be added with `path` set to the location of the keystore file that contains the private/public keys of the client. See [Configure TLS in Mule 4](#configure-tls-in-mule-4) for configuration instructions. ## Server Configuration The `tls:context` must contain a `tls:key-store` element to listen for a request using a secure connection such as HTTPS. Set `path` to the location of the keystore file that contains the private/public keys of the server. If the server needs to validate certificates from clients, add a `tls:trust-store` element and set `path` to the location of the trust store file that contains the certificates of the trusted clients. Mule supports many types of keystores, including: - `JCEKS` - `PKCS12` - `JKS` Specify your keystore type in the JRE. To fully configure TLS for a Mule app: 1. [Generate a keystore and a truststore](#generate-a-keystore), using the Java Keytool from Oracle. 2. [Configure TLS globally for client or server in Mule](#configure-tls-in-mule-4). 3. [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). ## Keystore Generation The standard JDK distribution does not include a keystore by default, use `keytool` to generate your keystores and certificates. The keystore you generate contains a private key and a public certificate. This certificate is self-signed so it is not to be trusted by clients unless you share the public certificate with them. ### Requirements Use Java 8 to generate your keystores. Using a different JDK version generates an incompatible keystore that causes an invalid keystore format runtime error when the Mule application tries to read the keystore. ### Generate a Keystore Follow these steps to generate a keystore and export a self-signed certificate. 1. Generate a keystore that exposes your server’s credentials. For example, run the following command: keytool -genkey -keyalg RSA -alias -keystore .jks Replace `` with a unique alias of your choice. Replace `` with the name you want for your keystore. Optionally, you can set the encryption algorithm to ECDSA by specifying `-keyalg EC` instead of `-keyalg RSA`. > [!IMPORTANT] If you do not specify the encryption algorithm, the tool uses DSA by default > which is not compatible with TLS 1.2 and causes the SSL handshake to fail when the Mule app > receives an HTTPS request. 2. Respond to the tool’s prompts. The following output shows example responses: Enter keystore password: mule123 Re-enter new password: mule123 3. Respond to prompts to enter other values. Enter your desired values. The following output shows example responses: What is your first and last name? \[Unknown\]: max What is the name of your organizational unit? \[Unknown\]: MuleSoft What is the name of your organization? \[Unknown\]: MuleSoft Inc What is the name of your City or Locality? \[Unknown\]: San Francisco What is the name of your State or Province? \[Unknown\]: CA What is the two-letter country code for this unit? \[Unknown\]: 01 4. In response to the following prompt, enter: `yes`. Is CN=max, OU=MuleSoft, O=MuleSoft Inc, L=San Francisco, ST=CA, C=01 correct? \[no\]: yes 5. Respond to the following prompt. For example, use the same password by pressing RETURN. Enter key password for (RETURN if same as keystore password): 6. Enter the following command to export a self-signed certificate authenticating the public key. keytool -export -alias -keystore .jks -file .cer Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate. 7. Enter the password you set up for the keystore associated with the certificate: Enter keystore password: mule123 ### Request Signing by a Certification Authority If you want your certificate signed by a Certification Authority (CA), follow these steps: 1. Export your certificate in the standard CSR format. To do so you can run this command: keytool -certreq -keystore .jks -alias -file .csr Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate sign request file. 2. Send the CSR file generated in the previous step to the Certification Authority and follow their instructions to obtain their signature. After you receive the CA’s signature, you can import the signed certificate file through the following command: keytool -import -keystore .jks -alias -file Replace `` with the a new desired value, the alias you define must not be linked to any existing key or the process fails. Replace `` with the same value used in the previous steps. Replace `` with the name of the signed certificate you received from the Certification Authority. ## Truststore Generation The standard JRE distribution includes a default trust store with certificates for several major certificate authorities (CA’s) which is used by default in the 'tls:trust-store' element, but you can generate your own if you want greater security or if you use self-signed certificates. To create a trust store, you can use the Oracle Java keytool. The client trusts the server if a chain of trust can be established, either directly to the server (in case its certificate is in the truststore) or through a signing CA whose certificate is present in the truststore; otherwise, the connection fails. A trust store must be defined when using self-signed certificates. ## Configure TLS in Mule 4 To enable TLS for Mule apps, configure the `tls:context` element in the Mule XML configuration file in one of three ways: - [Edit the XML file directly.](#edit-xml-to-configure-tls) - [Use Anypoint Studio 7.](#use-anypoint-studio-to-configure-tls) - [Use Design Center.](#use-design-center-to-configure-tls) Whichever method you use, we recommend you review the information in [Edit XML to Configure TLS](#edit-xml-to-configure-tls) to understand how the attributes of `tls:context` function. ### Edit XML to Configure TLS The `tls:context` element defines TLS communication in a Mule app. Unless you have a special requirement, configure TLS globally and then apply it to each specific use, such as listening for or sending HTTPS requests. #### Globally Define a TLS Element The `tls:context` element defines a configuration for TLS, which can be used from both the client and server sides. The element can be referenced by other configuration objects of other modules or defined as a nested element of one of them. Include at least one of the nested elements: key-store and trust-store. ```xml ``` #### Optional Attributes of the `tls-context` Element Optionally, specify the protocol and cipher suite to enable them: - `enabledProtocols`: The protocols in the the global TLS configuration - `enabledCipherSuites`: The cipher suites in global TLS configuration These values are used if there is nothing specified in the global TLS configuration, or if the values are enabled in a global TLS configuration, as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). #### Attributes of the `trust-store` Element The `password` attribute is required if you specify a `path`. Otherwise, the attributes are optional. - `path`: The path to the file that contains the trust store - `type`: The type of the trust store. Default = JKS - `password`: The trust store password (required if you specify `path`) - `algorithm`: The algorithm the trust store uses. Default = `SunX509` - `insecure`: Boolean that determines whether or not to validate the truststore. If set to `true`, no validation occurs. The default value is `false`. > [!IMPORTANT] Setting `insecure` to `true` renders connections vulnerable to attack. Use it only > for prototyping or testing. Never use it in production environments. #### Attributes of the `key-store` Element The attributes other than `path` are optional. - `path`: The path to the file that contains the keystore (required) - `type`: The type of the keystore (default JKS) - `password`: The keystore password - `keyPassword`: The key manager password, which is the password for the private key inside the keystore - `algorithm`: The algorithm used in the keystore. The default value is `SunX509`. ### Use Design Center to Configure TLS You can configure TLS for your app in Design Center. For example, to configure TLS in HTTP Listener: 1. Log into Design Center. 2. Open the project. 3. Open HTTP Listener. 4. In the Configuration tab, click **Edit**. 5. In the TLS tab, fill in the TLS Configuration fields as described above. 6. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ### Use Anypoint Studio to Configure TLS You can configure TLS for your app in Anypoint Studio (Studio). For example, to configure TLS in HTTP Listener: 1. Open Studio Center. 2. Open the project. 3. Open HTTP Listener. 4. In the General tab, select an existing configuration or create a new one. 5. In the HTTP Listener config dialog, select the TLS tab. 6. In the TLS tab, choose the TLS Configuration type **Edit Inline**, and supply the values. 7. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields in the Advanced section as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ## Optional: Specify Protocols and Cipher Suites When a TLS communication takes place between two systems, a negotiation determines which protocol and cipher suite are used. Optionally, administrators can specify the protocols and cipher suites to use, and then app developers can specify which cipher suites and protocols to use in `tls:context`. > [!NOTE] Protocols and cipher suites must be enabled in Mule Runtime and individual apps to be > used. If the protocols and cipher suites aren’t enabled in both places, the default Java > environment protocol and cipher suites are used. To configure protocols and cipher suites in the Mule Runtime: 1. The Mule admin edits the `/conf` directory in `$MULE_HOME`. `$MULE_HOME` points to the directory where your Mule installation resides, for example `/opt/mule-4.0`. Select the appropriate file where you specify the cipher suites and protocols: - `tls-default.conf` allows fine-tuning when Mule is not configured to run in Federal Information Processing Standards (FIPS) security mode. - `tls-fips140-2.conf` allows fine-tuning when Mule is running in FIPS security mode. Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and TLS protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols for an app. 2. The list of protocols and cipher suites that the admin sets in these configuration files can then be constrained locally by what the app developer specifies in an individual `tls:context` element. The app developer specifies a subset of the configured or default values in the `tls:context` element for use by TLS. Configure the protocols and cipher suites in `enabledProtocols` and `enabledCipherSuites` in the `tls:context` element. In the `tls:context` element, you can only reference protocols or cipher suites that are included in the Mule global TLS configuration file or defaults. In `tls:context`, set `enabledProtocols` and `enabledCipherSuite` for a Mule app to the value `default`. After these values are set, TLS uses the following protocols and cipher suites: - Those configured in your global TLS configuration if it exists - The defaults provided by your Java environment if a global TLS configuration does not exist Cipher suite names can be long and reduce the readability of your XML code. To improve readability, keep these names in an external properties file in your Mule project. You can then reference the properties. For example: ```xml ``` ## TLS Configuration Examples You can set up TLS in a Mule XML configuration file for a client or a server. ### Example: Configuring TLS for a Client This example secures an FTPS client by setting up a truststore: ```xml ``` ### Example: Configuring TLS for a Server This example secures an HTTP listener by setting up a keystore: ```xml ``` ### Example: Configuring TLS for Two-Way Authentication This example sets up two-way authentication (also called mutual authentication), for an HTTP listener: ```xml ``` ### Example: Disabling TLS Validations This example uses the `insecure` property to disable validations for prototyping and development. > [!IMPORTANT] Do not use the `insecure` property in production environments. ```xml ``` ### Example: Adding Additional Cipher Suites and Protocol Restrictions This example enables a protocol and cipher suite for an app, assuming a Mule admin has either specified nothing in the global TLS configuration or enabled the cipher suites and protocols being specified here. ```xml ``` ## See Also - [Oracle security](https://docs.oracle.com/javase/8/docs/technotes/tools/) - [Oracle Java keytool](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html) --- product: Mule Runtime version: 4.4 keywords: tls, https, ssl, secure messages, encryption, keystore, truststore --- # Configure TLS with Keystores and Truststores > For the full documentation index, see: https://docs.mulesoft.com/llms.txt TLS is a cryptographic protocol that provides communications security for your Mule app. TLS offers many different ways of exchanging keys for authentication, encrypting data, and guaranteeing message integrity. This topic describes TLS as supported by Mule and how to configure TLS in Mule apps. ## TLS Compatibility Matrix TLS compatibility differs by Mule deployment model and TLS version.
TLS VersionOn-PremisesCloudHubAnypoint Runtime Fabric

1.3

Supported when running Mule on a JDK that supports TLS 1.3 but not enabled by default

Supported for Mule apps hosted in this deployment model

Supported and enabled when running on a JDK that supports TLS 1.3

1.2

Supported and enabled by all deployment models

1.1

Supported and enabled by all deployment models

## The tls:context Element The `tls:context` element is used for all connectors that support TLS. For example, you can configure TLS in HTTP (server and client), FTPS (client), Email (client) or Sockets (client) connectors, among others. > [!NOTE] If a connector supports TLS, Studio shows either: > > - A **TLS/SSL** tab on that connector’s Global Elements Properties. > > - A **TLS Configuration** field on the **General** tab of that connector’s Global Element > Properties. ## The TLS-Enabled Server and Client A TLS-enabled server contains a private key and a public certificate: - The private key never leaves the server. - The public certificate is exposed through TLS. TLS-enabled clients verify that they trust the server by validating the public certificate against their own set of trusted certificates. To use TLS communications security in Mule 4, import certificates and private keys into a keystore file. Truststore files are also keystores that by convention include only public certificates of trusted servers. While there’s a default Java truststore, there is no default Java keystore in the standard JRE distribution. Add your own keystore to the TLS context. You likely already have corporate certificates for your client apps and don’t need to create them. Often, these certificates work with the JRE truststore, so no setup is required in the TLS context. A well-known Certificate Authority (CA) can generate certificates, or you can generate a certificate locally without external approval (self-signed certificate). A truststore contains certificates from trusted CAs that the client uses to verify a certificate presented by the server. ## Keystores and Truststores In a Mule configuration, the `tls:trust-store` and `tls:key-store` elements allow you to reference specific certificates and keys. If you don’t specify a `tls:trust-store`, Mule uses the default Java truststore, which is maintained by Java and updated automatically when Java is updated. This helps make sure that certificates from Certificate Authorities (CAs) remain current. Using a custom Java Trust Store isn’t the standard approach in MuleSoft and can lead to connectivity issues with the MuleSoft control plane when MuleSoft certificates are renewed. > [!IMPORTANT] Use the default Java truststore to avoid connectivity issues. If you use a custom > truststore, you’re responsible for managing and updating it. Truststore and keystore contents differ depending on whether they are used for clients or servers: - For servers: the truststore contains certificates of the trusted clients, the keystore contains the private and public key of the server. - For clients: the truststore contains certificates of the trusted servers, the keystore contains the private and public key of the client. Adding both a keystore and a truststore to the configuration implements two-way TLS authentication also known as mutual authentication. The keystore contains one or two passwords: - `password` accesses the entire keystore file. - `keyPassword` accesses the server’s private key inside the keystore. ## Client Configuration If the `tls:context` has an empty truststore defined, then the default values of the JVM are used, which usually include a truststore with certificates for all the major certifying authorities. Consider the following scenarios: - When the truststore is defined inline: - When the truststore is defined with a global element: If the client requires a certificate from the server that it is trying to connect to, then add the `tls:trust-store` element. Set `path` to the location of the truststore file that contains the certificates of the trusted servers. If the server validates certificates from the clients, then the `tls:key-store` element should be added with `path` set to the location of the keystore file that contains the private/public keys of the client. See [Configure TLS in Mule 4](#configure-tls-in-mule-4) for configuration instructions. ## Server Configuration The `tls:context` must contain a `tls:key-store` element to listen for a request using a secure connection such as HTTPS. Set `path` to the location of the keystore file that contains the private/public keys of the server. If the server needs to validate certificates from clients, add a `tls:trust-store` element and set `path` to the location of the trust store file that contains the certificates of the trusted clients. Mule supports many types of keystores, including: - `JCEKS` - `PKCS12` - `JKS` Specify your keystore type in the JRE. To fully configure TLS for a Mule app: 1. [Generate a keystore and a truststore](#generate-a-keystore), using the Java Keytool from Oracle. 2. [Configure TLS globally for client or server in Mule](#configure-tls-in-mule-4). 3. [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). ## Keystore Generation The standard JDK distribution does not include a keystore by default, use `keytool` to generate your keystores and certificates. The keystore you generate contains a private key and a public certificate. This certificate is self-signed so it is not to be trusted by clients unless you share the public certificate with them. ### Requirements Use Java 8 to generate your keystores. Using a different JDK version generates an incompatible keystore that causes an invalid keystore format runtime error when the Mule application tries to read the keystore. ### Generate a Keystore Follow these steps to generate a keystore and export a self-signed certificate. 1. Generate a keystore that exposes your server’s credentials. For example, run one of the following commands: keytool -genkey -keyalg RSA -alias -keystore .jks keytool -genkey -alias -keyalg RSA -keystore .jks -storepass Replace `` with a unique alias of your choice. Replace `` with a password of your choice. Replace `` with the name you want for your keystore. Optionally, you can set the encryption algorithm to ECDSA by specifying `-keyalg EC` instead of `-keyalg RSA`. > [!IMPORTANT] If you do not specify the encryption algorithm, the tool uses DSA by default > which is not compatible with TLS 1.2 and causes the SSL handshake to fail when the Mule app > receives an HTTPS request. 2. Respond to the tool’s prompts. The following output shows example responses: Enter keystore password: mule123 Re-enter new password: mule123 3. Respond to prompts to enter other values. Enter your desired values. The following output shows example responses: What is your first and last name? \[Unknown\]: max What is the name of your organizational unit? \[Unknown\]: MuleSoft What is the name of your organization? \[Unknown\]: MuleSoft Inc What is the name of your City or Locality? \[Unknown\]: San Francisco What is the name of your State or Province? \[Unknown\]: CA What is the two-letter country code for this unit? \[Unknown\]: 01 4. In response to the following prompt, enter: `yes`. Is CN=max, OU=MuleSoft, O=MuleSoft Inc, L=San Francisco, ST=CA, C=01 correct? \[no\]: yes 5. Respond to the following prompt. For example, use the same password by pressing RETURN. Enter key password for (RETURN if same as keystore password): 6. Enter the following command to export a self-signed certificate authenticating the public key. keytool -export -alias -keystore .jks -file .cer Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate. 7. Enter the password you set up for the keystore associated with the certificate: Enter keystore password: mule123 ### Request Signing by a Certification Authority If you want your certificate signed by a Certification Authority (CA), follow these steps: 1. Export your certificate in the standard CSR format. To do so you can run this command: keytool -certreq -keystore .jks -alias -file .csr Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate sign request file. 2. Send the CSR file generated in the previous step to the Certification Authority and follow their instructions to obtain their signature. After you receive the CA’s signature, you can import the signed certificate file through the following command: keytool -import -keystore .jks -alias -file Replace `` with the a new desired value, the alias you define must not be linked to any existing key or the process fails. Replace `` with the same value used in the previous steps. Replace `` with the name of the signed certificate you received from the Certification Authority. 1. Export your certificate in the standard PEM format. First verify the keystore type, then export the certificates: keytool -list -v -keystore .jks openssl -in .jks -out .key.pem -nocerts -nodes openssl -in .jks -out .crt.pem -nocerts -nodes Replace `` with the new desired value in keystore type format, for example PKCS12. Replace `` with the name you want for the keystore. Replace `` with the name you want for the PEM file. ## Truststore Generation The standard JRE distribution includes a default trust store with certificates for several major certificate authorities (CA’s) which is used by default in the 'tls:trust-store' element, but you can generate your own if you want greater security or if you use self-signed certificates. To create a trust store, you can use the Oracle Java keytool. The client trusts the server if a chain of trust can be established, either directly to the server (in case its certificate is in the truststore) or through a signing CA whose certificate is present in the truststore; otherwise, the connection fails. A trust store must be defined when using self-signed certificates. ## Configure TLS in Mule 4 To enable TLS for Mule apps, configure the `tls:context` element in the Mule XML configuration file in one of three ways: - [Edit the XML file directly.](#edit-xml-to-configure-tls) - [Use Anypoint Studio 7.](#use-anypoint-studio-to-configure-tls) - [Use Design Center.](#use-design-center-to-configure-tls) Whichever method you use, we recommend you review the information in [Edit XML to Configure TLS](#edit-xml-to-configure-tls) to understand how the attributes of `tls:context` function. ### Edit XML to Configure TLS The `tls:context` element defines TLS communication in a Mule app. Unless you have a special requirement, configure TLS globally and then apply it to each specific use, such as listening for or sending HTTPS requests. #### Globally Define a TLS Element The `tls:context` element defines a configuration for TLS, which can be used from both the client and server sides. The element can be referenced by other configuration objects of other modules or defined as a nested element of one of them. Include at least one of the nested elements: key-store and trust-store. ```xml ``` #### Optional Attributes of the `tls-context` Element Optionally, specify the protocol and cipher suite to enable them: - `enabledProtocols`: The protocols in the the global TLS configuration - `enabledCipherSuites`: The cipher suites in global TLS configuration These values are used if there is nothing specified in the global TLS configuration, or if the values are enabled in a global TLS configuration, as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). #### Attributes of the `trust-store` Element The `password` attribute is required if you specify a `path`. Otherwise, the attributes are optional. - `path`: The path to the file that contains the trust store - `type`: The type of the trust store. Default = JKS - `password`: The trust store password (required if you specify `path`) - `algorithm`: The algorithm the trust store uses. Default = `SunX509` - `insecure`: Boolean that determines whether or not to validate the truststore. If set to `true`, no validation occurs. The default value is `false`. > [!IMPORTANT] Setting `insecure` to `true` renders connections vulnerable to attack. Use it only > for prototyping or testing. Never use it in production environments. #### Attributes of the `key-store` Element The attributes other than `path` are optional. - `path`: The path to the file that contains the keystore (required) - `type`: The type of the keystore (default JKS) - `password`: The keystore password - `keyPassword`: The key manager password, which is the password for the private key inside the keystore - `algorithm`: The algorithm used in the keystore. The default value is `SunX509`. ### Use Design Center to Configure TLS You can configure TLS for your app in Design Center. For example, to configure TLS in HTTP Listener: 1. Log into Design Center. 2. Open the project. 3. Open HTTP Listener. 4. In the Configuration tab, click **Edit**. 5. In the TLS tab, fill in the TLS Configuration fields as described above. 6. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ### Use Anypoint Studio to Configure TLS You can configure TLS for your app in Anypoint Studio (Studio). For example, to configure TLS in HTTP Listener: 1. Open Studio Center. 2. Open the project. 3. Open HTTP Listener. 4. In the General tab, select an existing configuration or create a new one. 5. In the HTTP Listener config dialog, select the TLS tab. 6. In the TLS tab, choose the TLS Configuration type **Edit Inline**, and supply the values. 7. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields in the Advanced section as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ## Optional: Specify Protocols and Cipher Suites When a TLS communication takes place between two systems, a negotiation determines which protocol and cipher suite are used. Optionally, administrators can specify the protocols and cipher suites to use, and then app developers can specify which cipher suites and protocols to use in `tls:context`. > [!NOTE] Protocols and cipher suites must be enabled in Mule Runtime and individual apps to be > used. If the protocols and cipher suites aren’t enabled in both places, the default Java > environment protocol and cipher suites are used. To configure protocols and cipher suites in the Mule Runtime: 1. The Mule admin edits the `/conf` directory in `$MULE_HOME`. `$MULE_HOME` points to the directory where your Mule installation resides, for example `/opt/mule-4.0`. Select the appropriate file where you specify the cipher suites and protocols: - `tls-default.conf` allows fine-tuning when Mule is not configured to run in Federal Information Processing Standards (FIPS) security mode. - `tls-fips140-2.conf` allows fine-tuning when Mule is running in FIPS security mode. Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and TLS protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols for an app. 2. The list of protocols and cipher suites that the admin sets in these configuration files can then be constrained locally by what the app developer specifies in an individual `tls:context` element. The app developer specifies a subset of the configured or default values in the `tls:context` element for use by TLS. Configure the protocols and cipher suites in `enabledProtocols` and `enabledCipherSuites` in the `tls:context` element. In the `tls:context` element, you can only reference protocols or cipher suites that are included in the Mule global TLS configuration file or defaults. In `tls:context`, set `enabledProtocols` and `enabledCipherSuite` for a Mule app to the value `default`. After these values are set, TLS uses the following protocols and cipher suites: - Those configured in your global TLS configuration if it exists - The defaults provided by your Java environment if a global TLS configuration does not exist Cipher suite names can be long and reduce the readability of your XML code. To improve readability, keep these names in an external properties file in your Mule project. You can then reference the properties. For example: ```xml ``` ## Test after deployment Example time curl -i -k --cert ./.crt.pem --cert-type PEM --key ./.key.pem https://: Replace `` with the value name defined. Replace `` with the value name defined by Anypoint Platform. Replace `` with the value name defined in the Mule application. ## TLS Configuration Examples You can set up TLS in a Mule XML configuration file for a client or a server. ### Example: Configuring TLS for a Client This example secures an FTPS client by setting up a truststore: ```xml ``` ### Example: Configuring TLS for a Server This example secures an HTTP listener by setting up a keystore: ```xml ``` ### Example: Configuring TLS for Two-Way Authentication This example sets up two-way authentication (also called mutual authentication), for an HTTP listener: ```xml ``` ### Example: Disabling TLS Validations This example uses the `insecure` property to disable validations for prototyping and development. > [!IMPORTANT] Do not use the `insecure` property in production environments. ```xml ``` ### Example: Adding Additional Cipher Suites and Protocol Restrictions This example enables a protocol and cipher suite for an app, assuming a Mule admin has either specified nothing in the global TLS configuration or enabled the cipher suites and protocols being specified here. ```xml ``` ## See Also - [Oracle security](https://docs.oracle.com/javase/8/docs/technotes/tools/) - [Oracle Java keytool](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html) --- product: Mule Runtime version: 4.6 keywords: tls, https, ssl, secure messages, encryption, keystore, truststore --- # Configure TLS with Keystores and Truststores > For the full documentation index, see: https://docs.mulesoft.com/llms.txt TLS is a cryptographic protocol that provides communications security for your Mule app. TLS offers many different ways of exchanging keys for authentication, encrypting data, and guaranteeing message integrity. This topic describes TLS as supported by Mule and how to configure TLS in Mule apps. ## TLS Compatibility Matrix TLS compatibility differs by Mule deployment model and TLS version.
TLS VersionOn-PremisesCloudHubAnypoint Runtime Fabric

1.3

Supported when running Mule on a JDK that supports TLS 1.3 but not enabled by default

Supported for Mule apps hosted in this deployment model

Supported and enabled when running on a JDK that supports TLS 1.3

1.2

Supported and enabled by all deployment models

1.1

Supported and enabled by all deployment models

## The tls:context Element The `tls:context` element is used for all connectors that support TLS. For example, you can configure TLS in HTTP (server and client), FTPS (client), Email (client) or Sockets (client) connectors, among others. > [!NOTE] If a connector supports TLS, Studio shows either: > > - A **TLS/SSL** tab on that connector’s Global Elements Properties. > > - A **TLS Configuration** field on the **General** tab of that connector’s Global Element > Properties. ## The TLS-Enabled Server and Client A TLS-enabled server contains a private key and a public certificate: - The private key never leaves the server. - The public certificate is exposed through TLS. TLS-enabled clients verify that they trust the server by validating the public certificate against their own set of trusted certificates. To use TLS communications security in Mule 4, import certificates and private keys into a keystore file. Truststore files are also keystores that by convention include only public certificates of trusted servers. While there’s a default Java truststore, there is no default Java keystore in the standard JRE distribution. Add your own keystore to the TLS context. You likely already have corporate certificates for your client apps and don’t need to create them. Often, these certificates work with the JRE truststore, so no setup is required in the TLS context. A well-known Certificate Authority (CA) can generate certificates, or you can generate a certificate locally without external approval (self-signed certificate). A truststore contains certificates from trusted CAs that the client uses to verify a certificate presented by the server. ## Keystores and Truststores In a Mule configuration, the `tls:trust-store` and `tls:key-store` elements allow you to reference specific certificates and keys. If you don’t specify a `tls:trust-store`, Mule uses the default Java truststore, which is maintained by Java and updated automatically when Java is updated. This helps make sure that certificates from Certificate Authorities (CAs) remain current. Using a custom Java Trust Store isn’t the standard approach in MuleSoft and can lead to connectivity issues with the MuleSoft control plane when MuleSoft certificates are renewed. > [!IMPORTANT] Use the default Java truststore to avoid connectivity issues. If you use a custom > truststore, you’re responsible for managing and updating it. Truststore and keystore contents differ depending on whether they are used for clients or servers: - For servers: the truststore contains certificates of the trusted clients, the keystore contains the private and public key of the server. - For clients: the truststore contains certificates of the trusted servers, the keystore contains the private and public key of the client. Adding both a keystore and a truststore to the configuration implements two-way TLS authentication also known as mutual authentication. The keystore contains one or two passwords: - `password` accesses the entire keystore file. - `keyPassword` accesses the server’s private key inside the keystore. ## Client Configuration If the `tls:context` has an empty truststore defined, then the default values of the JVM are used, which usually include a truststore with certificates for all the major certifying authorities. Consider the following scenarios: - When the truststore is defined inline: - When the truststore is defined with a global element: If the client requires a certificate from the server that it is trying to connect to, then add the `tls:trust-store` element. Set `path` to the location within the artifact of the truststore file that contains the certificates of the trusted servers. If the server validates certificates from the clients, then the `tls:key-store` element should be added with `path` set to the location within the artifact of the keystore file that contains the private/public keys of the client. See [Configure TLS in Mule 4](#configure-tls-in-mule-4) for configuration instructions. ## Server Configuration The `tls:context` must contain a `tls:key-store` element to listen for a request using a secure connection such as HTTPS. Set `path` to the location within the artifact of the keystore file that contains the private/public keys of the server. If the server needs to validate certificates from clients, add a `tls:trust-store` element and set `path` to the location of the trust store file that contains the certificates of the trusted clients. Mule supports many types of keystores, including: - `JCEKS` - `PKCS12` - `JKS` Specify your keystore type in the JRE. To fully configure TLS for a Mule app: 1. [Generate a keystore and a truststore](#generate-a-keystore), using the Java Keytool from Oracle. 2. [Configure TLS globally for client or server in Mule](#configure-tls-in-mule-4). 3. [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). ## Keystore Generation The standard JDK distribution does not include a keystore by default, use `keytool` to generate your keystores and certificates. The keystore you generate contains a private key and a public certificate. This certificate is self-signed so it is not to be trusted by clients unless you share the public certificate with them. ### Requirements Use Java 8 or later versions to generate your keystores. Using a different JDK version generates an incompatible keystore that causes an invalid keystore format runtime error when the Mule application tries to read the keystore. ### Generate a Keystore Follow these steps to generate a keystore and export a self-signed certificate. 1. Generate a keystore that exposes your server’s credentials. For example, run one of the following commands: keytool -genkey -keyalg RSA -alias -keystore .jks keytool -genkey -alias -keyalg RSA -keystore .jks -storepass Replace `` with a unique alias of your choice. Replace `` with a password of your choice. Replace `` with the name you want for your keystore. Optionally, you can set the encryption algorithm to ECDSA by specifying `-keyalg EC` instead of `-keyalg RSA`. > [!IMPORTANT] If you do not specify the encryption algorithm, the tool uses DSA by default > which is not compatible with TLS 1.2 and causes the SSL handshake to fail when the Mule app > receives an HTTPS request. 2. Respond to the tool’s prompts. The following output shows example responses: Enter keystore password: mule123 Re-enter new password: mule123 3. Respond to prompts to enter other values. Enter your desired values. The following output shows example responses: What is your first and last name? \[Unknown\]: max What is the name of your organizational unit? \[Unknown\]: MuleSoft What is the name of your organization? \[Unknown\]: MuleSoft Inc What is the name of your City or Locality? \[Unknown\]: San Francisco What is the name of your State or Province? \[Unknown\]: CA What is the two-letter country code for this unit? \[Unknown\]: 01 4. In response to the following prompt, enter: `yes`. Is CN=max, OU=MuleSoft, O=MuleSoft Inc, L=San Francisco, ST=CA, C=01 correct? \[no\]: yes 5. Respond to the following prompt. For example, use the same password by pressing RETURN. Enter key password for (RETURN if same as keystore password): 6. Enter the following command to export a self-signed certificate authenticating the public key. keytool -export -alias -keystore .jks -file .cer Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate. 7. Enter the password you set up for the keystore associated with the certificate: Enter keystore password: mule123 ### Request Signing by a Certification Authority If you want your certificate signed by a Certification Authority (CA), follow these steps: 1. Export your certificate in the standard CSR format. To do so you can run this command: keytool -certreq -keystore .jks -alias -file .csr Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate sign request file. 2. Send the CSR file generated in the previous step to the Certification Authority and follow their instructions to obtain their signature. After you receive the CA’s signature, you can import the signed certificate file through the following command: keytool -import -keystore .jks -alias -file Replace `` with the new desired value. Make sure the alias you define isn’t linked to any existing key, or the process fails. Replace `` with the same value used in the previous steps. Replace `` with the name of the signed certificate you received from the Certification Authority. 1. Export your certificate in the standard PEM format. First verify the keystore type, then export the certificates: keytool -list -v -keystore .jks openssl -in .jks -out .key.pem -nocerts -nodes openssl -in .jks -out .crt.pem -nocerts -nodes Replace `` with the new desired value in keystore type format, for example PKCS12. Replace `` with the name you want for the keystore. Replace `` with the name you want for the PEM file. ## Truststore Generation The standard JRE distribution includes a default trust store with certificates for several major certificate authorities (CA’s) which is used by default in the 'tls:trust-store' element, but you can generate your own if you want greater security or if you use self-signed certificates. To create a trust store, you can use the Oracle Java keytool. The client trusts the server if a chain of trust can be established, either directly to the server (in case its certificate is in the truststore) or through a signing CA whose certificate is present in the truststore; otherwise, the connection fails. A trust store must be defined when using self-signed certificates. ## Configure TLS in Mule 4 To enable TLS for Mule apps, configure the `tls:context` element in the Mule XML configuration file in one of three ways: - [Edit the XML file directly.](#edit-xml-to-configure-tls) - [Use Anypoint Studio 7.](#use-anypoint-studio-to-configure-tls) - [Use Design Center.](#use-design-center-to-configure-tls) Whichever method you use, we recommend you review the information in [Edit XML to Configure TLS](#edit-xml-to-configure-tls) to understand how the attributes of `tls:context` function. ### Edit XML to Configure TLS The `tls:context` element defines TLS communication in a Mule app. Unless you have a special requirement, configure TLS globally and then apply it to each specific use, such as listening for or sending HTTPS requests. #### Globally Define a TLS Element The `tls:context` element defines a configuration for TLS, which can be used from both the client and server sides. The element can be referenced by other configuration objects of other modules or defined as a nested element of one of them. Include at least one of the nested elements: key-store and trust-store. ```xml ``` #### Optional Attributes of the `tls-context` Element Optionally, specify the protocol and cipher suite to enable them: - `enabledProtocols`: The protocols in the the global TLS configuration - `enabledCipherSuites`: The cipher suites in global TLS configuration These values are used if there is nothing specified in the global TLS configuration, or if the values are enabled in a global TLS configuration, as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). #### Attributes of the `trust-store` Element The `password` attribute is required if you specify a `path`. Otherwise, the attributes are optional.
AttributeDescription

path

The path to the file within the artifact that contains the trust store.

type

The type of the trust store. Default is JKS.

password

The trust store password. Required if you specify path.

algorithm

The algorithm the trust store uses. Default is SunX509.

insecure

Boolean that determines whether to validate the trust store. If set to true, no validation occurs. Default is false.

> [!IMPORTANT] Setting `insecure` to `true` renders connections vulnerable to attack. Use it only > for prototyping or testing. Never use it in production environments. #### Attributes of the `key-store` Element The attributes other than `path` are optional.
AttributeDescription

path

The path to the file within the artifact that contains the keystore. Required.

type

The type of the keystore. Default is JKS.

password

The keystore password.

keyPassword

The key manager password, which is the password for the private key inside the keystore.

algorithm

The algorithm used in the keystore. Default is SunX509.

### Use Design Center to Configure TLS You can configure TLS for your app in Design Center. For example, to configure TLS in HTTP Listener: 1. Log into Design Center. 2. Open the project. 3. Open HTTP Listener. 4. In the Configuration tab, click **Edit**. 5. In the TLS tab, fill in the TLS Configuration fields as described above. 6. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ### Use Anypoint Studio to Configure TLS You can configure TLS for your app in Anypoint Studio (Studio). For example, to configure TLS in HTTP Listener: 1. Open Studio Center. 2. Open the project. 3. Open HTTP Listener. 4. In the General tab, select an existing configuration or create a new one. 5. In the HTTP Listener config dialog, select the TLS tab. 6. In the TLS tab, choose the TLS Configuration type **Edit Inline**, and supply the values. 7. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields in the Advanced section as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ## Optional: Specify Protocols and Cipher Suites When a TLS communication takes place between two systems, a negotiation determines which protocol and cipher suite are used. Optionally, administrators can specify the protocols and cipher suites to use, and then app developers can specify which cipher suites and protocols to use in `tls:context`. > [!NOTE] Protocols and cipher suites must be enabled in Mule runtime and individual apps to be > used. If the protocols and cipher suites aren’t enabled in both places, the default Java > environment protocol and cipher suites are used. To configure protocols and cipher suites in the Mule runtime: 1. The Mule admin edits the `/conf` directory in `$MULE_HOME`. `$MULE_HOME` points to the directory where your Mule installation resides, for example `/opt/mule-4.0`. Select the appropriate file where you specify the cipher suites and protocols: - `tls-default.conf` allows fine-tuning when Mule isn’t configured to run in Federal Information Processing Standards (FIPS) security mode. - `tls-fips140-2.conf` allows fine-tuning when Mule is running in FIPS security mode. Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and TLS protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols for an app. 2. The list of protocols and cipher suites that the admin sets in these configuration files can then be constrained locally by what the app developer specifies in an individual `tls:context` element. The app developer specifies a subset of the configured or default values in the `tls:context` element for use by TLS. Configure the protocols and cipher suites in `enabledProtocols` and `enabledCipherSuites` in the `tls:context` element. In the `tls:context` element, you can only reference protocols or cipher suites that are included in the Mule global TLS configuration file or defaults. In `tls:context`, set `enabledProtocols` and `enabledCipherSuite` for a Mule app to the value `default`. After these values are set, TLS uses the following protocols and cipher suites: - Those configured in your global TLS configuration if it exists - The defaults provided by your Java environment if a global TLS configuration doesn’t exist Cipher suite names can be long and reduce the readability of your XML code. To improve readability, keep these names in an external properties file in your Mule project. You can then reference the properties. For example: ```xml ``` ## Test after deployment Example time curl -i -k --cert ./.crt.pem --cert-type PEM --key ./.key.pem https://: Replace `` with the value name defined. Replace `` with the value name defined by Anypoint Platform. Replace `` with the value name defined in the Mule application. ## TLS Configuration Examples You can set up TLS in a Mule XML configuration file for a client or a server. ### Example: Configuring TLS for a Client This example secures an FTPS client by setting up a truststore: ```xml ``` ### Example: Configuring TLS for a Server This example secures an HTTP listener by setting up a keystore: ```xml ``` ### Example: Configuring TLS for Two-Way Authentication This example sets up two-way authentication (also called mutual authentication), for an HTTP listener: ```xml ``` ### Example: Disabling TLS Validations This example uses the `insecure` property to disable validations for prototyping and development. > [!IMPORTANT] Don’t use the `insecure` property in production environments. ```xml ``` ### Example: Adding Additional Cipher Suites and Protocol Restrictions This example enables a protocol and cipher suite for an app, assuming a Mule admin has either specified nothing in the global TLS configuration or enabled the cipher suites and protocols being specified here. ```xml ``` ## See Also - [Oracle security](https://docs.oracle.com/javase/8/docs/technotes/tools/) - [Oracle Java keytool](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html) --- product: Mule Runtime version: 4.9 keywords: tls, https, ssl, secure messages, encryption, keystore, truststore --- # Configure TLS with Keystores and Truststores > For the full documentation index, see: https://docs.mulesoft.com/llms.txt TLS is a cryptographic protocol that provides communications security for your Mule app. TLS offers many different ways of exchanging keys for authentication, encrypting data, and guaranteeing message integrity. This topic describes TLS as supported by Mule and how to configure TLS in Mule apps. ## TLS Compatibility Matrix TLS compatibility differs by Mule deployment model and TLS version.
TLS VersionOn-PremisesCloudHubAnypoint Runtime Fabric

1.3

Supported when running Mule on a JDK that supports TLS 1.3 but not enabled by default

Supported for Mule apps hosted in this deployment model

Supported and enabled when running on a JDK that supports TLS 1.3

1.2

Supported and enabled by all deployment models

1.1

Supported and enabled by all deployment models

## The tls:context Element The `tls:context` element is used for all connectors that support TLS. For example, you can configure TLS in HTTP (server and client), FTPS (client), Email (client) or Sockets (client) connectors, among others. > [!NOTE] If a connector supports TLS, Studio shows either: > > - A **TLS/SSL** tab on that connector’s Global Elements Properties. > > - A **TLS Configuration** field on the **General** tab of that connector’s Global Element > Properties. ## The TLS-Enabled Server and Client A TLS-enabled server contains a private key and a public certificate: - The private key never leaves the server. - The public certificate is exposed through TLS. TLS-enabled clients verify that they trust the server by validating the public certificate against their own set of trusted certificates. To use TLS communications security in Mule 4, import certificates and private keys into a keystore file. Truststore files are also keystores that by convention include only public certificates of trusted servers. While there’s a default Java truststore, there is no default Java keystore in the standard JRE distribution. Add your own keystore to the TLS context. You likely already have corporate certificates for your client apps and don’t need to create them. Often, these certificates work with the JRE truststore, so no setup is required in the TLS context. A well-known Certificate Authority (CA) can generate certificates, or you can generate a certificate locally without external approval (self-signed certificate). A truststore contains certificates from trusted CAs that the client uses to verify a certificate presented by the server. ## Keystores and Truststores In a Mule configuration, the `tls:trust-store` and `tls:key-store` elements allow you to reference specific certificates and keys. If you don’t specify a `tls:trust-store`, Mule uses the default Java truststore, which is maintained by Java and updated automatically when Java is updated. This helps make sure that certificates from Certificate Authorities (CAs) remain current. Using a custom Java Trust Store isn’t the standard approach in MuleSoft and can lead to connectivity issues with the MuleSoft control plane when MuleSoft certificates are renewed. > [!IMPORTANT] Use the default Java truststore to avoid connectivity issues. If you use a custom > truststore, you’re responsible for managing and updating it. Truststore and keystore contents differ depending on whether they are used for clients or servers: - For servers: the truststore contains certificates of the trusted clients, the keystore contains the private and public key of the server. - For clients: the truststore contains certificates of the trusted servers, the keystore contains the private and public key of the client. Adding both a keystore and a truststore to the configuration implements two-way TLS authentication also known as mutual authentication. The keystore contains one or two passwords: - `password` accesses the entire keystore file. - `keyPassword` accesses the server’s private key inside the keystore. ## Client Configuration If the `tls:context` has an empty truststore defined, then the default values of the JVM are used, which usually include a truststore with certificates for all the major certifying authorities. Consider the following scenarios: - When the truststore is defined inline: - When the truststore is defined with a global element: If the client requires a certificate from the server that it is trying to connect to, then add the `tls:trust-store` element. Set `path` to the location within the artifact of the truststore file that contains the certificates of the trusted servers. If the server validates certificates from the clients, then the `tls:key-store` element should be added with `path` set to the location within the artifact of the keystore file that contains the private/public keys of the client. See [Configure TLS in Mule 4](#configure-tls-in-mule-4) for configuration instructions. ## Server Configuration The `tls:context` must contain a `tls:key-store` element to listen for a request using a secure connection such as HTTPS. Set `path` to the location within the artifact of the keystore file that contains the private/public keys of the server. If the server needs to validate certificates from clients, add a `tls:trust-store` element and set `path` to the location within the artifact of the trust store file that contains the certificates of the trusted clients. Mule supports many types of keystores, including: - `JCEKS` - `PKCS12` - `JKS` Specify your keystore type in the JRE. To fully configure TLS for a Mule app: 1. [Generate a keystore and a truststore](#generate-a-keystore), using the Java Keytool from Oracle. 2. [Configure TLS globally for client or server in Mule](#configure-tls-in-mule-4). 3. [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). ## Keystore Generation The standard JDK distribution doesn’t include a keystore by default, use `keytool` to generate your keystores and certificates. The keystore you generate contains a private key and a public certificate. This certificate is self-signed so it isn’t to be trusted by clients unless you share the public certificate with them. ### Requirements Use Java 17 to generate your keystores. Using a different JDK version generates an incompatible keystore that causes an invalid keystore format runtime error when the Mule application tries to read the keystore. ### Generate a Keystore Follow these steps to generate a keystore and export a self-signed certificate. 1. Generate a keystore that exposes your server’s credentials. For example, run one of the following commands: keytool -genkey -keyalg RSA -alias -keystore .jks keytool -genkey -alias -keyalg RSA -keystore .jks -storepass Replace `` with a unique alias of your choice. Replace `` with a password of your choice. Replace `` with the name you want for your keystore. Optionally, you can set the encryption algorithm to ECDSA by specifying `-keyalg EC` instead of `-keyalg RSA`. > [!IMPORTANT] If you don’t specify the encryption algorithm, the tool uses DSA by default which > isn’t compatible with TLS 1.2 and causes the SSL handshake to fail when the Mule app receives > an HTTPS request. 2. Respond to the tool’s prompts. The following output shows example responses: Enter keystore password: mule123 Re-enter new password: mule123 3. Respond to prompts to enter other values. Enter your desired values. The following output shows example responses: What is your first and last name? \[Unknown\]: max What is the name of your organizational unit? \[Unknown\]: MuleSoft What is the name of your organization? \[Unknown\]: MuleSoft Inc What is the name of your City or Locality? \[Unknown\]: San Francisco What is the name of your State or Province? \[Unknown\]: CA What is the two-letter country code for this unit? \[Unknown\]: 01 4. In response to the following prompt, enter: `yes`. Is CN=max, OU=MuleSoft, O=MuleSoft Inc, L=San Francisco, ST=CA, C=01 correct? \[no\]: yes 5. Respond to the following prompt. For example, use the same password by pressing RETURN. Enter key password for (RETURN if same as keystore password): 6. Enter the following command to export a self-signed certificate authenticating the public key. keytool -export -alias -keystore .jks -file .cer Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate. 7. Enter the password you set up for the keystore associated with the certificate: Enter keystore password: mule123 ### Request Signing by a Certification Authority If you want your certificate signed by a Certification Authority (CA), follow these steps: 1. Export your certificate in the standard CSR format. To do so you can run this command: keytool -certreq -keystore .jks -alias -file .csr Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate sign request file. 2. Send the CSR file generated in the previous step to the Certification Authority and follow their instructions to obtain their signature. After you receive the CA’s signature, you can import the signed certificate file through the following command: keytool -import -keystore .jks -alias -file Replace `` with the new desired value. Make sure the alias you define isn’t linked to any existing key, or the process fails. Replace `` with the same value used in the previous steps. Replace `` with the name of the signed certificate you received from the Certification Authority. 1. Export your certificate in the standard PEM format. First verify the keystore type, then export the certificates: keytool -list -v -keystore .jks openssl -in .jks -out .key.pem -nocerts -nodes openssl -in .jks -out .crt.pem -nocerts -nodes Replace `` with the new desired value in keystore type format, for example PKCS12. Replace `` with the name you want for the keystore. Replace `` with the name you want for the PEM file. ## Truststore Generation The standard JRE distribution includes a default trust store with certificates for several major certificate authorities (CA’s) which is used by default in the 'tls:trust-store' element, but you can generate your own if you want greater security or if you use self-signed certificates. To create a trust store, you can use the Oracle Java keytool. The client trusts the server if a chain of trust can be established, either directly to the server (in case its certificate is in the truststore) or through a signing CA whose certificate is present in the truststore; otherwise, the connection fails. A trust store must be defined when using self-signed certificates. ## Configure TLS in Mule 4 To enable TLS for Mule apps, configure the `tls:context` element in the Mule XML configuration file in one of three ways: - [Edit the XML file directly.](#edit-xml-to-configure-tls) - [Use Anypoint Studio 7.](#use-anypoint-studio-to-configure-tls) - [Use Design Center.](#use-design-center-to-configure-tls) Whichever method you use, we recommend you review the information in [Edit XML to Configure TLS](#edit-xml-to-configure-tls) to understand how the attributes of `tls:context` function. ### Edit XML to Configure TLS The `tls:context` element defines TLS communication in a Mule app. Unless you have a special requirement, configure TLS globally and then apply it to each specific use, such as listening for or sending HTTPS requests. #### Globally Define a TLS Element The `tls:context` element defines a configuration for TLS, which can be used from both the client and server sides. The element can be referenced by other configuration objects of other modules or defined as a nested element of one of them. Include at least one of the nested elements: key-store and trust-store. ```xml ``` #### Optional Attributes of the `tls-context` Element Optionally, specify the protocol and cipher suite to enable them: - `enabledProtocols`: The protocols in the global TLS configuration - `enabledCipherSuites`: The cipher suites in global TLS configuration These values are used if there is nothing specified in the global TLS configuration, or if the values are enabled in a global TLS configuration, as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). #### Attributes of the `trust-store` Element The `password` attribute is required if you specify a `path`. Otherwise, the attributes are optional.
AttributeDescription

path

The path to the file within the artifact that contains the trust store.

type

The type of the trust store. Default is JKS.

password

The trust store password. Required if you specify path.

algorithm

The algorithm the trust store uses. Default is SunX509.

insecure

Boolean that determines whether to validate the trust store. If set to true, no validation occurs. Default is false.

> [!IMPORTANT] Setting `insecure` to `true` renders connections vulnerable to attack. Use it only > for prototyping or testing. Never use it in production environments. #### Attributes of the `key-store` Element The attributes other than `path` are optional.
AttributeDescription

path

The path to the file within the artifact that contains the keystore. Required.

type

The type of the keystore. Default is JKS.

password

The keystore password.

keyPassword

The key manager password, which is the password for the private key inside the keystore.

algorithm

The algorithm used in the keystore. Default is SunX509.

### Use Design Center to Configure TLS You can configure TLS for your app in Design Center. For example, to configure TLS in HTTP Listener: 1. Log into Design Center. 2. Open the project. 3. Open HTTP Listener. 4. In the Configuration tab, click **Edit**. 5. In the TLS tab, fill in the TLS Configuration fields as described above. 6. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ### Use Anypoint Studio to Configure TLS You can configure TLS for your app in Anypoint Studio (Studio). For example, to configure TLS in HTTP Listener: 1. Open Studio Center. 2. Open the project. 3. Open HTTP Listener. 4. In the General tab, select an existing configuration or create a new one. 5. In the HTTP Listener config dialog, select the TLS tab. 6. In the TLS tab, choose the TLS Configuration type **Edit Inline**, and supply the values. 7. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields in the Advanced section as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ## Optional: Specify Protocols and Cipher Suites When a TLS communication takes place between two systems, a negotiation determines which protocol and cipher suite are used. Optionally, administrators can specify the protocols and cipher suites to use, and then app developers can specify which cipher suites and protocols to use in `tls:context`. > [!NOTE] Protocols and cipher suites must be enabled in Mule runtime and individual apps to be > used. If the protocols and cipher suites aren’t enabled in both places, the default Java > environment protocol and cipher suites are used. To configure protocols and cipher suites in the Mule runtime: 1. The Mule admin edits the `/conf` directory in `$MULE_HOME`. `$MULE_HOME` points to the directory where your Mule installation resides, for example `/opt/mule-4.0`. Select the appropriate file where you specify the cipher suites and protocols: - `tls-default.conf` allows fine-tuning when Mule isn’t configured to run in Federal Information Processing Standards (FIPS) security mode. - `tls-fips140-2.conf` allows fine-tuning when Mule is running in FIPS security mode. Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and TLS protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols for an app. 2. The list of protocols and cipher suites that the admin sets in these configuration files can then be constrained locally by what the app developer specifies in an individual `tls:context` element. The app developer specifies a subset of the configured or default values in the `tls:context` element for use by TLS. Configure the protocols and cipher suites in `enabledProtocols` and `enabledCipherSuites` in the `tls:context` element. In the `tls:context` element, you can only reference protocols or cipher suites that are included in the Mule global TLS configuration file or defaults. In `tls:context`, set `enabledProtocols` and `enabledCipherSuite` for a Mule app to the value `default`. After these values are set, TLS uses the following protocols and cipher suites: - Those configured in your global TLS configuration if it exists - The defaults provided by your Java environment if a global TLS configuration doesn’t exist Cipher suite names can be long and reduce the readability of your XML code. To improve readability, keep these names in an external properties file in your Mule project. You can then reference the properties. For example: ```xml ``` ## Test after deployment Example time curl -i -k --cert ./.crt.pem --cert-type PEM --key ./.key.pem https://: Replace `` with the value name defined. Replace `` with the value name defined by Anypoint Platform. Replace `` with the value name defined in the Mule application. ## TLS Configuration Examples You can set up TLS in a Mule XML configuration file for a client or a server. ### Example: Configuring TLS for a Client This example secures an FTPS client by setting up a truststore: ```xml ``` ### Example: Configuring TLS for a Server This example secures an HTTP listener by setting up a keystore: ```xml ``` ### Example: Configuring TLS for Two-Way Authentication This example sets up two-way authentication (also called mutual authentication), for an HTTP listener: ```xml ``` ### Example: Disabling TLS Validations This example uses the `insecure` property to disable validations for prototyping and development. > [!IMPORTANT] Don’t use the `insecure` property in production environments. ```xml ``` ### Example: Adding Additional Cipher Suites and Protocol Restrictions This example enables a protocol and cipher suite for an app, assuming a Mule admin has either specified nothing in the global TLS configuration or enabled the cipher suites and protocols being specified here. Use IANA (Internet Assigned Numbers Authority) naming convention for the cipher suites. Check the [OpenSSL - IANA mapping](https://testssl.sh/openssl-iana.mapping.html) for reference. ```xml ``` ## See Also - [Oracle security](https://docs.oracle.com/javase/8/docs/technotes/tools/#security) - [Oracle Java keytool](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: tls, https, ssl, secure messages, encryption, keystore, truststore --- # Configure TLS with Keystores and Truststores > For the full documentation index, see: https://docs.mulesoft.com/llms.txt TLS is a cryptographic protocol that provides communications security for your Mule app. TLS offers many different ways of exchanging keys for authentication, encrypting data, and guaranteeing message integrity. This topic describes TLS as supported by Mule and how to configure TLS in Mule apps. ## TLS Compatibility Matrix TLS compatibility differs by Mule deployment model and TLS version.
TLS VersionOn-PremisesCloudHubAnypoint Runtime Fabric

1.3

Supported when running Mule on a JDK that supports TLS 1.3 but not enabled by default

Supported for Mule apps hosted in this deployment model

Supported and enabled when running on a JDK that supports TLS 1.3

1.2

Supported and enabled by all deployment models

## The tls:context Element The `tls:context` element is used for all connectors that support TLS. For example, you can configure TLS in HTTP (server and client), FTPS (client), Email (client) or Sockets (client) connectors, among others. > [!NOTE] If a connector supports TLS, Studio shows either: > > - A **TLS/SSL** tab on that connector’s Global Elements Properties. > > - A **TLS Configuration** field on the **General** tab of that connector’s Global Element > Properties. ## The TLS-Enabled Server and Client A TLS-enabled server contains a private key and a public certificate: - The private key never leaves the server. - The public certificate is exposed through TLS. TLS-enabled clients verify that they trust the server by validating the public certificate against their own set of trusted certificates. To use TLS communications security in Mule 4, import certificates and private keys into a keystore file. Truststore files are also keystores that by convention include only public certificates of trusted servers. While there’s a default Java truststore, there is no default Java keystore in the standard JRE distribution. Add your own keystore to the TLS context. You likely already have corporate certificates for your client apps and don’t need to create them. Often, these certificates work with the JRE truststore, so no setup is required in the TLS context. A well-known Certificate Authority (CA) can generate certificates, or you can generate a certificate locally without external approval (self-signed certificate). A truststore contains certificates from trusted CAs that the client uses to verify a certificate presented by the server. ## Keystores and Truststores In a Mule configuration, the `tls:trust-store` and `tls:key-store` elements allow you to reference specific certificates and keys. If you don’t specify a `tls:trust-store`, Mule uses the default Java truststore, which is maintained by Java and updated automatically when Java is updated. This helps make sure that certificates from Certificate Authorities (CAs) remain current. Using a custom Java Trust Store isn’t the standard approach in MuleSoft and can lead to connectivity issues with the MuleSoft control plane when MuleSoft certificates are renewed. > [!IMPORTANT] Use the default Java truststore to avoid connectivity issues. If you use a custom > truststore, you’re responsible for managing and updating it. Truststore and keystore contents differ depending on whether they are used for clients or servers: - For servers: the truststore contains certificates of the trusted clients, the keystore contains the private and public key of the server. - For clients: the truststore contains certificates of the trusted servers, the keystore contains the private and public key of the client. Adding both a keystore and a truststore to the configuration implements two-way TLS authentication also known as mutual authentication. The keystore contains one or two passwords: - `password` accesses the entire keystore file. - `keyPassword` accesses the server’s private key inside the keystore. ## Client Configuration If the `tls:context` has an empty truststore defined, then the default values of the JVM are used, which usually include a truststore with certificates for all the major certifying authorities. Consider the following scenarios: - When the truststore is defined inline: - When the truststore is defined with a global element: If the client requires a certificate from the server that it is trying to connect to, then add the `tls:trust-store` element. Set `path` to the location within the artifact of the truststore file that contains the certificates of the trusted servers. If the server validates certificates from the clients, then the `tls:key-store` element should be added with `path` set to the location within the artifact of the keystore file that contains the private/public keys of the client. See [Configure TLS in Mule 4](#configure-tls-in-mule-4) for configuration instructions. ## Server Configuration The `tls:context` must contain a `tls:key-store` element to listen for a request using a secure connection such as HTTPS. Set `path` to the location within the artifact of the keystore file that contains the private/public keys of the server. If the server needs to validate certificates from clients, add a `tls:trust-store` element and set `path` to the location within the artifact of the trust store file that contains the certificates of the trusted clients. Mule supports many types of keystores, including: - `JCEKS` - `PKCS12` - `JKS` Specify your keystore type in the JRE. To fully configure TLS for a Mule app: 1. [Generate a keystore and a truststore](#generate-a-keystore), using the Java Keytool from Oracle. 2. [Configure TLS globally for client or server in Mule](#configure-tls-in-mule-4). 3. [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). ## Keystore Generation The standard JDK distribution doesn’t include a keystore by default, use `keytool` to generate your keystores and certificates. The keystore you generate contains a private key and a public certificate. This certificate is self-signed so it isn’t to be trusted by clients unless you share the public certificate with them. ### Requirements Use Java 17 to generate your keystores. Using a different JDK version generates an incompatible keystore that causes an invalid keystore format runtime error when the Mule application tries to read the keystore. ### Generate a Keystore Follow these steps to generate a keystore and export a self-signed certificate. 1. Generate a keystore that exposes your server’s credentials. For example, run one of the following commands: keytool -genkey -keyalg RSA -alias -keystore .jks keytool -genkey -alias -keyalg RSA -keystore .jks -storepass Replace `` with a unique alias of your choice. Replace `` with a password of your choice. Replace `` with the name you want for your keystore. Optionally, you can set the encryption algorithm to ECDSA by specifying `-keyalg EC` instead of `-keyalg RSA`. > [!IMPORTANT] If you don’t specify the encryption algorithm, the tool uses DSA by default which > isn’t compatible with TLS 1.2 and causes the SSL handshake to fail when the Mule app receives > an HTTPS request. 2. Respond to the tool’s prompts. The following output shows example responses: Enter keystore password: mule123 Re-enter new password: mule123 3. Respond to prompts to enter other values. Enter your desired values. The following output shows example responses: What is your first and last name? \[Unknown\]: max What is the name of your organizational unit? \[Unknown\]: MuleSoft What is the name of your organization? \[Unknown\]: MuleSoft Inc What is the name of your City or Locality? \[Unknown\]: San Francisco What is the name of your State or Province? \[Unknown\]: CA What is the two-letter country code for this unit? \[Unknown\]: 01 4. In response to the following prompt, enter: `yes`. Is CN=max, OU=MuleSoft, O=MuleSoft Inc, L=San Francisco, ST=CA, C=01 correct? \[no\]: yes 5. Respond to the following prompt. For example, use the same password by pressing RETURN. Enter key password for (RETURN if same as keystore password): 6. Enter the following command to export a self-signed certificate authenticating the public key. keytool -export -alias -keystore .jks -file .cer Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate. 7. Enter the password you set up for the keystore associated with the certificate: Enter keystore password: mule123 ### Request Signing by a Certification Authority If you want your certificate signed by a Certification Authority (CA), follow these steps: 1. Export your certificate in the standard CSR format. To do so you can run this command: keytool -certreq -keystore .jks -alias -file .csr Replace `` with the same value used in the previous steps. Replace `` with the same value used in the previous steps. Replace `` with the name you want for your certificate sign request file. 2. Send the CSR file generated in the previous step to the Certification Authority and follow their instructions to obtain their signature. After you receive the CA’s signature, you can import the signed certificate file through the following command: keytool -import -keystore .jks -alias -file Replace `` with the new desired value. Make sure the alias you define isn’t linked to any existing key, or the process fails. Replace `` with the same value used in the previous steps. Replace `` with the name of the signed certificate you received from the Certification Authority. 1. Export your certificate in the standard PEM format. First verify the keystore type, then export the certificates: keytool -list -v -keystore .jks openssl -in .jks -out .key.pem -nocerts -nodes openssl -in .jks -out .crt.pem -nocerts -nodes Replace `` with the new desired value in keystore type format, for example PKCS12. Replace `` with the name you want for the keystore. Replace `` with the name you want for the PEM file. ## Truststore Generation The standard JRE distribution includes a default trust store with certificates for several major certificate authorities (CA’s) which is used by default in the 'tls:trust-store' element, but you can generate your own if you want greater security or if you use self-signed certificates. To create a trust store, you can use the Oracle Java keytool. The client trusts the server if a chain of trust can be established, either directly to the server (in case its certificate is in the truststore) or through a signing CA whose certificate is present in the truststore; otherwise, the connection fails. A trust store must be defined when using self-signed certificates. ## Configure TLS in Mule 4 To enable TLS for Mule apps, configure the `tls:context` element in the Mule XML configuration file in one of three ways: - [Edit the XML file directly.](#edit-xml-to-configure-tls) - [Use Anypoint Studio 7.](#use-anypoint-studio-to-configure-tls) - [Use Design Center.](#use-design-center-to-configure-tls) Whichever method you use, we recommend you review the information in [Edit XML to Configure TLS](#edit-xml-to-configure-tls) to understand how the attributes of `tls:context` function. ### Edit XML to Configure TLS The `tls:context` element defines TLS communication in a Mule app. Unless you have a special requirement, configure TLS globally and then apply it to each specific use, such as listening for or sending HTTPS requests. #### Globally Define a TLS Element The `tls:context` element defines a configuration for TLS, which can be used from both the client and server sides. The element can be referenced by other configuration objects of other modules or defined as a nested element of one of them. Include at least one of the nested elements: key-store and trust-store. ```xml ``` #### Optional Attributes of the `tls-context` Element Optionally, specify the protocol and cipher suite to enable them: - `enabledProtocols`: The protocols in the global TLS configuration - `enabledCipherSuites`: The cipher suites in global TLS configuration These values are used if there is nothing specified in the global TLS configuration, or if the values are enabled in a global TLS configuration, as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). #### Attributes of the `trust-store` Element The `password` attribute is required if you specify a `path`. Otherwise, the attributes are optional.
AttributeDescription

path

The path to the file within the artifact that contains the trust store.

type

The type of the trust store. Default is JKS.

password

The trust store password. Required if you specify path.

algorithm

The algorithm the trust store uses. Default is SunX509.

insecure

Boolean that determines whether to validate the trust store. If set to true, no validation occurs. Default is false.

> [!IMPORTANT] Setting `insecure` to `true` renders connections vulnerable to attack. Use it only > for prototyping or testing. Never use it in production environments. #### Attributes of the `key-store` Element The attributes other than `path` are optional.
AttributeDescription

path

The path to the file within the artifact that contains the keystore. Required.

type

The type of the keystore. Default is JKS.

password

The keystore password.

keyPassword

The key manager password, which is the password for the private key inside the keystore.

algorithm

The algorithm used in the keystore. Default is SunX509.

> [!NOTE] By default, the `path` attribute loads trust and keystore files as classloader resources. > For on-premises deployments (hybrid or standalone), set the system property > `mule.tlsStores.filesystemLookup.enable` to `true` to enable file system access. ### Use Design Center to Configure TLS You can configure TLS for your app in Design Center. For example, to configure TLS in HTTP Listener: 1. Log into Design Center. 2. Open the project. 3. Open HTTP Listener. 4. In the Configuration tab, click **Edit**. 5. In the TLS tab, fill in the TLS Configuration fields as described above. 6. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ### Use Anypoint Studio to Configure TLS You can configure TLS for your app in Anypoint Studio (Studio). For example, to configure TLS in HTTP Listener: 1. Open Studio Center. 2. Open the project. 3. Open HTTP Listener. 4. In the General tab, select an existing configuration or create a new one. 5. In the HTTP Listener config dialog, select the TLS tab. 6. In the TLS tab, choose the TLS Configuration type **Edit Inline**, and supply the values. 7. Optionally, fill in the **Enabled Protocols** and **Enabled Cipher Suites** fields in the Advanced section as described in [Optional: Specify Protocols and Cipher Suites](#optional-specify-protocols-and-cipher-suites). Save your configuration and test. ## Optional: Specify Protocols and Cipher Suites When a TLS communication takes place between two systems, a negotiation determines which protocol and cipher suite are used. Optionally, administrators can specify the protocols and cipher suites to use, and then app developers can specify which cipher suites and protocols to use in `tls:context`. > [!NOTE] Protocols and cipher suites must be enabled in Mule runtime and individual apps to be > used. If the protocols and cipher suites aren’t enabled in both places, the default Java > environment protocol and cipher suites are used. To configure protocols and cipher suites in the Mule runtime: 1. The Mule admin edits the `/conf` directory in `$MULE_HOME`. `$MULE_HOME` points to the directory where your Mule installation resides, for example `/opt/mule-4.0`. Select the appropriate file where you specify the cipher suites and protocols: - `tls-default.conf` allows fine-tuning when Mule isn’t configured to run in Federal Information Processing Standards (FIPS) security mode. - `tls-fips140-2.conf` allows fine-tuning when Mule is running in FIPS security mode. Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and TLS protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols for an app. 2. The list of protocols and cipher suites that the admin sets in these configuration files can then be constrained locally by what the app developer specifies in an individual `tls:context` element. The app developer specifies a subset of the configured or default values in the `tls:context` element for use by TLS. Configure the protocols and cipher suites in `enabledProtocols` and `enabledCipherSuites` in the `tls:context` element. In the `tls:context` element, you can only reference protocols or cipher suites that are included in the Mule global TLS configuration file or defaults. In `tls:context`, set `enabledProtocols` and `enabledCipherSuite` for a Mule app to the value `default`. After these values are set, TLS uses the following protocols and cipher suites: - Those configured in your global TLS configuration if it exists - The defaults provided by your Java environment if a global TLS configuration doesn’t exist Cipher suite names can be long and reduce the readability of your XML code. To improve readability, keep these names in an external properties file in your Mule project. You can then reference the properties. For example: ```xml ``` ## Test after deployment Example time curl -i -k --cert ./.crt.pem --cert-type PEM --key ./.key.pem https://: Replace `` with the value name defined. Replace `` with the value name defined by Anypoint Platform. Replace `` with the value name defined in the Mule application. ## TLS Configuration Examples You can set up TLS in a Mule XML configuration file for a client or a server. ### Example: Configuring TLS for a Client This example secures an FTPS client by setting up a truststore: ```xml ``` ### Example: Configuring TLS for a Server This example secures an HTTP listener by setting up a keystore: ```xml ``` ### Example: Configuring TLS for Two-Way Authentication This example sets up two-way authentication (also called mutual authentication), for an HTTP listener: ```xml ``` ### Example: Disabling TLS Validations This example uses the `insecure` property to disable validations for prototyping and development. > [!IMPORTANT] Don’t use the `insecure` property in production environments. ```xml ``` ### Example: Adding Additional Cipher Suites and Protocol Restrictions This example enables a protocol and cipher suite for an app, assuming a Mule admin has either specified nothing in the global TLS configuration or enabled the cipher suites and protocols being specified here. Use IANA (Internet Assigned Numbers Authority) naming convention for the cipher suites. Check the [OpenSSL - IANA mapping](https://testssl.sh/openssl-iana.mapping.html) for reference. ```xml ``` ## See Also - [Oracle security](https://docs.oracle.com/javase/8/docs/technotes/tools/) - [Oracle Java keytool](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/keytool.html) --- product: Mule Runtime version: 4.11 --- # Configuring Batch Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can set up and configure Mule batch processing components to perform common batch processing use cases and to enhance the performance of batch jobs for cases in which the defaults require adjustment. ## Filtering Records to Process within a Batch Step Component You can apply one or more record filters as attributes to any number of Batch Step components. For example, assume that the first Batch Step component within a given Batch Job component checks for a Salesforce contact in each record and the second updates the contact information in those records. To ensure that the second Batch Step processes only records that succeeded in the first step, you can configure a filter on the second Batch Step. The filter streamlines processing so that Mule focuses on only the relevant data for a given step. To filter records, the Batch Step component supports one `acceptExpression` and one `acceptPolicy`. Both are optional, and no other Mule components accept these filters. If you use both filters on the same component, Mule evaluates the filters in the following order: 1. Accept Policy: [acceptPolicy](#accept_policy) 2. Accept Expression: [acceptExpression](#accept_expression) A Batch Step component that uses an `acceptExpression` attribute applies a DataWeave expression to each record that reaches the component and accepts a record for processing within the component only if the expression evaluates to `true` for that record. If the record evaluates to `false`, the Batch Step component skips the record, and that record becomes available to the next Batch Step component within the Batch Job component if one exists. The example below filters out all records in which the `age` value is less than `21`: ```xml ... ``` A Batch Step component uses an `acceptPolicy` attribute to apply a policy to records processed in a previous Batch Step component. The Batch Step accepts a record for processing within the component only if the policy evaluates to `true` for that record. The default policy is `NO_FAILURES`. Other policies are `ONLY_FAILURES` and `ALL`. For descriptions of these policies, see [Batch Step Component ()](https://docs.mulesoft.com/mule-runtime/4.11/batch-reference#ref_batch_step_component). In the following example, the second Batch Step component (`batchStep2`) accepts only those records that failed to process successfully during the preceding step (`batchStep1`). For example, assume processors within `batchStep1` check each record for a Salesforce contact. If the check fails to find a contact, `batchStep2` accepts only those records without contacts, skipping records with contacts. Message processors within `batchStep2` can add a contact to those records. ```xml ... ... ``` For demonstration purposes, the following example uses the Raise Error component (``) to produce failures in the first Batch Step (`batchStep1`). The second Batch Step (`batchStep2`) accepts failed records only (`ONLY_FAILURES`) and logs the payload of those records. The third uses the default `acceptPolicy` to accept `NO_FAILURES`. ```xml ``` - The Set Payload component (``) sends the array `[1,2,3,4,5]` to the Batch Job component. - The Batch Job component (``) sets `maxFailedRecords` to `-1` so that failed records within the first Batch Step component do not stop the batch job instance from processing. - The first Batch Step (`batchStep1`) configures `acceptExpression="#[payload < 3]"` to accept only records with a payload less than `3` and throws an error on those records because of the Raise Error component within it: ```logs INFO ...DefaultBatchStep: Found error processing record on step 'batchStep1' for job instance 'f9bb6d60-5ef2-11ed-81e7-147ddaaf4f97' of job 'batch-example-policiesBatch_Job'. ``` - The second Batch Step (`batchStep2`) prints the payload of the failed records, for example: ```logs INFO ... LOGGER IN SECOND BATCH STEP: 1 INFO ... LOGGER IN SECOND BATCH STEP: 2 ``` - The third Batch Step (`batchStep3`) prints the payload of the successful records, for example: ```logs INFO ... LOGS IN THIRD BATCH STEP: 3 INFO ...LOGS IN THIRD BATCH STEP: 4 INFO ...LOGS IN THIRD BATCH STEP: 5 ``` - After the batch job instance completes, the logs indicate that `3` records processed successfully and `2` records failed: ```logs INFO ...engine.DefaultBatchEngine: Finished execution for instance ... Total Records processed: 5. Successful records: 3. Failed Records: 2 ``` For more information, see [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.11/batch-error-handling-faq). ## Performing Bulk Operations from a Batch Aggregator Component Aggregation is useful for sending multiple records within an array to an external server. Within the Batch Aggregator component, you can add an operation, such as a bulk upsert, insert, or update operation, to load multiple records to a server with a single execution of an operation, instead of running an operation separately on each record. You can process records in separate arrays of a fixed size or stream a single array of records from the batch job instance. For example, you can configure an Upsert operation in the Anypoint Connector for Salesforce (Salesforce Connector) to upsert 200 processed records. Alternatively, you can stream all the records in the instance to the server. The following example bulk upserts records in separate arrays of 200 records per upsert: ```xml ``` The following example streams upserts to a database: ```xml salesforce:upsert doc:name="Upsert" ... /> ``` Error handling: Some connectors handle record-level errors without causing an entire batch aggregation process to fail, for example, [Anypoint Connector for Salesforce (Salesforce Connector)](https://docs.mulesoft.com/salesforce-connector/latest/salesforce-connector-reference#upsert) and [Anypoint Connector for NetSuite (NetSuite Connector)](https://docs.mulesoft.com/netsuite-connector/latest/netsuite-reference#Upsert). At runtime, these connectors keep track of records that the target resource accepts successfully and which fail. Rather than failing the entire group of records, the connector upserts as many records as it can and tracks any failures for notification purposes. To learn more about processing within the Batch Aggregator component and how aggregation differs from processing within the Batch Step component, see [Process Phase](https://docs.mulesoft.com/mule-runtime/4.11/batch-processing-concept#phase_process). ## Modifying Records within a Batch Aggregator You can modify records within the Batch Aggregator component, just as you can modify them with processors in the Batch Step component. The modifications can take place sequentially or through random access to specific records. ### Sequential Processing within a Batch Aggregator The following example performs sequential access to records. Using Groovy within a [Scripting module](https://docs.mulesoft.com/scripting-module/latest/), the example modifies the payload of each record from the [For Each](https://docs.mulesoft.com/mule-runtime/4.11/for-each-scope-concept) component’s iteration and creates a variable for each collected record. ```xml vars['marco'] = 'polo' vars['record'].payload = 'hello' ``` ### Randomly Accessing Records within a Batch Aggregator You can also use the For Each scope when randomly accessing records by their iteration number. For Each exposes a `records` variable, which is an immutable list that it uses to keep track of the iteration. You can use this variable to randomly access records in the list from the Batch Aggregator component. To demonstrate random access when using fixed-size aggregation, the following example specifies the index of a record in the For Each list of records. Instead of sequentially accessing each record, using the `records` variable with an index of a record selects a single record from the list. The example uses the Scripting module to modify the payload of the selected record and create a variable for that record: ```xml records[0].vars['marco'] = 'polo' records[0].vars['record'].payload = 'hello' ``` You can configure a Batch Aggregator component to stream its content. Setting this component to stream the records (`streaming="true"`) enables you to process an array of all the records in the batch job instance without running out of memory, regardless of how many or how large the records are. For example, if you need to write millions of records to a CSV file, you can stream the records with the Batch Aggregator component. ```xml ``` As the following example shows, only sequential access to records is possible when streaming within the Batch Aggregator component. Random access is not supported when streaming because streaming requires access to the entire set of records. This restriction is necessary because Mule cannot guarantee that all records will fit in memory if no fixed size is specified. ```xml vars['marco'] = 'polo' vars['record'].payload = 'foo' ``` To learn more about processing within the Batch Aggregator component and how aggregation differs from processing within the Batch Step component, see [Process Phase](https://docs.mulesoft.com/mule-runtime/4.11/batch-processing-concept#phase_process). NOTE When using a Batch Aggregator component, do not attempt to process Guava data types, such as `ImmutableMap`. Instead, use a Java Map to avoid serialization issues. ## Preserving the MIME types of the Aggregated Records _Introduced in Mule 4.3_ Aggregated records pass into the Batch Aggregator component as an array containing each record’s payload. However, by default, the MIME types associated with those payloads are not preserved. To preserve record’s MIME types, specify the `preserveMimeTypes` attribute in the Batch Aggregator component. Consider the following JSON array: ```json [ { "name": "Tony Stark", "alias": "Iron Man", "status": "DEAD" }, { "name": "Steve Rodgers", "alias": "Captain America", "status": "RETIRED" }, { "name": "Peter Parker", "alias": "SpiderMan", "status": "FUGITIVE" } ] ``` Assume that the [JSON array](#json_array) is the input to the following Batch Job component: ```xml ``` The batch engine splits the input JSON array into individual records, which aggregator block receives an array with three elements. The first one of them is: ```json { "name": "Tony Stark", "alias": "Iron Man", "status": "DEAD" } ``` However, when the Logger component attempts to evaluate the `#[payload.alias]` expression, an error similar to the following one results: ```text ******************************************************************************** Message : "You called the function 'Value Selector' with these arguments: 1: Binary ("ewogICJmaXJzdE5hbWUiOiAiUmFtIiwKICAibGFzdE5hbWUiOiAiUmFtMSIsCiAgImFkZHJlc3Mi...) 2: Name ("alias") But it expects one of these combinations: (Array, Name) (Array, String) (Date, Name) (DateTime, Name) (LocalDateTime, Name) (LocalTime, Name) (Object, Name) (Object, String) (Period, Name) (Time, Name) 5| name: payload.alias, ^^^^^^^^^^^^^ ``` This error occurs because MIME types are not preserved, which prevents Mule from reading it as JSON. To resolve this issue, you must set the `preserveMimeTypes` attribute in the Batch Aggregator component to `true`, for example: ```xml ``` The setting makes Mule maintain each record’s media type and treat the payload as a JSON document. ## Changing the Record Block Size A traditional online processing model typically maps each request to a worker thread. Generally, there is 1:1 relationship between a request and a running thread regardless of the processing type. This relationship holds for synchronous, asynchronous, one-way, and request-response processing types, and when temporarily buffering requests before processing. However, in a batch job, the traditional threading model does not apply because records are first stored in a persistent queue, before the Process phase begins. To improve performance, Mule runtime queues and schedules batch records in blocks of up to 100 records per thread. This behavior reduces the number of I/O requests and improves an operation’s load. Batch jobs use Mule thread pools, so there is no default for the job. Each thread iterates through that block to process each record, and then each block is queued back, and the process continues. Consider having 1 million records to place in a queue for a 3-step batch job. At least three million I/O operations occur as the Mule runtime engine takes and requests each record as they move through the job’s phases. Performance requires having enough available memory to process the threads in parallel, which means moving the records from persistent storage into RAM. The larger your records and their quantity, the more available memory you need for batch processing. Although the standard model of up to 100 records per thread in the batch job works for most use cases, consider three use cases where you need to increase or decrease the block size: - Assume you have 200 records to process through a batch job. With the default 100-record block size, Mule can only process two records in parallel at a time. If a batch job has fewer than 101 records to process, then processing becomes sequential. If you need to process heavy payloads, then queueing a hundred records demands a large amount of working memory. - Consider a batch job that needs to process images, and an average image size of 3 MB. In this case, Mule processes 100-record blocks with payloads of 3 MB in each thread. Hence, your default threading-profile setting would require a large amount of working memory just to keep the blocks in the queue. In this case, set a lower block size to distribute each payload through more jobs and lessen the load on your available memory. - Suppose you have 5 million records with payloads so small that you can fit blocks of 500 records in your memory without problems. Setting a larger block size improves your batch job time without sacrificing working memory load. To take full advantage of this feature, you must understand how the block sizes affect your batch job. Running comparative tests with different values and testing performance helps you find an optimum block size before moving this change into production. Remember that modifying the batch block size is optional. If you apply no changes, the default value is 100 records per block. You set the size through the Batch Job component, for example: ```xml ... ``` ## Setting a Max Concurrency Limit on Batch Job Instances The Max Concurrency (`maxConcurrency`) property limits the number of record blocks to process concurrently. You can configure the `maxConcurrency` property as in the following example: ```xml ... ``` By default, the Batch Job component limits the maximum concurrency to twice the number of available cores. The capacity of the system running the Mule instance also limits concurrency. ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.11/batch-processing-concept) - [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/4.11/batch-job-instance-id) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.11/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.12 --- # Configuring Batch Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can set up and configure Mule batch processing components to perform common batch processing use cases and to enhance the performance of batch jobs for cases in which the defaults require adjustment. ## Filtering Records to Process within a Batch Step Component You can apply one or more record filters as attributes to any number of Batch Step components. For example, assume that the first Batch Step component within a given Batch Job component checks for a Salesforce contact in each record and the second updates the contact information in those records. To ensure that the second Batch Step processes only records that succeeded in the first step, you can configure a filter on the second Batch Step. The filter streamlines processing so that Mule focuses on only the relevant data for a given step. To filter records, the Batch Step component supports one `acceptExpression` and one `acceptPolicy`. Both are optional, and no other Mule components accept these filters. If you use both filters on the same component, Mule evaluates the filters in the following order: 1. Accept Policy: [acceptPolicy](#accept_policy) 2. Accept Expression: [acceptExpression](#accept_expression) A Batch Step component that uses an `acceptExpression` attribute applies a DataWeave expression to each record that reaches the component and accepts a record for processing within the component only if the expression evaluates to `true` for that record. If the record evaluates to `false`, the Batch Step component skips the record, and that record becomes available to the next Batch Step component within the Batch Job component if one exists. The example below filters out all records in which the `age` value is less than `21`: ```xml ... ``` A Batch Step component uses an `acceptPolicy` attribute to apply a policy to records processed in a previous Batch Step component. The Batch Step accepts a record for processing within the component only if the policy evaluates to `true` for that record. The default policy is `NO_FAILURES`. Other policies are `ONLY_FAILURES` and `ALL`. For descriptions of these policies, see [Batch Step Component ()](https://docs.mulesoft.com/mule-runtime/4.12/batch-reference#ref_batch_step_component). In the following example, the second Batch Step component (`batchStep2`) accepts only those records that failed to process successfully during the preceding step (`batchStep1`). For example, assume processors within `batchStep1` check each record for a Salesforce contact. If the check fails to find a contact, `batchStep2` accepts only those records without contacts, skipping records with contacts. Message processors within `batchStep2` can add a contact to those records. ```xml ... ... ``` For demonstration purposes, the following example uses the Raise Error component (``) to produce failures in the first Batch Step (`batchStep1`). The second Batch Step (`batchStep2`) accepts failed records only (`ONLY_FAILURES`) and logs the payload of those records. The third uses the default `acceptPolicy` to accept `NO_FAILURES`. ```xml ``` - The Set Payload component (``) sends the array `[1,2,3,4,5]` to the Batch Job component. - The Batch Job component (``) sets `maxFailedRecords` to `-1` so that failed records within the first Batch Step component do not stop the batch job instance from processing. - The first Batch Step (`batchStep1`) configures `acceptExpression="#[payload < 3]"` to accept only records with a payload less than `3` and throws an error on those records because of the Raise Error component within it: ```logs INFO ...DefaultBatchStep: Found error processing record on step 'batchStep1' for job instance 'f9bb6d60-5ef2-11ed-81e7-147ddaaf4f97' of job 'batch-example-policiesBatch_Job'. ``` - The second Batch Step (`batchStep2`) prints the payload of the failed records, for example: ```logs INFO ... LOGGER IN SECOND BATCH STEP: 1 INFO ... LOGGER IN SECOND BATCH STEP: 2 ``` - The third Batch Step (`batchStep3`) prints the payload of the successful records, for example: ```logs INFO ... LOGS IN THIRD BATCH STEP: 3 INFO ...LOGS IN THIRD BATCH STEP: 4 INFO ...LOGS IN THIRD BATCH STEP: 5 ``` - After the batch job instance completes, the logs indicate that `3` records processed successfully and `2` records failed: ```logs INFO ...engine.DefaultBatchEngine: Finished execution for instance ... Total Records processed: 5. Successful records: 3. Failed Records: 2 ``` For more information, see [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.12/batch-error-handling-faq). ## Performing Bulk Operations from a Batch Aggregator Component Aggregation is useful for sending multiple records within an array to an external server. Within the Batch Aggregator component, you can add an operation, such as a bulk upsert, insert, or update operation, to load multiple records to a server with a single execution of an operation, instead of running an operation separately on each record. You can process records in separate arrays of a fixed size or stream a single array of records from the batch job instance. For example, you can configure an Upsert operation in the Anypoint Connector for Salesforce (Salesforce Connector) to upsert 200 processed records. Alternatively, you can stream all the records in the instance to the server. The following example bulk upserts records in separate arrays of 200 records per upsert: ```xml ``` The following example streams upserts to a database: ```xml salesforce:upsert doc:name="Upsert" ... /> ``` Error handling: Some connectors handle record-level errors without causing an entire batch aggregation process to fail, for example, [Anypoint Connector for Salesforce (Salesforce Connector)](https://docs.mulesoft.com/salesforce-connector/latest/salesforce-connector-reference#upsert) and [Anypoint Connector for NetSuite (NetSuite Connector)](https://docs.mulesoft.com/netsuite-connector/latest/netsuite-reference#Upsert). At runtime, these connectors keep track of records that the target resource accepts successfully and which fail. Rather than failing the entire group of records, the connector upserts as many records as it can and tracks any failures for notification purposes. To learn more about processing within the Batch Aggregator component and how aggregation differs from processing within the Batch Step component, see [Process Phase](https://docs.mulesoft.com/mule-runtime/4.12/batch-processing-concept#phase_process). ## Modifying Records within a Batch Aggregator You can modify records within the Batch Aggregator component, just as you can modify them with processors in the Batch Step component. The modifications can take place sequentially or through random access to specific records. ### Sequential Processing within a Batch Aggregator The following example performs sequential access to records. Using Groovy within a [Scripting module](https://docs.mulesoft.com/scripting-module/latest/), the example modifies the payload of each record from the [For Each](https://docs.mulesoft.com/mule-runtime/4.12/for-each-scope-concept) component’s iteration and creates a variable for each collected record. ```xml vars['marco'] = 'polo' vars['record'].payload = 'hello' ``` ### Randomly Accessing Records within a Batch Aggregator You can also use the For Each scope when randomly accessing records by their iteration number. For Each exposes a `records` variable, which is an immutable list that it uses to keep track of the iteration. You can use this variable to randomly access records in the list from the Batch Aggregator component. To demonstrate random access when using fixed-size aggregation, the following example specifies the index of a record in the For Each list of records. Instead of sequentially accessing each record, using the `records` variable with an index of a record selects a single record from the list. The example uses the Scripting module to modify the payload of the selected record and create a variable for that record: ```xml records[0].vars['marco'] = 'polo' records[0].vars['record'].payload = 'hello' ``` You can configure a Batch Aggregator component to stream its content. Setting this component to stream the records (`streaming="true"`) enables you to process an array of all the records in the batch job instance without running out of memory, regardless of how many or how large the records are. For example, if you need to write millions of records to a CSV file, you can stream the records with the Batch Aggregator component. ```xml ``` As the following example shows, only sequential access to records is possible when streaming within the Batch Aggregator component. Random access is not supported when streaming because streaming requires access to the entire set of records. This restriction is necessary because Mule cannot guarantee that all records will fit in memory if no fixed size is specified. ```xml vars['marco'] = 'polo' vars['record'].payload = 'foo' ``` To learn more about processing within the Batch Aggregator component and how aggregation differs from processing within the Batch Step component, see [Process Phase](https://docs.mulesoft.com/mule-runtime/4.12/batch-processing-concept#phase_process). NOTE When using a Batch Aggregator component, do not attempt to process Guava data types, such as `ImmutableMap`. Instead, use a Java Map to avoid serialization issues. ## Preserving the MIME types of the Aggregated Records _Introduced in Mule 4.3_ Aggregated records pass into the Batch Aggregator component as an array containing each record’s payload. However, by default, the MIME types associated with those payloads are not preserved. To preserve record’s MIME types, specify the `preserveMimeTypes` attribute in the Batch Aggregator component. Consider the following JSON array: ```json [ { "name": "Tony Stark", "alias": "Iron Man", "status": "DEAD" }, { "name": "Steve Rodgers", "alias": "Captain America", "status": "RETIRED" }, { "name": "Peter Parker", "alias": "SpiderMan", "status": "FUGITIVE" } ] ``` Assume that the [JSON array](#json_array) is the input to the following Batch Job component: ```xml ``` The batch engine splits the input JSON array into individual records, which aggregator block receives an array with three elements. The first one of them is: ```json { "name": "Tony Stark", "alias": "Iron Man", "status": "DEAD" } ``` However, when the Logger component attempts to evaluate the `#[payload.alias]` expression, an error similar to the following one results: ```text ******************************************************************************** Message : "You called the function 'Value Selector' with these arguments: 1: Binary ("ewogICJmaXJzdE5hbWUiOiAiUmFtIiwKICAibGFzdE5hbWUiOiAiUmFtMSIsCiAgImFkZHJlc3Mi...) 2: Name ("alias") But it expects one of these combinations: (Array, Name) (Array, String) (Date, Name) (DateTime, Name) (LocalDateTime, Name) (LocalTime, Name) (Object, Name) (Object, String) (Period, Name) (Time, Name) 5| name: payload.alias, ^^^^^^^^^^^^^ ``` This error occurs because MIME types are not preserved, which prevents Mule from reading it as JSON. To resolve this issue, you must set the `preserveMimeTypes` attribute in the Batch Aggregator component to `true`, for example: ```xml ``` The setting makes Mule maintain each record’s media type and treat the payload as a JSON document. ## Changing the Record Block Size A traditional online processing model typically maps each request to a worker thread. Generally, there is 1:1 relationship between a request and a running thread regardless of the processing type. This relationship holds for synchronous, asynchronous, one-way, and request-response processing types, and when temporarily buffering requests before processing. However, in a batch job, the traditional threading model does not apply because records are first stored in a persistent queue, before the Process phase begins. To improve performance, Mule runtime queues and schedules batch records in blocks of up to 100 records per thread. This behavior reduces the number of I/O requests and improves an operation’s load. Batch jobs use Mule thread pools, so there is no default for the job. Each thread iterates through that block to process each record, and then each block is queued back, and the process continues. Consider having 1 million records to place in a queue for a 3-step batch job. At least three million I/O operations occur as the Mule runtime engine takes and requests each record as they move through the job’s phases. Performance requires having enough available memory to process the threads in parallel, which means moving the records from persistent storage into RAM. The larger your records and their quantity, the more available memory you need for batch processing. Although the standard model of up to 100 records per thread in the batch job works for most use cases, consider three use cases where you need to increase or decrease the block size: - Assume you have 200 records to process through a batch job. With the default 100-record block size, Mule can only process two records in parallel at a time. If a batch job has fewer than 101 records to process, then processing becomes sequential. If you need to process heavy payloads, then queueing a hundred records demands a large amount of working memory. - Consider a batch job that needs to process images, and an average image size of 3 MB. In this case, Mule processes 100-record blocks with payloads of 3 MB in each thread. Hence, your default threading-profile setting would require a large amount of working memory just to keep the blocks in the queue. In this case, set a lower block size to distribute each payload through more jobs and lessen the load on your available memory. - Suppose you have 5 million records with payloads so small that you can fit blocks of 500 records in your memory without problems. Setting a larger block size improves your batch job time without sacrificing working memory load. To take full advantage of this feature, you must understand how the block sizes affect your batch job. Running comparative tests with different values and testing performance helps you find an optimum block size before moving this change into production. Remember that modifying the batch block size is optional. If you apply no changes, the default value is 100 records per block. You set the size through the Batch Job component, for example: ```xml ... ``` ## Setting a Max Concurrency Limit on Batch Job Instances The Max Concurrency (`maxConcurrency`) property limits the number of record blocks to process concurrently. You can configure the `maxConcurrency` property as in the following example: ```xml ... ``` By default, the Batch Job component limits the maximum concurrency to twice the number of available cores. The capacity of the system running the Mule instance also limits concurrency. ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.12/batch-processing-concept) - [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/4.12/batch-job-instance-id) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.12/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.4 --- # Configuring Batch Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can set up and configure Mule batch processing components to perform common batch processing use cases and to enhance the performance of batch jobs for cases in which the defaults require adjustment. ## Filtering Records to Process within a Batch Step Component You can apply one or more record filters as attributes to any number of Batch Step components. For example, assume that the first Batch Step component within a given Batch Job component checks for a Salesforce contact in each record and the second updates the contact information in those records. To ensure that the second Batch Step processes only records that succeeded in the first step, you can configure a filter on the second Batch Step. The filter streamlines processing so that Mule focuses on only the relevant data for a given step. To filter records, the Batch Step component supports one `acceptExpression` and one `acceptPolicy`. Both are optional, and no other Mule components accept these filters. If you use both filters on the same component, Mule evaluates the filters in the following order: 1. Accept Policy: [acceptPolicy](#accept_policy) 2. Accept Expression: [acceptExpression](#accept_expression) A Batch Step component that uses an `acceptExpression` attribute applies a DataWeave expression to each record that reaches the component and accepts a record for processing within the component only if the expression evaluates to `true` for that record. If the record evaluates to `false`, the Batch Step component skips the record, and that record becomes available to the next Batch Step component within the Batch Job component if one exists. The example below filters out all records in which the `age` value is less than `21`: ```xml ... ``` A Batch Step component uses an `acceptPolicy` attribute to apply a policy to records processed in a previous Batch Step component. The Batch Step accepts a record for processing within the component only if the policy evaluates to `true` for that record. The default policy is `NO_FAILURES`. Other policies are `ONLY_FAILURES` and `ALL`. For descriptions of these policies, see [Batch Step Component ()](https://docs.mulesoft.com/mule-runtime/4.4/batch-reference#ref_batch_step_component). In the following example, the second Batch Step component (`batchStep2`) accepts only those records that failed to process successfully during the preceding step (`batchStep1`). For example, assume processors within `batchStep1` check each record for a Salesforce contact. If the check fails to find a contact, `batchStep2` accepts only those records without contacts, skipping records with contacts. Message processors within `batchStep2` can add a contact to those records. ```xml ... ... ``` For demonstration purposes, the following example uses the Raise Error component (``) to produce failures in the first Batch Step (`batchStep1`). The second Batch Step (`batchStep2`) accepts failed records only (`ONLY_FAILURES`) and logs the payload of those records. The third uses the default `acceptPolicy` to accept `NO_FAILURES`. ```xml ``` - The Set Payload component (``) sends the array `[1,2,3,4,5]` to the Batch Job component. - The Batch Job component (``) sets `maxFailedRecords` to `-1` so that failed records within the first Batch Step component do not stop the batch job instance from processing. - The first Batch Step (`batchStep1`) configures `acceptExpression="#[payload < 3]"` to accept only records with a payload less than `3` and throws an error on those records because of the Raise Error component within it: ```logs INFO ...DefaultBatchStep: Found exception processing record on step 'batchStep1' for job instance 'f9bb6d60-5ef2-11ed-81e7-147ddaaf4f97' of job 'batch-example-policiesBatch_Job'. ``` - The second Batch Step (`batchStep2`) prints the payload of the failed records, for example: ```logs INFO ... LOGGER IN SECOND BATCH STEP: 1 INFO ... LOGGER IN SECOND BATCH STEP: 2 ``` - The third Batch Step (`batchStep3`) prints the payload of the successful records, for example: ```logs INFO ... LOGS IN THIRD BATCH STEP: 3 INFO ...LOGS IN THIRD BATCH STEP: 4 INFO ...LOGS IN THIRD BATCH STEP: 5 ``` - After the batch job instance completes, the logs indicate that `3` records processed successfully and `2` records failed: ```logs INFO ...engine.DefaultBatchEngine: Finished execution for instance ... Total Records processed: 5. Successful records: 3. Failed Records: 2 ``` For more information, see [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.4/batch-error-handling-faq). ## Performing Bulk Operations from a Batch Aggregator Component Aggregation is useful for sending multiple records within an array to an external server. Within the Batch Aggregator component, you can add an operation, such as a bulk upsert, insert, or update operation, to load multiple records to a server with a single execution of an operation, instead of running an operation separately on each record. You can process records in separate arrays of a fixed size or stream a single array of records from the batch job instance. For example, you can configure an Upsert operation in the Anypoint Connector for Salesforce (Salesforce Connector) to upsert 200 processed records. Alternatively, you can stream all the records in the instance to the server. The following example bulk upserts records in separate arrays of 200 records per upsert: ```xml ``` The following example streams upserts to a database: ```xml salesforce:upsert doc:name="Upsert" ... /> ``` Error handling: Some connectors handle record-level errors without causing an entire batch aggregation process to fail, for example, [Anypoint Connector for Salesforce (Salesforce Connector)](https://docs.mulesoft.com/salesforce-connector/latest/salesforce-connector-reference#upsert) and [Anypoint Connector for NetSuite (NetSuite Connector)](https://docs.mulesoft.com/netsuite-connector/latest/netsuite-reference#Upsert). At runtime, these connectors keep track of records that the target resource accepts successfully and which fail. Rather than failing the entire group of records, the connector upserts as many records as it can and tracks any failures for notification purposes. To learn more about processing within the Batch Aggregator component and how aggregation differs from processing within the Batch Step component, see [Process Phase](https://docs.mulesoft.com/mule-runtime/4.4/batch-processing-concept#phase_process). ## Modifying Records within a Batch Aggregator You can modify records within the Batch Aggregator component, just as you can modify them with processors in the Batch Step component. The modifications can take place sequentially or through random access to specific records. ### Sequential Processing within a Batch Aggregator The following example performs sequential access to records. Using Groovy within a [Scripting module](https://docs.mulesoft.com/scripting-module/latest/), the example modifies the payload of each record from the [For Each](https://docs.mulesoft.com/mule-runtime/4.4/for-each-scope-concept) component’s iteration and creates a variable for each collected record. ```xml vars['marco'] = 'polo' vars['record'].payload = 'hello' ``` ### Randomly Accessing Records within a Batch Aggregator You can also use the For Each scope when randomly accessing records by their iteration number. For Each exposes a `records` variable, which is an immutable list that it uses to keep track of the iteration. You can use this variable to randomly access records in the list from the Batch Aggregator component. To demonstrate random access when using fixed-size aggregation, the following example specifies the index of a record in the For Each list of records. Instead of sequentially accessing each record, using the `records` variable with an index of a record selects a single record from the list. The example uses the Scripting module to modify the payload of the selected record and create a variable for that record: ```xml records[0].vars['marco'] = 'polo' records[0].vars['record'].payload = 'hello' ``` You can configure a Batch Aggregator component to stream its content. Setting this component to stream the records (`streaming="true"`) enables you to process an array of all the records in the batch job instance without running out of memory, regardless of how many or how large the records are. For example, if you need to write millions of records to a CSV file, you can stream the records with the Batch Aggregator component. ```xml ``` As the following example shows, only sequential access to records is possible when streaming within the Batch Aggregator component. Random access is not supported when streaming because streaming requires access to the entire set of records. This restriction is necessary because Mule cannot guarantee that all records will fit in memory if no fixed size is specified. ```xml vars['marco'] = 'polo' vars['record'].payload = 'foo' ``` To learn more about processing within the Batch Aggregator component and how aggregation differs from processing within the Batch Step component, see [Process Phase](https://docs.mulesoft.com/mule-runtime/4.4/batch-processing-concept#phase_process). NOTE When using a Batch Aggregator component, do not attempt to process Guava data types, such as `ImmutableMap`. Instead, use a Java Map to avoid serialization issues. ## Preserving the MIME types of the Aggregated Records _Introduced in Mule 4.3_ Aggregated records pass into the Batch Aggregator component as an array containing each record’s payload. However, by default, the MIME types associated with those payloads are not preserved. To preserve record’s MIME types, specify the `preserveMimeTypes` attribute in the Batch Aggregator component. Consider the following JSON array: ```json [ { "name": "Tony Stark", "alias": "Iron Man", "status": "DEAD" }, { "name": "Steve Rodgers", "alias": "Captain America", "status": "RETIRED" }, { "name": "Peter Parker", "alias": "SpiderMan", "status": "FUGITIVE" } ] ``` Assume that the [JSON array](#json_array) is the input to the following Batch Job component: ```xml ``` The batch engine splits the input JSON array into individual records, which aggregator block receives an array with three elements. The first one of them is: ```json { "name": "Tony Stark", "alias": "Iron Man", "status": "DEAD" } ``` However, when the Logger component attempts to evaluate the `#[payload.alias]` expression, an error similar to the following one results: ```text ******************************************************************************** Message : "You called the function 'Value Selector' with these arguments: 1: Binary ("ewogICJmaXJzdE5hbWUiOiAiUmFtIiwKICAibGFzdE5hbWUiOiAiUmFtMSIsCiAgImFkZHJlc3Mi...) 2: Name ("alias") But it expects one of these combinations: (Array, Name) (Array, String) (Date, Name) (DateTime, Name) (LocalDateTime, Name) (LocalTime, Name) (Object, Name) (Object, String) (Period, Name) (Time, Name) 5| name: payload.alias, ^^^^^^^^^^^^^ ``` This error occurs because MIME types are not preserved, which prevents Mule from reading it as JSON. To resolve this issue, you must set the `preserveMimeTypes` attribute in the Batch Aggregator component to `true`, for example: ```xml ``` The setting makes Mule maintain each record’s media type and treat the payload as a JSON document. ## Changing the Record Block Size A traditional online processing model typically maps each request to a worker thread. Generally, there is 1:1 relationship between a request and a running thread regardless of the processing type. This relationship holds for synchronous, asynchronous, one-way, and request-response processing types, and when temporarily buffering requests before processing. However, in a batch job, the traditional threading model does not apply because records are first stored in a persistent queue, before the Process phase begins. To improve performance, Mule runtime queues and schedules batch records in blocks of up to 100 records per thread. This behavior reduces the number of I/O requests and improves an operation’s load. Batch jobs use Mule thread pools, so there is no default for the job. Each thread iterates through that block to process each record, and then each block is queued back, and the process continues. Consider having 1 million records to place in a queue for a 3-step batch job. At least three million I/O operations occur as the Mule runtime engine takes and requests each record as they move through the job’s phases. Performance requires having enough available memory to process the threads in parallel, which means moving the records from persistent storage into RAM. The larger your records and their quantity, the more available memory you need for batch processing. Although the standard model of up to 100 records per thread in the batch job works for most use cases, consider three use cases where you need to increase or decrease the block size: - Assume you have 200 records to process through a batch job. With the default 100-record block size, Mule can only process two records in parallel at a time. If a batch job has fewer than 101 records to process, then processing becomes sequential. If you need to process heavy payloads, then queueing a hundred records demands a large amount of working memory. - Consider a batch job that needs to process images, and an average image size of 3 MB. In this case, Mule processes 100-record blocks with payloads of 3 MB in each thread. Hence, your default threading-profile setting would require a large amount of working memory just to keep the blocks in the queue. In this case, set a lower block size to distribute each payload through more jobs and lessen the load on your available memory. - Suppose you have 5 million records with payloads so small that you can fit blocks of 500 records in your memory without problems. Setting a larger block size improves your batch job time without sacrificing working memory load. To take full advantage of this feature, you must understand how the block sizes affect your batch job. Running comparative tests with different values and testing performance helps you find an optimum block size before moving this change into production. Remember that modifying the batch block size is optional. If you apply no changes, the default value is 100 records per block. You set the size through the Batch Job component, for example: ```xml ... ``` ## Setting a Max Concurrency Limit on Batch Job Instances The Max Concurrency (`maxConcurrency`) property limits the number of record blocks to process concurrently. You can configure the `maxConcurrency` property as in the following example: ```xml ... ``` By default, the Batch Job component limits the maximum concurrency to twice the number of available cores. The capacity of the system running the Mule instance also limits concurrency. ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.4/batch-processing-concept) - [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/4.4/batch-job-instance-id) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.4/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.6 --- # Configuring Batch Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can set up and configure Mule batch processing components to perform common batch processing use cases and to enhance the performance of batch jobs for cases in which the defaults require adjustment. ## Filtering Records to Process within a Batch Step Component You can apply one or more record filters as attributes to any number of Batch Step components. For example, assume that the first Batch Step component within a given Batch Job component checks for a Salesforce contact in each record and the second updates the contact information in those records. To ensure that the second Batch Step processes only records that succeeded in the first step, you can configure a filter on the second Batch Step. The filter streamlines processing so that Mule focuses on only the relevant data for a given step. To filter records, the Batch Step component supports one `acceptExpression` and one `acceptPolicy`. Both are optional, and no other Mule components accept these filters. If you use both filters on the same component, Mule evaluates the filters in the following order: 1. Accept Policy: [acceptPolicy](#accept_policy) 2. Accept Expression: [acceptExpression](#accept_expression) A Batch Step component that uses an `acceptExpression` attribute applies a DataWeave expression to each record that reaches the component and accepts a record for processing within the component only if the expression evaluates to `true` for that record. If the record evaluates to `false`, the Batch Step component skips the record, and that record becomes available to the next Batch Step component within the Batch Job component if one exists. The example below filters out all records in which the `age` value is less than `21`: ```xml ... ``` A Batch Step component uses an `acceptPolicy` attribute to apply a policy to records processed in a previous Batch Step component. The Batch Step accepts a record for processing within the component only if the policy evaluates to `true` for that record. The default policy is `NO_FAILURES`. Other policies are `ONLY_FAILURES` and `ALL`. For descriptions of these policies, see [Batch Step Component ()](https://docs.mulesoft.com/mule-runtime/4.6/batch-reference#ref_batch_step_component). In the following example, the second Batch Step component (`batchStep2`) accepts only those records that failed to process successfully during the preceding step (`batchStep1`). For example, assume processors within `batchStep1` check each record for a Salesforce contact. If the check fails to find a contact, `batchStep2` accepts only those records without contacts, skipping records with contacts. Message processors within `batchStep2` can add a contact to those records. ```xml ... ... ``` For demonstration purposes, the following example uses the Raise Error component (``) to produce failures in the first Batch Step (`batchStep1`). The second Batch Step (`batchStep2`) accepts failed records only (`ONLY_FAILURES`) and logs the payload of those records. The third uses the default `acceptPolicy` to accept `NO_FAILURES`. ```xml ``` - The Set Payload component (``) sends the array `[1,2,3,4,5]` to the Batch Job component. - The Batch Job component (``) sets `maxFailedRecords` to `-1` so that failed records within the first Batch Step component do not stop the batch job instance from processing. - The first Batch Step (`batchStep1`) configures `acceptExpression="#[payload < 3]"` to accept only records with a payload less than `3` and throws an error on those records because of the Raise Error component within it: ```logs INFO ...DefaultBatchStep: Found exception processing record on step 'batchStep1' for job instance 'f9bb6d60-5ef2-11ed-81e7-147ddaaf4f97' of job 'batch-example-policiesBatch_Job'. ``` - The second Batch Step (`batchStep2`) prints the payload of the failed records, for example: ```logs INFO ... LOGGER IN SECOND BATCH STEP: 1 INFO ... LOGGER IN SECOND BATCH STEP: 2 ``` - The third Batch Step (`batchStep3`) prints the payload of the successful records, for example: ```logs INFO ... LOGS IN THIRD BATCH STEP: 3 INFO ...LOGS IN THIRD BATCH STEP: 4 INFO ...LOGS IN THIRD BATCH STEP: 5 ``` - After the batch job instance completes, the logs indicate that `3` records processed successfully and `2` records failed: ```logs INFO ...engine.DefaultBatchEngine: Finished execution for instance ... Total Records processed: 5. Successful records: 3. Failed Records: 2 ``` For more information, see [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.6/batch-error-handling-faq). ## Performing Bulk Operations from a Batch Aggregator Component Aggregation is useful for sending multiple records within an array to an external server. Within the Batch Aggregator component, you can add an operation, such as a bulk upsert, insert, or update operation, to load multiple records to a server with a single execution of an operation, instead of running an operation separately on each record. You can process records in separate arrays of a fixed size or stream a single array of records from the batch job instance. For example, you can configure an Upsert operation in the Anypoint Connector for Salesforce (Salesforce Connector) to upsert 200 processed records. Alternatively, you can stream all the records in the instance to the server. The following example bulk upserts records in separate arrays of 200 records per upsert: ```xml ``` The following example streams upserts to a database: ```xml salesforce:upsert doc:name="Upsert" ... /> ``` Error handling: Some connectors handle record-level errors without causing an entire batch aggregation process to fail, for example, [Anypoint Connector for Salesforce (Salesforce Connector)](https://docs.mulesoft.com/salesforce-connector/latest/salesforce-connector-reference#upsert) and [Anypoint Connector for NetSuite (NetSuite Connector)](https://docs.mulesoft.com/netsuite-connector/latest/netsuite-reference#Upsert). At runtime, these connectors keep track of records that the target resource accepts successfully and which fail. Rather than failing the entire group of records, the connector upserts as many records as it can and tracks any failures for notification purposes. To learn more about processing within the Batch Aggregator component and how aggregation differs from processing within the Batch Step component, see [Process Phase](https://docs.mulesoft.com/mule-runtime/4.6/batch-processing-concept#phase_process). ## Modifying Records within a Batch Aggregator You can modify records within the Batch Aggregator component, just as you can modify them with processors in the Batch Step component. The modifications can take place sequentially or through random access to specific records. ### Sequential Processing within a Batch Aggregator The following example performs sequential access to records. Using Groovy within a [Scripting module](https://docs.mulesoft.com/scripting-module/latest/), the example modifies the payload of each record from the [For Each](https://docs.mulesoft.com/mule-runtime/4.6/for-each-scope-concept) component’s iteration and creates a variable for each collected record. ```xml vars['marco'] = 'polo' vars['record'].payload = 'hello' ``` ### Randomly Accessing Records within a Batch Aggregator You can also use the For Each scope when randomly accessing records by their iteration number. For Each exposes a `records` variable, which is an immutable list that it uses to keep track of the iteration. You can use this variable to randomly access records in the list from the Batch Aggregator component. To demonstrate random access when using fixed-size aggregation, the following example specifies the index of a record in the For Each list of records. Instead of sequentially accessing each record, using the `records` variable with an index of a record selects a single record from the list. The example uses the Scripting module to modify the payload of the selected record and create a variable for that record: ```xml records[0].vars['marco'] = 'polo' records[0].vars['record'].payload = 'hello' ``` You can configure a Batch Aggregator component to stream its content. Setting this component to stream the records (`streaming="true"`) enables you to process an array of all the records in the batch job instance without running out of memory, regardless of how many or how large the records are. For example, if you need to write millions of records to a CSV file, you can stream the records with the Batch Aggregator component. ```xml ``` As the following example shows, only sequential access to records is possible when streaming within the Batch Aggregator component. Random access is not supported when streaming because streaming requires access to the entire set of records. This restriction is necessary because Mule cannot guarantee that all records will fit in memory if no fixed size is specified. ```xml vars['marco'] = 'polo' vars['record'].payload = 'foo' ``` To learn more about processing within the Batch Aggregator component and how aggregation differs from processing within the Batch Step component, see [Process Phase](https://docs.mulesoft.com/mule-runtime/4.6/batch-processing-concept#phase_process). NOTE When using a Batch Aggregator component, do not attempt to process Guava data types, such as `ImmutableMap`. Instead, use a Java Map to avoid serialization issues. ## Preserving the MIME types of the Aggregated Records _Introduced in Mule 4.3_ Aggregated records pass into the Batch Aggregator component as an array containing each record’s payload. However, by default, the MIME types associated with those payloads are not preserved. To preserve record’s MIME types, specify the `preserveMimeTypes` attribute in the Batch Aggregator component. Consider the following JSON array: ```json [ { "name": "Tony Stark", "alias": "Iron Man", "status": "DEAD" }, { "name": "Steve Rodgers", "alias": "Captain America", "status": "RETIRED" }, { "name": "Peter Parker", "alias": "SpiderMan", "status": "FUGITIVE" } ] ``` Assume that the [JSON array](#json_array) is the input to the following Batch Job component: ```xml ``` The batch engine splits the input JSON array into individual records, which aggregator block receives an array with three elements. The first one of them is: ```json { "name": "Tony Stark", "alias": "Iron Man", "status": "DEAD" } ``` However, when the Logger component attempts to evaluate the `#[payload.alias]` expression, an error similar to the following one results: ```text ******************************************************************************** Message : "You called the function 'Value Selector' with these arguments: 1: Binary ("ewogICJmaXJzdE5hbWUiOiAiUmFtIiwKICAibGFzdE5hbWUiOiAiUmFtMSIsCiAgImFkZHJlc3Mi...) 2: Name ("alias") But it expects one of these combinations: (Array, Name) (Array, String) (Date, Name) (DateTime, Name) (LocalDateTime, Name) (LocalTime, Name) (Object, Name) (Object, String) (Period, Name) (Time, Name) 5| name: payload.alias, ^^^^^^^^^^^^^ ``` This error occurs because MIME types are not preserved, which prevents Mule from reading it as JSON. To resolve this issue, you must set the `preserveMimeTypes` attribute in the Batch Aggregator component to `true`, for example: ```xml ``` The setting makes Mule maintain each record’s media type and treat the payload as a JSON document. ## Changing the Record Block Size A traditional online processing model typically maps each request to a worker thread. Generally, there is 1:1 relationship between a request and a running thread regardless of the processing type. This relationship holds for synchronous, asynchronous, one-way, and request-response processing types, and when temporarily buffering requests before processing. However, in a batch job, the traditional threading model does not apply because records are first stored in a persistent queue, before the Process phase begins. To improve performance, Mule runtime queues and schedules batch records in blocks of up to 100 records per thread. This behavior reduces the number of I/O requests and improves an operation’s load. Batch jobs use Mule thread pools, so there is no default for the job. Each thread iterates through that block to process each record, and then each block is queued back, and the process continues. Consider having 1 million records to place in a queue for a 3-step batch job. At least three million I/O operations occur as the Mule runtime engine takes and requests each record as they move through the job’s phases. Performance requires having enough available memory to process the threads in parallel, which means moving the records from persistent storage into RAM. The larger your records and their quantity, the more available memory you need for batch processing. Although the standard model of up to 100 records per thread in the batch job works for most use cases, consider three use cases where you need to increase or decrease the block size: - Assume you have 200 records to process through a batch job. With the default 100-record block size, Mule can only process two records in parallel at a time. If a batch job has fewer than 101 records to process, then processing becomes sequential. If you need to process heavy payloads, then queueing a hundred records demands a large amount of working memory. - Consider a batch job that needs to process images, and an average image size of 3 MB. In this case, Mule processes 100-record blocks with payloads of 3 MB in each thread. Hence, your default threading-profile setting would require a large amount of working memory just to keep the blocks in the queue. In this case, set a lower block size to distribute each payload through more jobs and lessen the load on your available memory. - Suppose you have 5 million records with payloads so small that you can fit blocks of 500 records in your memory without problems. Setting a larger block size improves your batch job time without sacrificing working memory load. To take full advantage of this feature, you must understand how the block sizes affect your batch job. Running comparative tests with different values and testing performance helps you find an optimum block size before moving this change into production. Remember that modifying the batch block size is optional. If you apply no changes, the default value is 100 records per block. You set the size through the Batch Job component, for example: ```xml ... ``` ## Setting a Max Concurrency Limit on Batch Job Instances The Max Concurrency (`maxConcurrency`) property limits the number of record blocks to process concurrently. You can configure the `maxConcurrency` property as in the following example: ```xml ... ``` By default, the Batch Job component limits the maximum concurrency to twice the number of available cores. The capacity of the system running the Mule instance also limits concurrency. ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.6/batch-processing-concept) - [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/4.6/batch-job-instance-id) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.6/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.9 --- # Configuring Batch Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can set up and configure Mule batch processing components to perform common batch processing use cases and to enhance the performance of batch jobs for cases in which the defaults require adjustment. ## Filtering Records to Process within a Batch Step Component You can apply one or more record filters as attributes to any number of Batch Step components. For example, assume that the first Batch Step component within a given Batch Job component checks for a Salesforce contact in each record and the second updates the contact information in those records. To ensure that the second Batch Step processes only records that succeeded in the first step, you can configure a filter on the second Batch Step. The filter streamlines processing so that Mule focuses on only the relevant data for a given step. To filter records, the Batch Step component supports one `acceptExpression` and one `acceptPolicy`. Both are optional, and no other Mule components accept these filters. If you use both filters on the same component, Mule evaluates the filters in the following order: 1. Accept Policy: [acceptPolicy](#accept_policy) 2. Accept Expression: [acceptExpression](#accept_expression) A Batch Step component that uses an `acceptExpression` attribute applies a DataWeave expression to each record that reaches the component and accepts a record for processing within the component only if the expression evaluates to `true` for that record. If the record evaluates to `false`, the Batch Step component skips the record, and that record becomes available to the next Batch Step component within the Batch Job component if one exists. The example below filters out all records in which the `age` value is less than `21`: ```xml ... ``` A Batch Step component uses an `acceptPolicy` attribute to apply a policy to records processed in a previous Batch Step component. The Batch Step accepts a record for processing within the component only if the policy evaluates to `true` for that record. The default policy is `NO_FAILURES`. Other policies are `ONLY_FAILURES` and `ALL`. For descriptions of these policies, see [Batch Step Component ()](https://docs.mulesoft.com/mule-runtime/4.9/batch-reference#ref_batch_step_component). In the following example, the second Batch Step component (`batchStep2`) accepts only those records that failed to process successfully during the preceding step (`batchStep1`). For example, assume processors within `batchStep1` check each record for a Salesforce contact. If the check fails to find a contact, `batchStep2` accepts only those records without contacts, skipping records with contacts. Message processors within `batchStep2` can add a contact to those records. ```xml ... ... ``` For demonstration purposes, the following example uses the Raise Error component (``) to produce failures in the first Batch Step (`batchStep1`). The second Batch Step (`batchStep2`) accepts failed records only (`ONLY_FAILURES`) and logs the payload of those records. The third uses the default `acceptPolicy` to accept `NO_FAILURES`. ```xml ``` - The Set Payload component (``) sends the array `[1,2,3,4,5]` to the Batch Job component. - The Batch Job component (``) sets `maxFailedRecords` to `-1` so that failed records within the first Batch Step component do not stop the batch job instance from processing. - The first Batch Step (`batchStep1`) configures `acceptExpression="#[payload < 3]"` to accept only records with a payload less than `3` and throws an error on those records because of the Raise Error component within it: ```logs INFO ...DefaultBatchStep: Found exception processing record on step 'batchStep1' for job instance 'f9bb6d60-5ef2-11ed-81e7-147ddaaf4f97' of job 'batch-example-policiesBatch_Job'. ``` - The second Batch Step (`batchStep2`) prints the payload of the failed records, for example: ```logs INFO ... LOGGER IN SECOND BATCH STEP: 1 INFO ... LOGGER IN SECOND BATCH STEP: 2 ``` - The third Batch Step (`batchStep3`) prints the payload of the successful records, for example: ```logs INFO ... LOGS IN THIRD BATCH STEP: 3 INFO ...LOGS IN THIRD BATCH STEP: 4 INFO ...LOGS IN THIRD BATCH STEP: 5 ``` - After the batch job instance completes, the logs indicate that `3` records processed successfully and `2` records failed: ```logs INFO ...engine.DefaultBatchEngine: Finished execution for instance ... Total Records processed: 5. Successful records: 3. Failed Records: 2 ``` For more information, see [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/4.9/batch-error-handling-faq). ## Performing Bulk Operations from a Batch Aggregator Component Aggregation is useful for sending multiple records within an array to an external server. Within the Batch Aggregator component, you can add an operation, such as a bulk upsert, insert, or update operation, to load multiple records to a server with a single execution of an operation, instead of running an operation separately on each record. You can process records in separate arrays of a fixed size or stream a single array of records from the batch job instance. For example, you can configure an Upsert operation in the Anypoint Connector for Salesforce (Salesforce Connector) to upsert 200 processed records. Alternatively, you can stream all the records in the instance to the server. The following example bulk upserts records in separate arrays of 200 records per upsert: ```xml ``` The following example streams upserts to a database: ```xml salesforce:upsert doc:name="Upsert" ... /> ``` Error handling: Some connectors handle record-level errors without causing an entire batch aggregation process to fail, for example, [Anypoint Connector for Salesforce (Salesforce Connector)](https://docs.mulesoft.com/salesforce-connector/latest/salesforce-connector-reference#upsert) and [Anypoint Connector for NetSuite (NetSuite Connector)](https://docs.mulesoft.com/netsuite-connector/latest/netsuite-reference#Upsert). At runtime, these connectors keep track of records that the target resource accepts successfully and which fail. Rather than failing the entire group of records, the connector upserts as many records as it can and tracks any failures for notification purposes. To learn more about processing within the Batch Aggregator component and how aggregation differs from processing within the Batch Step component, see [Process Phase](https://docs.mulesoft.com/mule-runtime/4.9/batch-processing-concept#phase_process). ## Modifying Records within a Batch Aggregator You can modify records within the Batch Aggregator component, just as you can modify them with processors in the Batch Step component. The modifications can take place sequentially or through random access to specific records. ### Sequential Processing within a Batch Aggregator The following example performs sequential access to records. Using Groovy within a [Scripting module](https://docs.mulesoft.com/scripting-module/latest/), the example modifies the payload of each record from the [For Each](https://docs.mulesoft.com/mule-runtime/4.9/for-each-scope-concept) component’s iteration and creates a variable for each collected record. ```xml vars['marco'] = 'polo' vars['record'].payload = 'hello' ``` ### Randomly Accessing Records within a Batch Aggregator You can also use the For Each scope when randomly accessing records by their iteration number. For Each exposes a `records` variable, which is an immutable list that it uses to keep track of the iteration. You can use this variable to randomly access records in the list from the Batch Aggregator component. To demonstrate random access when using fixed-size aggregation, the following example specifies the index of a record in the For Each list of records. Instead of sequentially accessing each record, using the `records` variable with an index of a record selects a single record from the list. The example uses the Scripting module to modify the payload of the selected record and create a variable for that record: ```xml records[0].vars['marco'] = 'polo' records[0].vars['record'].payload = 'hello' ``` You can configure a Batch Aggregator component to stream its content. Setting this component to stream the records (`streaming="true"`) enables you to process an array of all the records in the batch job instance without running out of memory, regardless of how many or how large the records are. For example, if you need to write millions of records to a CSV file, you can stream the records with the Batch Aggregator component. ```xml ``` As the following example shows, only sequential access to records is possible when streaming within the Batch Aggregator component. Random access is not supported when streaming because streaming requires access to the entire set of records. This restriction is necessary because Mule cannot guarantee that all records will fit in memory if no fixed size is specified. ```xml vars['marco'] = 'polo' vars['record'].payload = 'foo' ``` To learn more about processing within the Batch Aggregator component and how aggregation differs from processing within the Batch Step component, see [Process Phase](https://docs.mulesoft.com/mule-runtime/4.9/batch-processing-concept#phase_process). NOTE When using a Batch Aggregator component, do not attempt to process Guava data types, such as `ImmutableMap`. Instead, use a Java Map to avoid serialization issues. ## Preserving the MIME types of the Aggregated Records _Introduced in Mule 4.3_ Aggregated records pass into the Batch Aggregator component as an array containing each record’s payload. However, by default, the MIME types associated with those payloads are not preserved. To preserve record’s MIME types, specify the `preserveMimeTypes` attribute in the Batch Aggregator component. Consider the following JSON array: ```json [ { "name": "Tony Stark", "alias": "Iron Man", "status": "DEAD" }, { "name": "Steve Rodgers", "alias": "Captain America", "status": "RETIRED" }, { "name": "Peter Parker", "alias": "SpiderMan", "status": "FUGITIVE" } ] ``` Assume that the [JSON array](#json_array) is the input to the following Batch Job component: ```xml ``` The batch engine splits the input JSON array into individual records, which aggregator block receives an array with three elements. The first one of them is: ```json { "name": "Tony Stark", "alias": "Iron Man", "status": "DEAD" } ``` However, when the Logger component attempts to evaluate the `#[payload.alias]` expression, an error similar to the following one results: ```text ******************************************************************************** Message : "You called the function 'Value Selector' with these arguments: 1: Binary ("ewogICJmaXJzdE5hbWUiOiAiUmFtIiwKICAibGFzdE5hbWUiOiAiUmFtMSIsCiAgImFkZHJlc3Mi...) 2: Name ("alias") But it expects one of these combinations: (Array, Name) (Array, String) (Date, Name) (DateTime, Name) (LocalDateTime, Name) (LocalTime, Name) (Object, Name) (Object, String) (Period, Name) (Time, Name) 5| name: payload.alias, ^^^^^^^^^^^^^ ``` This error occurs because MIME types are not preserved, which prevents Mule from reading it as JSON. To resolve this issue, you must set the `preserveMimeTypes` attribute in the Batch Aggregator component to `true`, for example: ```xml ``` The setting makes Mule maintain each record’s media type and treat the payload as a JSON document. ## Changing the Record Block Size A traditional online processing model typically maps each request to a worker thread. Generally, there is 1:1 relationship between a request and a running thread regardless of the processing type. This relationship holds for synchronous, asynchronous, one-way, and request-response processing types, and when temporarily buffering requests before processing. However, in a batch job, the traditional threading model does not apply because records are first stored in a persistent queue, before the Process phase begins. To improve performance, Mule runtime queues and schedules batch records in blocks of up to 100 records per thread. This behavior reduces the number of I/O requests and improves an operation’s load. Batch jobs use Mule thread pools, so there is no default for the job. Each thread iterates through that block to process each record, and then each block is queued back, and the process continues. Consider having 1 million records to place in a queue for a 3-step batch job. At least three million I/O operations occur as the Mule runtime engine takes and requests each record as they move through the job’s phases. Performance requires having enough available memory to process the threads in parallel, which means moving the records from persistent storage into RAM. The larger your records and their quantity, the more available memory you need for batch processing. Although the standard model of up to 100 records per thread in the batch job works for most use cases, consider three use cases where you need to increase or decrease the block size: - Assume you have 200 records to process through a batch job. With the default 100-record block size, Mule can only process two records in parallel at a time. If a batch job has fewer than 101 records to process, then processing becomes sequential. If you need to process heavy payloads, then queueing a hundred records demands a large amount of working memory. - Consider a batch job that needs to process images, and an average image size of 3 MB. In this case, Mule processes 100-record blocks with payloads of 3 MB in each thread. Hence, your default threading-profile setting would require a large amount of working memory just to keep the blocks in the queue. In this case, set a lower block size to distribute each payload through more jobs and lessen the load on your available memory. - Suppose you have 5 million records with payloads so small that you can fit blocks of 500 records in your memory without problems. Setting a larger block size improves your batch job time without sacrificing working memory load. To take full advantage of this feature, you must understand how the block sizes affect your batch job. Running comparative tests with different values and testing performance helps you find an optimum block size before moving this change into production. Remember that modifying the batch block size is optional. If you apply no changes, the default value is 100 records per block. You set the size through the Batch Job component, for example: ```xml ... ``` ## Setting a Max Concurrency Limit on Batch Job Instances The Max Concurrency (`maxConcurrency`) property limits the number of record blocks to process concurrently. You can configure the `maxConcurrency` property as in the following example: ```xml ... ``` By default, the Batch Job component limits the maximum concurrency to twice the number of available cores. The capacity of the system running the Mule instance also limits concurrency. ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/4.9/batch-processing-concept) - [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/4.9/batch-job-instance-id) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.9/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Configuring Batch Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can set up and configure Mule batch processing components to perform common batch processing use cases and to enhance the performance of batch jobs for cases in which the defaults require adjustment. ## Filtering Records to Process within a Batch Step Component You can apply one or more record filters as attributes to any number of Batch Step components. For example, assume that the first Batch Step component within a given Batch Job component checks for a Salesforce contact in each record and the second updates the contact information in those records. To ensure that the second Batch Step processes only records that succeeded in the first step, you can configure a filter on the second Batch Step. The filter streamlines processing so that Mule focuses on only the relevant data for a given step. To filter records, the Batch Step component supports one `acceptExpression` and one `acceptPolicy`. Both are optional, and no other Mule components accept these filters. If you use both filters on the same component, Mule evaluates the filters in the following order: 1. Accept Policy: [acceptPolicy](#accept_policy) 2. Accept Expression: [acceptExpression](#accept_expression) A Batch Step component that uses an `acceptExpression` attribute applies a DataWeave expression to each record that reaches the component and accepts a record for processing within the component only if the expression evaluates to `true` for that record. If the record evaluates to `false`, the Batch Step component skips the record, and that record becomes available to the next Batch Step component within the Batch Job component if one exists. The example below filters out all records in which the `age` value is less than `21`: ```xml ... ``` A Batch Step component uses an `acceptPolicy` attribute to apply a policy to records processed in a previous Batch Step component. The Batch Step accepts a record for processing within the component only if the policy evaluates to `true` for that record. The default policy is `NO_FAILURES`. Other policies are `ONLY_FAILURES` and `ALL`. For descriptions of these policies, see [Batch Step Component ()](https://docs.mulesoft.com/mule-runtime/latest/batch-reference#ref_batch_step_component). In the following example, the second Batch Step component (`batchStep2`) accepts only those records that failed to process successfully during the preceding step (`batchStep1`). For example, assume processors within `batchStep1` check each record for a Salesforce contact. If the check fails to find a contact, `batchStep2` accepts only those records without contacts, skipping records with contacts. Message processors within `batchStep2` can add a contact to those records. ```xml ... ... ``` For demonstration purposes, the following example uses the Raise Error component (``) to produce failures in the first Batch Step (`batchStep1`). The second Batch Step (`batchStep2`) accepts failed records only (`ONLY_FAILURES`) and logs the payload of those records. The third uses the default `acceptPolicy` to accept `NO_FAILURES`. ```xml ``` - The Set Payload component (``) sends the array `[1,2,3,4,5]` to the Batch Job component. - The Batch Job component (``) sets `maxFailedRecords` to `-1` so that failed records within the first Batch Step component do not stop the batch job instance from processing. - The first Batch Step (`batchStep1`) configures `acceptExpression="#[payload < 3]"` to accept only records with a payload less than `3` and throws an error on those records because of the Raise Error component within it: ```logs INFO ...DefaultBatchStep: Found error processing record on step 'batchStep1' for job instance 'f9bb6d60-5ef2-11ed-81e7-147ddaaf4f97' of job 'batch-example-policiesBatch_Job'. ``` - The second Batch Step (`batchStep2`) prints the payload of the failed records, for example: ```logs INFO ... LOGGER IN SECOND BATCH STEP: 1 INFO ... LOGGER IN SECOND BATCH STEP: 2 ``` - The third Batch Step (`batchStep3`) prints the payload of the successful records, for example: ```logs INFO ... LOGS IN THIRD BATCH STEP: 3 INFO ...LOGS IN THIRD BATCH STEP: 4 INFO ...LOGS IN THIRD BATCH STEP: 5 ``` - After the batch job instance completes, the logs indicate that `3` records processed successfully and `2` records failed: ```logs INFO ...engine.DefaultBatchEngine: Finished execution for instance ... Total Records processed: 5. Successful records: 3. Failed Records: 2 ``` For more information, see [Handling Errors During Batch Job](https://docs.mulesoft.com/mule-runtime/latest/batch-error-handling-faq). ## Performing Bulk Operations from a Batch Aggregator Component Aggregation is useful for sending multiple records within an array to an external server. Within the Batch Aggregator component, you can add an operation, such as a bulk upsert, insert, or update operation, to load multiple records to a server with a single execution of an operation, instead of running an operation separately on each record. You can process records in separate arrays of a fixed size or stream a single array of records from the batch job instance. For example, you can configure an Upsert operation in the Anypoint Connector for Salesforce (Salesforce Connector) to upsert 200 processed records. Alternatively, you can stream all the records in the instance to the server. The following example bulk upserts records in separate arrays of 200 records per upsert: ```xml ``` The following example streams upserts to a database: ```xml salesforce:upsert doc:name="Upsert" ... /> ``` Error handling: Some connectors handle record-level errors without causing an entire batch aggregation process to fail, for example, [Anypoint Connector for Salesforce (Salesforce Connector)](https://docs.mulesoft.com/salesforce-connector/latest/salesforce-connector-reference#upsert) and [Anypoint Connector for NetSuite (NetSuite Connector)](https://docs.mulesoft.com/netsuite-connector/latest/netsuite-reference#Upsert). At runtime, these connectors keep track of records that the target resource accepts successfully and which fail. Rather than failing the entire group of records, the connector upserts as many records as it can and tracks any failures for notification purposes. To learn more about processing within the Batch Aggregator component and how aggregation differs from processing within the Batch Step component, see [Process Phase](https://docs.mulesoft.com/mule-runtime/latest/batch-processing-concept#phase_process). ## Modifying Records within a Batch Aggregator You can modify records within the Batch Aggregator component, just as you can modify them with processors in the Batch Step component. The modifications can take place sequentially or through random access to specific records. ### Sequential Processing within a Batch Aggregator The following example performs sequential access to records. Using Groovy within a [Scripting module](https://docs.mulesoft.com/scripting-module/latest/), the example modifies the payload of each record from the [For Each](https://docs.mulesoft.com/mule-runtime/latest/for-each-scope-concept) component’s iteration and creates a variable for each collected record. ```xml vars['marco'] = 'polo' vars['record'].payload = 'hello' ``` ### Randomly Accessing Records within a Batch Aggregator You can also use the For Each scope when randomly accessing records by their iteration number. For Each exposes a `records` variable, which is an immutable list that it uses to keep track of the iteration. You can use this variable to randomly access records in the list from the Batch Aggregator component. To demonstrate random access when using fixed-size aggregation, the following example specifies the index of a record in the For Each list of records. Instead of sequentially accessing each record, using the `records` variable with an index of a record selects a single record from the list. The example uses the Scripting module to modify the payload of the selected record and create a variable for that record: ```xml records[0].vars['marco'] = 'polo' records[0].vars['record'].payload = 'hello' ``` You can configure a Batch Aggregator component to stream its content. Setting this component to stream the records (`streaming="true"`) enables you to process an array of all the records in the batch job instance without running out of memory, regardless of how many or how large the records are. For example, if you need to write millions of records to a CSV file, you can stream the records with the Batch Aggregator component. ```xml ``` As the following example shows, only sequential access to records is possible when streaming within the Batch Aggregator component. Random access is not supported when streaming because streaming requires access to the entire set of records. This restriction is necessary because Mule cannot guarantee that all records will fit in memory if no fixed size is specified. ```xml vars['marco'] = 'polo' vars['record'].payload = 'foo' ``` To learn more about processing within the Batch Aggregator component and how aggregation differs from processing within the Batch Step component, see [Process Phase](https://docs.mulesoft.com/mule-runtime/latest/batch-processing-concept#phase_process). NOTE When using a Batch Aggregator component, do not attempt to process Guava data types, such as `ImmutableMap`. Instead, use a Java Map to avoid serialization issues. ## Preserving the MIME types of the Aggregated Records _Introduced in Mule 4.3_ Aggregated records pass into the Batch Aggregator component as an array containing each record’s payload. However, by default, the MIME types associated with those payloads are not preserved. To preserve record’s MIME types, specify the `preserveMimeTypes` attribute in the Batch Aggregator component. Consider the following JSON array: ```json [ { "name": "Tony Stark", "alias": "Iron Man", "status": "DEAD" }, { "name": "Steve Rodgers", "alias": "Captain America", "status": "RETIRED" }, { "name": "Peter Parker", "alias": "SpiderMan", "status": "FUGITIVE" } ] ``` Assume that the [JSON array](#json_array) is the input to the following Batch Job component: ```xml ``` The batch engine splits the input JSON array into individual records, which aggregator block receives an array with three elements. The first one of them is: ```json { "name": "Tony Stark", "alias": "Iron Man", "status": "DEAD" } ``` However, when the Logger component attempts to evaluate the `#[payload.alias]` expression, an error similar to the following one results: ```text ******************************************************************************** Message : "You called the function 'Value Selector' with these arguments: 1: Binary ("ewogICJmaXJzdE5hbWUiOiAiUmFtIiwKICAibGFzdE5hbWUiOiAiUmFtMSIsCiAgImFkZHJlc3Mi...) 2: Name ("alias") But it expects one of these combinations: (Array, Name) (Array, String) (Date, Name) (DateTime, Name) (LocalDateTime, Name) (LocalTime, Name) (Object, Name) (Object, String) (Period, Name) (Time, Name) 5| name: payload.alias, ^^^^^^^^^^^^^ ``` This error occurs because MIME types are not preserved, which prevents Mule from reading it as JSON. To resolve this issue, you must set the `preserveMimeTypes` attribute in the Batch Aggregator component to `true`, for example: ```xml ``` The setting makes Mule maintain each record’s media type and treat the payload as a JSON document. ## Changing the Record Block Size A traditional online processing model typically maps each request to a worker thread. Generally, there is 1:1 relationship between a request and a running thread regardless of the processing type. This relationship holds for synchronous, asynchronous, one-way, and request-response processing types, and when temporarily buffering requests before processing. However, in a batch job, the traditional threading model does not apply because records are first stored in a persistent queue, before the Process phase begins. To improve performance, Mule runtime queues and schedules batch records in blocks of up to 100 records per thread. This behavior reduces the number of I/O requests and improves an operation’s load. Batch jobs use Mule thread pools, so there is no default for the job. Each thread iterates through that block to process each record, and then each block is queued back, and the process continues. Consider having 1 million records to place in a queue for a 3-step batch job. At least three million I/O operations occur as the Mule runtime engine takes and requests each record as they move through the job’s phases. Performance requires having enough available memory to process the threads in parallel, which means moving the records from persistent storage into RAM. The larger your records and their quantity, the more available memory you need for batch processing. Although the standard model of up to 100 records per thread in the batch job works for most use cases, consider three use cases where you need to increase or decrease the block size: - Assume you have 200 records to process through a batch job. With the default 100-record block size, Mule can only process two records in parallel at a time. If a batch job has fewer than 101 records to process, then processing becomes sequential. If you need to process heavy payloads, then queueing a hundred records demands a large amount of working memory. - Consider a batch job that needs to process images, and an average image size of 3 MB. In this case, Mule processes 100-record blocks with payloads of 3 MB in each thread. Hence, your default threading-profile setting would require a large amount of working memory just to keep the blocks in the queue. In this case, set a lower block size to distribute each payload through more jobs and lessen the load on your available memory. - Suppose you have 5 million records with payloads so small that you can fit blocks of 500 records in your memory without problems. Setting a larger block size improves your batch job time without sacrificing working memory load. To take full advantage of this feature, you must understand how the block sizes affect your batch job. Running comparative tests with different values and testing performance helps you find an optimum block size before moving this change into production. Remember that modifying the batch block size is optional. If you apply no changes, the default value is 100 records per block. You set the size through the Batch Job component, for example: ```xml ... ``` ## Setting a Max Concurrency Limit on Batch Job Instances The Max Concurrency (`maxConcurrency`) property limits the number of record blocks to process concurrently. You can configure the `maxConcurrency` property as in the following example: ```xml ... ``` By default, the Batch Job component limits the maximum concurrency to twice the number of available cores. The capacity of the system running the Mule instance also limits concurrency. ## See Also - [Batch Processing](https://docs.mulesoft.com/mule-runtime/latest/batch-processing-concept) - [Batch Job Instance ID](https://docs.mulesoft.com/mule-runtime/latest/batch-job-instance-id) - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/latest/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.11 keywords: deploy, deploying, cloudhub, on premises, on premise, environment --- # Configuring Environment Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure your Mule application to automatically load property files based on the development environment (QA, preproduction, production, etc) you are working on, making it easier to deploy your app both on-premises and in the cloud. This configuration requires you to complete the following tasks: 1. Create a properties file for each development environment in your application. 2. Configure a properties placeholder in your app to look for the environment upon launch. 3. Set an environment variable to point to a specific development environment during application deployment. Consider externalizing other aspects of your configuration, like time-out values, polling frequencies, and so on, even if these configurations don’t vary between environments. This configuration facilitates tuning and experimenting because the Mule application becomes fully configurable through a single properties file. [Download Example Studio Application](https://docs.mulesoft.com/mule-runtime/4.11/_attachments/multiple-envs-example.jar) ## Considerations when Using Environment Properties Consider the following guidelines when you configure environment properties: - Use a consistent naming strategy for your properties files and make them unique across applications. This practice ensures that files are easy to reuse across teams. A good strategy is to add the application name or application ID to the properties file names. - If you are deploying multiple applications through a [shared resources](https://docs.mulesoft.com/mule-runtime/4.11/shared-resources) structure, do not set anything in the properties files. Doing so can cause conflicts between the various apps that share a domain. Instead, you can set environment variables that span the scope of the deployed app, its domain, and other apps under that domain. In Studio, you can create environment variables using the **Environment** tab of the **Run Configurations** menu. You can access the Environment tab from the drop-down menu to the right of the **Play** button. ## Basic Architecture of an Environment Property Configuration The following Mule configuration fragment defines a global property called `env`, a dynamic configuration properties file (based on the `env` property), and an HTTP connector with variable configuration: ```xml ``` This example uses Spring’s property placeholder resolution mechanism. The variable bits: the **base path**, **host**, and **port** are clearly visible and can vary for each environment where this connector gets deployed in. When deploying your application, you can dynamically replace the `env` property with the particular environment to which you’re deploying, such as `qa` or `prod`. This causes the Mule application to load a different `.yaml` file with properties specific to the configured environment. To provide values for these environment variables, we use a Yaml configuration file for each environment: Properties File: qa.yaml path: "test/products" host: "localhost" port: 8082 Properties File: prod.yaml path: "products" host: "www.acme.com" port: 8081 ## Creating and Configuring Environment Properties Create variable properties files and configure them in your application to look for the environment upon launch. Additionally, you can test environment properties in Studio. To complete these tasks review the following steps: ### Using Studio Visual Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![A Package Explorer showing a project structure with folders for different environments including Production and QA in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![A QA YAML configuration file](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-02.png) ![A Production YAML configuration file](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Global Elements tab of your Studio project, below the canvas. 6. **Create** a new global element. When selecting the element type, pick **Configuration properties** under **Global Configurations**. ![Configuration panel for choosing a global element type including Configuration Properties under Global Configurations in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-04.png) 7. Set the value of the **File** field to `${env}.yaml` 8. **Create** a new property to add a default environment. When selecting the element type, pick **Global Property** under **Global Configurations**. ![Configuration panel for choosing a global element type including Global Property under Global Configurations in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-05.png) 9. Set a value to the property. ![A settings dialog with environment variable for QA in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-06.png) 10. You can change the environment by editing the configured **Global Property** value. ### Using XML Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![A Package Explorer showing a project structure with folders for different environments including Production and QA in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![A QA YAML configuration file](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-02.png) ![A Production YAML configuration file](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Configuration XML tab of your Studio application, below the canvas. 6. Add a **configuration-properties** element to the XML file and let the file name configurable. ```xml ``` 7. Add a **Global Property** element to set the default environment name. ```xml ``` 8. You can change the environment by editing the configured **Global Property** value. ### Testing Configured Environment Properties in Studio You can test that your application uses the specific environment you configured in your variables properties file, by running the application in Mule embedded in Studio. 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Mule Application**. 2. Studio automatically deploys your application according to the environment variable you specified in the **Global Property** from the previous procedure. 3. Again in the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Run Configurations…​**. ![A Package Explorer view showing how to run configurations in a project structure](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-07.png) 4. Define the System Property in the `Arguments` tab. ![A Run Configurations panel](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-08.png) 5. Click the `Run` button to complete the procedure. The properties configured in `prod.yaml` will be used instead of the ones defined in `qa.yaml`. ## Setting Environment Variables for Application Deployment Mule loads the environment variables when it starts, so depending on your deployment target (CloudHub or On-premises) you need to set the environment when you deploy the app (CloudHub) or when you start your Mule instance (On-premises). ### Setting a Specific Environment when Starting Mule On-Premises #### Using the command line Identify the environment in which to deploy your application at runtime with an environment variable. Execute the command to run Mule in your environment as per the following example: ```console $ mule -M-Denv=prod ``` Once Mule starts with your configured environment, you can deploy the application with your desired deployment method. #### Using Anypoint Runtime Manager As a prerequisite you need to [create a server in Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/servers-create) and link it to Mule. Then you can [create a custom server property](https://docs.mulesoft.com/runtime-manager/servers-properties-create). ### Setting a Specific Environment when Deploying to CloudHub #### Deploying to CloudHub from Studio From Studio you can initiate the process to set your properties environment variables and deploy your application to CloudHub : 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Anypoint Platform** → **Deploy to Cloud**. ![A Package Explorer view showing how to deploy applications to CloudHub](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-09.png) 2. Complete the requested data, and click the **Properties** tab. 3. Add a new environment variable by setting **Key** to **env** and its value to **prod**. ![CloudHub deployment settings for an application with environment-specific properties](/mulesoft/current/en-us/mule-runtime/4.11/_images/deploying-to-multiple-environments-10.png) 4. Click **Deploy Application**. #### Deploying to CloudHub from Runtime Manager To deploy your application to CloudHub via Anypoint Runtime Manager, you can [set properties values](https://docs.mulesoft.com/mule-runtime/4.11/configuring-properties#setting-properties-values-in-runtime-manager.adoc) using Runtime Manager Console. ## See Also - [Configuring Variable Properties](https://docs.mulesoft.com/mule-runtime/4.11/configuring-properties) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.11/shared-resources) --- product: Mule Runtime version: 4.12 keywords: deploy, deploying, cloudhub, on premises, on premise, environment --- # Configuring Environment Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure your Mule application to automatically load property files based on the development environment (QA, preproduction, production, etc) you are working on, making it easier to deploy your app both on-premises and in the cloud. This configuration requires you to complete the following tasks: 1. Create a properties file for each development environment in your application. 2. Configure a properties placeholder in your app to look for the environment upon launch. 3. Set an environment variable to point to a specific development environment during application deployment. Consider externalizing other aspects of your configuration, like time-out values, polling frequencies, and so on, even if these configurations don’t vary between environments. This configuration facilitates tuning and experimenting because the Mule application becomes fully configurable through a single properties file. [Download Example Studio Application](https://docs.mulesoft.com/mule-runtime/4.12/_attachments/multiple-envs-example.jar) ## Considerations when Using Environment Properties Consider the following guidelines when you configure environment properties: - Use a consistent naming strategy for your properties files and make them unique across applications. This practice ensures that files are easy to reuse across teams. A good strategy is to add the application name or application ID to the properties file names. - If you are deploying multiple applications through a [shared resources](https://docs.mulesoft.com/mule-runtime/4.12/shared-resources) structure, do not set anything in the properties files. Doing so can cause conflicts between the various apps that share a domain. Instead, you can set environment variables that span the scope of the deployed app, its domain, and other apps under that domain. In Studio, you can create environment variables using the **Environment** tab of the **Run Configurations** menu. You can access the Environment tab from the drop-down menu to the right of the **Play** button. ## Basic Architecture of an Environment Property Configuration The following Mule configuration fragment defines a global property called `env`, a dynamic configuration properties file (based on the `env` property), and an HTTP connector with variable configuration: ```xml ``` This example uses Spring’s property placeholder resolution mechanism. The variable bits: the **base path**, **host**, and **port** are clearly visible and can vary for each environment where this connector gets deployed in. When deploying your application, you can dynamically replace the `env` property with the particular environment to which you’re deploying, such as `qa` or `prod`. This causes the Mule application to load a different `.yaml` file with properties specific to the configured environment. To provide values for these environment variables, we use a Yaml configuration file for each environment: Properties File: qa.yaml path: "test/products" host: "localhost" port: 8082 Properties File: prod.yaml path: "products" host: "www.acme.com" port: 8081 ## Creating and Configuring Environment Properties Create variable properties files and configure them in your application to look for the environment upon launch. Additionally, you can test environment properties in Studio. To complete these tasks review the following steps: ### Using Studio Visual Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![A Package Explorer showing a project structure with folders for different environments including Production and QA in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![A QA YAML configuration file](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-02.png) ![A Production YAML configuration file](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Global Elements tab of your Studio project, below the canvas. 6. **Create** a new global element. When selecting the element type, pick **Configuration properties** under **Global Configurations**. ![Configuration panel for choosing a global element type including Configuration Properties under Global Configurations in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-04.png) 7. Set the value of the **File** field to `${env}.yaml` 8. **Create** a new property to add a default environment. When selecting the element type, pick **Global Property** under **Global Configurations**. ![Configuration panel for choosing a global element type including Global Property under Global Configurations in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-05.png) 9. Set a value to the property. ![A settings dialog with environment variable for QA in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-06.png) 10. You can change the environment by editing the configured **Global Property** value. ### Using XML Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![A Package Explorer showing a project structure with folders for different environments including Production and QA in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![A QA YAML configuration file](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-02.png) ![A Production YAML configuration file](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Configuration XML tab of your Studio application, below the canvas. 6. Add a **configuration-properties** element to the XML file and let the file name configurable. ```xml ``` 7. Add a **Global Property** element to set the default environment name. ```xml ``` 8. You can change the environment by editing the configured **Global Property** value. ### Testing Configured Environment Properties in Studio You can test that your application uses the specific environment you configured in your variables properties file, by running the application in Mule embedded in Studio. 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Mule Application**. 2. Studio automatically deploys your application according to the environment variable you specified in the **Global Property** from the previous procedure. 3. Again in the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Run Configurations…​**. ![A Package Explorer view showing how to run configurations in a project structure](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-07.png) 4. Define the System Property in the `Arguments` tab. ![A Run Configurations panel](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-08.png) 5. Click the `Run` button to complete the procedure. The properties configured in `prod.yaml` will be used instead of the ones defined in `qa.yaml`. ## Setting Environment Variables for Application Deployment Mule loads the environment variables when it starts, so depending on your deployment target (CloudHub or On-premises) you need to set the environment when you deploy the app (CloudHub) or when you start your Mule instance (On-premises). ### Setting a Specific Environment when Starting Mule On-Premises #### Using the command line Identify the environment in which to deploy your application at runtime with an environment variable. Execute the command to run Mule in your environment as per the following example: ```console $ mule -M-Denv=prod ``` Once Mule starts with your configured environment, you can deploy the application with your desired deployment method. #### Using Anypoint Runtime Manager As a prerequisite you need to [create a server in Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/servers-create) and link it to Mule. Then you can [create a custom server property](https://docs.mulesoft.com/runtime-manager/servers-properties-create). ### Setting a Specific Environment when Deploying to CloudHub #### Deploying to CloudHub from Studio From Studio you can initiate the process to set your properties environment variables and deploy your application to CloudHub : 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Anypoint Platform** → **Deploy to Cloud**. ![A Package Explorer view showing how to deploy applications to CloudHub](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-09.png) 2. Complete the requested data, and click the **Properties** tab. 3. Add a new environment variable by setting **Key** to **env** and its value to **prod**. ![CloudHub deployment settings for an application with environment-specific properties](/mulesoft/current/en-us/mule-runtime/4.12/_images/deploying-to-multiple-environments-10.png) 4. Click **Deploy Application**. #### Deploying to CloudHub from Runtime Manager To deploy your application to CloudHub via Anypoint Runtime Manager, you can [set properties values](https://docs.mulesoft.com/mule-runtime/4.12/configuring-properties#setting-properties-values-in-runtime-manager.adoc) using Runtime Manager Console. ## See Also - [Configuring Variable Properties](https://docs.mulesoft.com/mule-runtime/4.12/configuring-properties) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.12/shared-resources) --- product: Mule Runtime version: 4.3 keywords: deploy, deploying, cloudhub, on premises, on premise, environment --- # Configuring Environment Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure your Mule application to automatically load property files based on the development environment (QA, preproduction, production, etc) you are working on, making it easier to deploy your app both on-premises and in the cloud. This configuration requires you to complete the following tasks: 1. Create a properties file for each development environment in your application. 2. Configure a properties placeholder in your app to look for the environment upon launch. 3. Set an environment variable to point to a specific development environment during application deployment. Consider externalizing other aspects of your configuration, like time-out values, polling frequencies, and so on, even if these configurations don’t vary between environments. This configuration facilitates tuning and experimenting because the Mule application becomes fully configurable through a single properties file. [Download Example Studio Application](https://docs.mulesoft.com/mule-runtime/4.3/_attachments/multiple-envs-example.jar) ## Considerations when Using Environment Properties Consider the following guidelines when you configure environment properties: - Use a consistent naming strategy for your properties files and make them unique across applications. This practice ensures that files are easy to reuse across teams. A good strategy is to add the application name or application ID to the properties file names. - If you are deploying multiple applications through a [shared resources](https://docs.mulesoft.com/mule-runtime/4.3/shared-resources) structure, do not set anything in the properties files. Doing so can cause conflicts between the various apps that share a domain. Instead, you can set environment variables that span the scope of the deployed app, its domain, and other apps under that domain. In Studio, you can create environment variables using the **Environment** tab of the **Run Configurations** menu. You can access the Environment tab from the drop-down menu to the right of the **Play** button. ## Basic Architecture of an Environment Property Configuration The following Mule configuration fragment defines a global property called `env`, a dynamic configuration properties file (based on the `env` property), and an HTTP connector with variable configuration: ```xml ``` This example uses Spring’s property placeholder resolution mechanism. The variable bits: the **base path**, **host**, and **port** are clearly visible and can vary for each environment where this connector gets deployed in. When deploying your application, you can dynamically replace the `env` property with the particular environment to which you’re deploying, such as `qa` or `prod`. This causes the Mule application to load a different `.yaml` file with properties specific to the configured environment. To provide values for these environment variables, we use a Yaml configuration file for each environment: Properties File: qa.yaml path: "test/products" host: "localhost" port: 8082 Properties File: prod.yaml path: "products" host: "www.acme.com" port: 8081 ## Creating and Configuring Environment Properties Create variable properties files and configure them in your application to look for the environment upon launch. Additionally, you can test environment properties in Studio. To complete these tasks review the following steps: ### Using Studio Visual Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![deploying to multiple environments 01](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![deploying to multiple environments 02](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-02.png) ![deploying to multiple environments 03](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Global Elements tab of your Studio project, below the canvas. 6. **Create** a new global element. When selecting the element type, pick **Configuration properties** under **Global Configurations**. ![deploying to multiple environments 04](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-04.png) 7. Set the value of the **File** field to `${env}.yaml` 8. **Create** a new property to add a default environment. When selecting the element type, pick **Global Property** under **Global Configurations**. ![deploying to multiple environments 05](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-05.png) 9. Set a value to the property. ![deploying to multiple environments 06](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-06.png) 10. You can change the environment by editing the configured **Global Property** value. ### Using XML Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![deploying to multiple environments 01](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![deploying to multiple environments 02](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-02.png) ![deploying to multiple environments 03](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Configuration XML tab of your Studio application, below the canvas. 6. Add a **configuration-properties** element to the XML file and let the file name configurable. ```xml ``` 7. Add a **Global Property** element to set the default environment name. ```xml ``` 8. You can change the environment by editing the configured **Global Property** value. ### Testing Configured Environment Properties in Studio You can test that your application uses the specific environment you configured in your variables properties file, by running the application in Mule embedded in Studio. 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Mule Application**. 2. Studio automatically deploys your application according to the environment variable you specified in the **Global Property** from the previous procedure. 3. Again in the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Run Configurations…​**. ![deploying to multiple environments 07](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-07.png) 4. Define the System Property in the `Arguments` tab. ![deploying to multiple environments 08](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-08.png) 5. Click the `Run` button to complete the procedure. The properties configured in `prod.yaml` will be used instead of the ones defined in `qa.yaml`. ## Setting Environment Variables for Application Deployment Mule loads the environment variables when it starts, so depending on your deployment target (CloudHub or On-premises) you need to set the environment when you deploy the app (CloudHub) or when you start your Mule instance (On-premises). ### Setting a Specific Environment when Starting Mule On-Premises #### Using the command line Identify the environment in which to deploy your application at runtime with an environment variable. Execute the command to run Mule in your environment as per the following example: ```console $ mule -M-Denv=prod ``` Once Mule starts with your configured environment, you can deploy the application with your desired deployment method. #### Using Anypoint Runtime Manager As a prerequisite you need to [create a server in Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/servers-create) and link it to Mule. Then you can [create a custom server property](https://docs.mulesoft.com/runtime-manager/servers-properties-create). ### Setting a Specific Environment when Deploying to CloudHub #### Deploying to CloudHub from Studio From Studio you can initiate the process to set your properties environment variables and deploy your application to CloudHub : 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Anypoint Platform** → **Deploy to Cloud**. ![deploying to multiple environments 09](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-09.png) 2. Complete the requested data, and click the **Properties** tab. 3. Add a new environment variable by setting **Key** to **env** and its value to **prod**. ![deploying to multiple environments 10](/mulesoft/current/en-us/mule-runtime/4.3/_images/deploying-to-multiple-environments-10.png) 4. Click **Deploy Application**. #### Deploying to CloudHub from Runtime Manager To deploy your application to CloudHub via Anypoint Runtime Manager, you can [set properties values](https://docs.mulesoft.com/mule-runtime/4.3/configuring-properties#setting-properties-values-in-runtime-manager.adoc) using Runtime Manager Console. ## See Also - [Configuring Variable Properties](https://docs.mulesoft.com/mule-runtime/4.3/configuring-properties) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.3/shared-resources) --- product: Mule Runtime version: 4.4 keywords: deploy, deploying, cloudhub, on premises, on premise, environment --- # Configuring Environment Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure your Mule application to automatically load property files based on the development environment (QA, preproduction, production, etc) you are working on, making it easier to deploy your app both on-premises and in the cloud. This configuration requires you to complete the following tasks: 1. Create a properties file for each development environment in your application. 2. Configure a properties placeholder in your app to look for the environment upon launch. 3. Set an environment variable to point to a specific development environment during application deployment. Consider externalizing other aspects of your configuration, like time-out values, polling frequencies, and so on, even if these configurations don’t vary between environments. This configuration facilitates tuning and experimenting because the Mule application becomes fully configurable through a single properties file. [Download Example Studio Application](https://docs.mulesoft.com/mule-runtime/4.4/_attachments/multiple-envs-example.jar) ## Considerations when Using Environment Properties Consider the following guidelines when you configure environment properties: - Use a consistent naming strategy for your properties files and make them unique across applications. This practice ensures that files are easy to reuse across teams. A good strategy is to add the application name or application ID to the properties file names. - If you are deploying multiple applications through a [shared resources](https://docs.mulesoft.com/mule-runtime/4.4/shared-resources) structure, do not set anything in the properties files. Doing so can cause conflicts between the various apps that share a domain. Instead, you can set environment variables that span the scope of the deployed app, its domain, and other apps under that domain. In Studio, you can create environment variables using the **Environment** tab of the **Run Configurations** menu. You can access the Environment tab from the drop-down menu to the right of the **Play** button. ## Basic Architecture of an Environment Property Configuration The following Mule configuration fragment defines a global property called `env`, a dynamic configuration properties file (based on the `env` property), and an HTTP connector with variable configuration: ```xml ``` This example uses Spring’s property placeholder resolution mechanism. The variable bits: the **base path**, **host**, and **port** are clearly visible and can vary for each environment where this connector gets deployed in. When deploying your application, you can dynamically replace the `env` property with the particular environment to which you’re deploying, such as `qa` or `prod`. This causes the Mule application to load a different `.yaml` file with properties specific to the configured environment. To provide values for these environment variables, we use a Yaml configuration file for each environment: Properties File: qa.yaml path: "test/products" host: "localhost" port: 8082 Properties File: prod.yaml path: "products" host: "www.acme.com" port: 8081 ## Creating and Configuring Environment Properties Create variable properties files and configure them in your application to look for the environment upon launch. Additionally, you can test environment properties in Studio. To complete these tasks review the following steps: ### Using Studio Visual Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![deploying to multiple environments 01](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![deploying to multiple environments 02](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-02.png) ![deploying to multiple environments 03](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Global Elements tab of your Studio project, below the canvas. 6. **Create** a new global element. When selecting the element type, pick **Configuration properties** under **Global Configurations**. ![deploying to multiple environments 04](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-04.png) 7. Set the value of the **File** field to `${env}.yaml` 8. **Create** a new property to add a default environment. When selecting the element type, pick **Global Property** under **Global Configurations**. ![deploying to multiple environments 05](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-05.png) 9. Set a value to the property. ![deploying to multiple environments 06](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-06.png) 10. You can change the environment by editing the configured **Global Property** value. ### Using XML Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![deploying to multiple environments 01](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![deploying to multiple environments 02](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-02.png) ![deploying to multiple environments 03](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Configuration XML tab of your Studio application, below the canvas. 6. Add a **configuration-properties** element to the XML file and let the file name configurable. ```xml ``` 7. Add a **Global Property** element to set the default environment name. ```xml ``` 8. You can change the environment by editing the configured **Global Property** value. ### Testing Configured Environment Properties in Studio You can test that your application uses the specific environment you configured in your variables properties file, by running the application in Mule embedded in Studio. 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Mule Application**. 2. Studio automatically deploys your application according to the environment variable you specified in the **Global Property** from the previous procedure. 3. Again in the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Run Configurations…​**. ![deploying to multiple environments 07](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-07.png) 4. Define the System Property in the `Arguments` tab. ![deploying to multiple environments 08](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-08.png) 5. Click the `Run` button to complete the procedure. The properties configured in `prod.yaml` will be used instead of the ones defined in `qa.yaml`. ## Setting Environment Variables for Application Deployment Mule loads the environment variables when it starts, so depending on your deployment target (CloudHub or On-premises) you need to set the environment when you deploy the app (CloudHub) or when you start your Mule instance (On-premises). ### Setting a Specific Environment when Starting Mule On-Premises #### Using the command line Identify the environment in which to deploy your application at runtime with an environment variable. Execute the command to run Mule in your environment as per the following example: ```console $ mule -M-Denv=prod ``` Once Mule starts with your configured environment, you can deploy the application with your desired deployment method. #### Using Anypoint Runtime Manager As a prerequisite you need to [create a server in Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/servers-create) and link it to Mule. Then you can [create a custom server property](https://docs.mulesoft.com/runtime-manager/servers-properties-create). ### Setting a Specific Environment when Deploying to CloudHub #### Deploying to CloudHub from Studio From Studio you can initiate the process to set your properties environment variables and deploy your application to CloudHub : 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Anypoint Platform** → **Deploy to Cloud**. ![deploying to multiple environments 09](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-09.png) 2. Complete the requested data, and click the **Properties** tab. 3. Add a new environment variable by setting **Key** to **env** and its value to **prod**. ![deploying to multiple environments 10](/mulesoft/current/en-us/mule-runtime/4.4/_images/deploying-to-multiple-environments-10.png) 4. Click **Deploy Application**. #### Deploying to CloudHub from Runtime Manager To deploy your application to CloudHub via Anypoint Runtime Manager, you can [set properties values](https://docs.mulesoft.com/mule-runtime/4.4/configuring-properties#setting-properties-values-in-runtime-manager.adoc) using Runtime Manager Console. ## See Also - [Configuring Variable Properties](https://docs.mulesoft.com/mule-runtime/4.4/configuring-properties) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.4/shared-resources) --- product: Mule Runtime version: 4.6 keywords: deploy, deploying, cloudhub, on premises, on premise, environment --- # Configuring Environment Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure your Mule application to automatically load property files based on the development environment (QA, preproduction, production, etc) you are working on, making it easier to deploy your app both on-premises and in the cloud. This configuration requires you to complete the following tasks: 1. Create a properties file for each development environment in your application. 2. Configure a properties placeholder in your app to look for the environment upon launch. 3. Set an environment variable to point to a specific development environment during application deployment. Consider externalizing other aspects of your configuration, like time-out values, polling frequencies, and so on, even if these configurations don’t vary between environments. This configuration facilitates tuning and experimenting because the Mule application becomes fully configurable through a single properties file. [Download Example Studio Application](https://docs.mulesoft.com/mule-runtime/4.6/_attachments/multiple-envs-example.jar) ## Considerations when Using Environment Properties Consider the following guidelines when you configure environment properties: - Use a consistent naming strategy for your properties files and make them unique across applications. This practice ensures that files are easy to reuse across teams. A good strategy is to add the application name or application ID to the properties file names. - If you are deploying multiple applications through a [shared resources](https://docs.mulesoft.com/mule-runtime/4.6/shared-resources) structure, do not set anything in the properties files. Doing so can cause conflicts between the various apps that share a domain. Instead, you can set environment variables that span the scope of the deployed app, its domain, and other apps under that domain. In Studio, you can create environment variables using the **Environment** tab of the **Run Configurations** menu. You can access the Environment tab from the drop-down menu to the right of the **Play** button. ## Basic Architecture of an Environment Property Configuration The following Mule configuration fragment defines a global property called `env`, a dynamic configuration properties file (based on the `env` property), and an HTTP connector with variable configuration: ```xml ``` This example uses Spring’s property placeholder resolution mechanism. The variable bits: the **base path**, **host**, and **port** are clearly visible and can vary for each environment where this connector gets deployed in. When deploying your application, you can dynamically replace the `env` property with the particular environment to which you’re deploying, such as `qa` or `prod`. This causes the Mule application to load a different `.yaml` file with properties specific to the configured environment. To provide values for these environment variables, we use a Yaml configuration file for each environment: Properties File: qa.yaml path: "test/products" host: "localhost" port: 8082 Properties File: prod.yaml path: "products" host: "www.acme.com" port: 8081 ## Creating and Configuring Environment Properties Create variable properties files and configure them in your application to look for the environment upon launch. Additionally, you can test environment properties in Studio. To complete these tasks review the following steps: ### Using Studio Visual Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![deploying to multiple environments 01](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![deploying to multiple environments 02](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-02.png) ![deploying to multiple environments 03](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Global Elements tab of your Studio project, below the canvas. 6. **Create** a new global element. When selecting the element type, pick **Configuration properties** under **Global Configurations**. ![deploying to multiple environments 04](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-04.png) 7. Set the value of the **File** field to `${env}.yaml` 8. **Create** a new property to add a default environment. When selecting the element type, pick **Global Property** under **Global Configurations**. ![deploying to multiple environments 05](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-05.png) 9. Set a value to the property. ![deploying to multiple environments 06](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-06.png) 10. You can change the environment by editing the configured **Global Property** value. ### Using XML Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![deploying to multiple environments 01](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![deploying to multiple environments 02](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-02.png) ![deploying to multiple environments 03](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Configuration XML tab of your Studio application, below the canvas. 6. Add a **configuration-properties** element to the XML file and let the file name configurable. ```xml ``` 7. Add a **Global Property** element to set the default environment name. ```xml ``` 8. You can change the environment by editing the configured **Global Property** value. ### Testing Configured Environment Properties in Studio You can test that your application uses the specific environment you configured in your variables properties file, by running the application in Mule embedded in Studio. 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Mule Application**. 2. Studio automatically deploys your application according to the environment variable you specified in the **Global Property** from the previous procedure. 3. Again in the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Run Configurations…​**. ![deploying to multiple environments 07](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-07.png) 4. Define the System Property in the `Arguments` tab. ![deploying to multiple environments 08](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-08.png) 5. Click the `Run` button to complete the procedure. The properties configured in `prod.yaml` will be used instead of the ones defined in `qa.yaml`. ## Setting Environment Variables for Application Deployment Mule loads the environment variables when it starts, so depending on your deployment target (CloudHub or On-premises) you need to set the environment when you deploy the app (CloudHub) or when you start your Mule instance (On-premises). ### Setting a Specific Environment when Starting Mule On-Premises #### Using the command line Identify the environment in which to deploy your application at runtime with an environment variable. Execute the command to run Mule in your environment as per the following example: ```console $ mule -M-Denv=prod ``` Once Mule starts with your configured environment, you can deploy the application with your desired deployment method. #### Using Anypoint Runtime Manager As a prerequisite you need to [create a server in Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/servers-create) and link it to Mule. Then you can [create a custom server property](https://docs.mulesoft.com/runtime-manager/servers-properties-create). ### Setting a Specific Environment when Deploying to CloudHub #### Deploying to CloudHub from Studio From Studio you can initiate the process to set your properties environment variables and deploy your application to CloudHub : 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Anypoint Platform** → **Deploy to Cloud**. ![deploying to multiple environments 09](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-09.png) 2. Complete the requested data, and click the **Properties** tab. 3. Add a new environment variable by setting **Key** to **env** and its value to **prod**. ![deploying to multiple environments 10](/mulesoft/current/en-us/mule-runtime/4.6/_images/deploying-to-multiple-environments-10.png) 4. Click **Deploy Application**. #### Deploying to CloudHub from Runtime Manager To deploy your application to CloudHub via Anypoint Runtime Manager, you can [set properties values](https://docs.mulesoft.com/mule-runtime/4.6/configuring-properties#setting-properties-values-in-runtime-manager.adoc) using Runtime Manager Console. ## See Also - [Configuring Variable Properties](https://docs.mulesoft.com/mule-runtime/4.6/configuring-properties) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.6/shared-resources) --- product: Mule Runtime version: 4.9 keywords: deploy, deploying, cloudhub, on premises, on premise, environment --- # Configuring Environment Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure your Mule application to automatically load property files based on the development environment (QA, preproduction, production, etc) you are working on, making it easier to deploy your app both on-premises and in the cloud. This configuration requires you to complete the following tasks: 1. Create a properties file for each development environment in your application. 2. Configure a properties placeholder in your app to look for the environment upon launch. 3. Set an environment variable to point to a specific development environment during application deployment. Consider externalizing other aspects of your configuration, like time-out values, polling frequencies, and so on, even if these configurations don’t vary between environments. This configuration facilitates tuning and experimenting because the Mule application becomes fully configurable through a single properties file. [Download Example Studio Application](https://docs.mulesoft.com/mule-runtime/4.9/_attachments/multiple-envs-example.jar) ## Considerations when Using Environment Properties Consider the following guidelines when you configure environment properties: - Use a consistent naming strategy for your properties files and make them unique across applications. This practice ensures that files are easy to reuse across teams. A good strategy is to add the application name or application ID to the properties file names. - If you are deploying multiple applications through a [shared resources](https://docs.mulesoft.com/mule-runtime/4.9/shared-resources) structure, do not set anything in the properties files. Doing so can cause conflicts between the various apps that share a domain. Instead, you can set environment variables that span the scope of the deployed app, its domain, and other apps under that domain. In Studio, you can create environment variables using the **Environment** tab of the **Run Configurations** menu. You can access the Environment tab from the drop-down menu to the right of the **Play** button. ## Basic Architecture of an Environment Property Configuration The following Mule configuration fragment defines a global property called `env`, a dynamic configuration properties file (based on the `env` property), and an HTTP connector with variable configuration: ```xml ``` This example uses Spring’s property placeholder resolution mechanism. The variable bits: the **base path**, **host**, and **port** are clearly visible and can vary for each environment where this connector gets deployed in. When deploying your application, you can dynamically replace the `env` property with the particular environment to which you’re deploying, such as `qa` or `prod`. This causes the Mule application to load a different `.yaml` file with properties specific to the configured environment. To provide values for these environment variables, we use a Yaml configuration file for each environment: Properties File: qa.yaml path: "test/products" host: "localhost" port: 8082 Properties File: prod.yaml path: "products" host: "www.acme.com" port: 8081 ## Creating and Configuring Environment Properties Create variable properties files and configure them in your application to look for the environment upon launch. Additionally, you can test environment properties in Studio. To complete these tasks review the following steps: ### Using Studio Visual Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![A Package Explorer showing a project structure with folders for different environments including Production and QA in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![A QA YAML configuration file](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-02.png) ![A Production YAML configuration file](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Global Elements tab of your Studio project, below the canvas. 6. **Create** a new global element. When selecting the element type, pick **Configuration properties** under **Global Configurations**. ![Configuration panel for choosing a global element type including Configuration Properties under Global Configurations in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-04.png) 7. Set the value of the **File** field to `${env}.yaml` 8. **Create** a new property to add a default environment. When selecting the element type, pick **Global Property** under **Global Configurations**. ![Configuration panel for choosing a global element type including Global Property under Global Configurations in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-05.png) 9. Set a value to the property. ![A settings dialog with environment variable for QA in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-06.png) 10. You can change the environment by editing the configured **Global Property** value. ### Using XML Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![A Package Explorer showing a project structure with folders for different environments including Production and QA in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![A QA YAML configuration file](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-02.png) ![A Production YAML configuration file](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Configuration XML tab of your Studio application, below the canvas. 6. Add a **configuration-properties** element to the XML file and let the file name configurable. ```xml ``` 7. Add a **Global Property** element to set the default environment name. ```xml ``` 8. You can change the environment by editing the configured **Global Property** value. ### Testing Configured Environment Properties in Studio You can test that your application uses the specific environment you configured in your variables properties file, by running the application in Mule embedded in Studio. 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Mule Application**. 2. Studio automatically deploys your application according to the environment variable you specified in the **Global Property** from the previous procedure. 3. Again in the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Run Configurations…​**. ![A Package Explorer view showing how to run configurations in a project structure](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-07.png) 4. Define the System Property in the `Arguments` tab. ![A Run Configurations panel](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-08.png) 5. Click the `Run` button to complete the procedure. The properties configured in `prod.yaml` will be used instead of the ones defined in `qa.yaml`. ## Setting Environment Variables for Application Deployment Mule loads the environment variables when it starts, so depending on your deployment target (CloudHub or On-premises) you need to set the environment when you deploy the app (CloudHub) or when you start your Mule instance (On-premises). ### Setting a Specific Environment when Starting Mule On-Premises #### Using the command line Identify the environment in which to deploy your application at runtime with an environment variable. Execute the command to run Mule in your environment as per the following example: ```console $ mule -M-Denv=prod ``` Once Mule starts with your configured environment, you can deploy the application with your desired deployment method. #### Using Anypoint Runtime Manager As a prerequisite you need to [create a server in Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/servers-create) and link it to Mule. Then you can [create a custom server property](https://docs.mulesoft.com/runtime-manager/servers-properties-create). ### Setting a Specific Environment when Deploying to CloudHub #### Deploying to CloudHub from Studio From Studio you can initiate the process to set your properties environment variables and deploy your application to CloudHub : 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Anypoint Platform** → **Deploy to Cloud**. ![A Package Explorer view showing how to deploy applications to CloudHub](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-09.png) 2. Complete the requested data, and click the **Properties** tab. 3. Add a new environment variable by setting **Key** to **env** and its value to **prod**. ![CloudHub deployment settings for an application with environment-specific properties](/mulesoft/current/en-us/mule-runtime/4.9/_images/deploying-to-multiple-environments-10.png) 4. Click **Deploy Application**. #### Deploying to CloudHub from Runtime Manager To deploy your application to CloudHub via Anypoint Runtime Manager, you can [set properties values](https://docs.mulesoft.com/mule-runtime/4.9/configuring-properties#setting-properties-values-in-runtime-manager.adoc) using Runtime Manager Console. ## See Also - [Configuring Variable Properties](https://docs.mulesoft.com/mule-runtime/4.9/configuring-properties) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.9/shared-resources) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: deploy, deploying, cloudhub, on premises, on premise, environment --- # Configuring Environment Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure your Mule application to automatically load property files based on the development environment (QA, preproduction, production, etc) you are working on, making it easier to deploy your app both on-premises and in the cloud. This configuration requires you to complete the following tasks: 1. Create a properties file for each development environment in your application. 2. Configure a properties placeholder in your app to look for the environment upon launch. 3. Set an environment variable to point to a specific development environment during application deployment. Consider externalizing other aspects of your configuration, like time-out values, polling frequencies, and so on, even if these configurations don’t vary between environments. This configuration facilitates tuning and experimenting because the Mule application becomes fully configurable through a single properties file. [Download Example Studio Application](https://docs.mulesoft.com/mule-runtime/latest/_attachments/multiple-envs-example.jar) ## Considerations when Using Environment Properties Consider the following guidelines when you configure environment properties: - Use a consistent naming strategy for your properties files and make them unique across applications. This practice ensures that files are easy to reuse across teams. A good strategy is to add the application name or application ID to the properties file names. - If you are deploying multiple applications through a [shared resources](https://docs.mulesoft.com/mule-runtime/latest/shared-resources) structure, do not set anything in the properties files. Doing so can cause conflicts between the various apps that share a domain. Instead, you can set environment variables that span the scope of the deployed app, its domain, and other apps under that domain. In Studio, you can create environment variables using the **Environment** tab of the **Run Configurations** menu. You can access the Environment tab from the drop-down menu to the right of the **Play** button. ## Basic Architecture of an Environment Property Configuration The following Mule configuration fragment defines a global property called `env`, a dynamic configuration properties file (based on the `env` property), and an HTTP connector with variable configuration: ```xml ``` This example uses Spring’s property placeholder resolution mechanism. The variable bits: the **base path**, **host**, and **port** are clearly visible and can vary for each environment where this connector gets deployed in. When deploying your application, you can dynamically replace the `env` property with the particular environment to which you’re deploying, such as `qa` or `prod`. This causes the Mule application to load a different `.yaml` file with properties specific to the configured environment. To provide values for these environment variables, we use a Yaml configuration file for each environment: Properties File: qa.yaml path: "test/products" host: "localhost" port: 8082 Properties File: prod.yaml path: "products" host: "www.acme.com" port: 8081 ## Creating and Configuring Environment Properties Create variable properties files and configure them in your application to look for the environment upon launch. Additionally, you can test environment properties in Studio. To complete these tasks review the following steps: ### Using Studio Visual Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![A Package Explorer showing a project structure with folders for different environments including Production and QA in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![A QA YAML configuration file](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-02.png) ![A Production YAML configuration file](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Global Elements tab of your Studio project, below the canvas. 6. **Create** a new global element. When selecting the element type, pick **Configuration properties** under **Global Configurations**. ![Configuration panel for choosing a global element type including Configuration Properties under Global Configurations in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-04.png) 7. Set the value of the **File** field to `${env}.yaml` 8. **Create** a new property to add a default environment. When selecting the element type, pick **Global Property** under **Global Configurations**. ![Configuration panel for choosing a global element type including Global Property under Global Configurations in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-05.png) 9. Set a value to the property. ![A settings dialog with environment variable for QA in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-06.png) 10. You can change the environment by editing the configured **Global Property** value. ### Using XML Editor 1. Define a list of environments you wish to support in your application. For example, one common use case involves configuring the application to support both Production and a QA environments. We will define the variable `variable` in the environments `prod` and `qa` and test it using a single application. 2. Right-click the `src/main/resources` folder, then select **New** > **File** to create a properties file for each environment you wish to support. For example: - `qa.yaml` - `prod.yaml` ![A Package Explorer showing a project structure with folders for different environments including Production and QA in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-01.png) 3. Double-click each of these new files to open them in new tabs in Studio. By editing them, you can configure the properties of the environment that correspond to the filename. For example, you may wish to add the properties as per the following images. Keep in mind that you can use these properties anywhere in your application. ![A QA YAML configuration file](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-02.png) ![A Production YAML configuration file](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-03.png) 4. Close the properties files. 5. Click in the Configuration XML tab of your Studio application, below the canvas. 6. Add a **configuration-properties** element to the XML file and let the file name configurable. ```xml ``` 7. Add a **Global Property** element to set the default environment name. ```xml ``` 8. You can change the environment by editing the configured **Global Property** value. ### Testing Configured Environment Properties in Studio You can test that your application uses the specific environment you configured in your variables properties file, by running the application in Mule embedded in Studio. 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Mule Application**. 2. Studio automatically deploys your application according to the environment variable you specified in the **Global Property** from the previous procedure. 3. Again in the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Run As** > **Run Configurations…​**. ![A Package Explorer view showing how to run configurations in a project structure](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-07.png) 4. Define the System Property in the `Arguments` tab. ![A Run Configurations panel](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-08.png) 5. Click the `Run` button to complete the procedure. The properties configured in `prod.yaml` will be used instead of the ones defined in `qa.yaml`. ## Setting Environment Variables for Application Deployment Mule loads the environment variables when it starts, so depending on your deployment target (CloudHub or On-premises) you need to set the environment when you deploy the app (CloudHub) or when you start your Mule instance (On-premises). ### Setting a Specific Environment when Starting Mule On-Premises #### Using the command line Identify the environment in which to deploy your application at runtime with an environment variable. Execute the command to run Mule in your environment as per the following example: ```console $ mule -M-Denv=prod ``` Once Mule starts with your configured environment, you can deploy the application with your desired deployment method. #### Using Anypoint Runtime Manager As a prerequisite you need to [create a server in Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/servers-create) and link it to Mule. Then you can [create a custom server property](https://docs.mulesoft.com/runtime-manager/servers-properties-create). ### Setting a Specific Environment when Deploying to CloudHub #### Deploying to CloudHub from Studio From Studio you can initiate the process to set your properties environment variables and deploy your application to CloudHub : 1. In the Package Explorer view, right-click the filename of the project you wish to deploy, then select **Anypoint Platform** → **Deploy to Cloud**. ![A Package Explorer view showing how to deploy applications to CloudHub](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-09.png) 2. Complete the requested data, and click the **Properties** tab. 3. Add a new environment variable by setting **Key** to **env** and its value to **prod**. ![CloudHub deployment settings for an application with environment-specific properties](/mulesoft/current/en-us/mule-runtime/latest/_images/deploying-to-multiple-environments-10.png) 4. Click **Deploy Application**. #### Deploying to CloudHub from Runtime Manager To deploy your application to CloudHub via Anypoint Runtime Manager, you can [set properties values](https://docs.mulesoft.com/mule-runtime/latest/configuring-properties#setting-properties-values-in-runtime-manager.adoc) using Runtime Manager Console. ## See Also - [Configuring Variable Properties](https://docs.mulesoft.com/mule-runtime/latest/configuring-properties) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/latest/shared-resources) --- product: Mule Runtime version: 4.11 keywords: mule, studio, logger, logs, log, notifications, errors, debug --- # Configuring Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides application logs and a runtime log to help you monitor and troubleshoot your Mule applications and the Mule instance. ## App Logs Every app that you build in Studio comes with its own `log4j2.xml` file. The log contains information about any errors raised in the app (unless you have app logic to handle those errors). It also contains anything you want to explicitly log, if you build the logic in the app. Mule automatically logs multiple messages and specific elements in your app flows to help you debug and keep track of events. You can also include the [Logger component](https://docs.mulesoft.com/mule-runtime/4.11/logger-component-reference) anywhere in a flow and set it up to output any message you want. You can view an app log as follows: - If you’re running an app from Anypoint Studio, the output from the app log is visible in Anypoint Studio’s console window. - If you’re using Mule from the command line to run an app, the app log is visible in your OS console. By default, Mule stores application log files in the following location: `MULE_HOME/logs/.log`. You can customize the log file path in the `log4j2.xml` file of the Mule app. ## Runtime Log The runtime log (`mule_ee.log`) contains information about the apps and lifecycle events. For example, the log records an entry when a Mule service or app starts, deploys, stops, or undeploys. The runtime log configuration is located in the `log4j2.xml` file, in the `/conf` directory. You can customize this file when running Mule on-premises. ### View the Runtime Log in Anypoint Studio: Click **Anypoint Studio > About Anypoint Studio > Installation Details > Configuration > View Error Log**: ![An Anypoint Studio error log viewer interface](/mulesoft/current/en-us/mule-runtime/4.11/_images/logging-in-mule-view-error-log.png) ### Change the Log Level You can change the runtime log level by modifying the `level` value of the following packages in the `log4j2.xml` file: ```xml ``` Accepted values are: `DEBUG`, `ERROR`, `INFO`, `TRACE`, and `WARN`. To change the log level only for specific Connectors, see [Enable Verbose Logging](https://docs.mulesoft.com/mule-runtime/4.11/enable-verbose-logging). ## Configure Logging You can create a configuration file to define: - What kinds of messages to log - How to log the messages (asynchronously or synchronously) - Where to log the messages, such as to the console or disk, or to an endpoint or database Mule uses `slf4j`, which is a logging facade that discovers and uses a logging strategy from the classpath, such as Apache Log4j 2 or the JDK Logger. By default, Mule includes Log4j 2, which is configured with a file called `log4j2.xml`. ## Synchronous Versus Asynchronous Logging By default, Mule logs messages asynchronously. When logging synchronously, the execution of the thread that is processing your message is interrupted to wait for the log message to be fully handled before it can continue: ![A synchronous logging in a threaded environment](/mulesoft/current/en-us/mule-runtime/4.11/_images/logger-synch.png) When logging asynchronously, the logging operation occurs in a separate thread, so the message can process before the logging completes: ![An asynchronous logging in a threaded environment](/mulesoft/current/en-us/mule-runtime/4.11/_images/logger-asynch-alternativo.png) In most situations, MuleSoft recommends that you use **asynchronous logging** because it substantially improves the throughput and lowers the latency of message processing. When asynchronous logging is used, some actions might not be logged if there is a system crash. This situation occurs because log writing is performed on a separate thread that runs independently of other actions. See [Exception Handling with Asynchronous Logging](#exception_handling) for information on mitigating this issue. If you use app logs as audit trails, configure your app to always use **synchronous** logging. This prevents the loss of any log messages. > [!NOTE] Mule 4 introduced thread-local functionality to optimize the memory usage of log4j. To > enhance the use of this feature, you can set the system property > `AsyncLoggerConfig.RingBufferSize` (see [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.11/configuring-properties)). `20000` > is the suggested value, but you need to tune it to meet your needs. ### Performance tests The chart below shows the performance difference between synchronous and asynchronous logging, and how much latency increased as more concurrent messages were added. In this test, an app logged about one million messages, using an increasingly higher amount of threads on each run. Each transaction resulted in 1000 messages. ![A line chart comparing latency versus concurrency](/mulesoft/current/en-us/mule-runtime/4.11/_images/logging-latency-vs-concurrency.png) As indicated by the chart, the results of logging asynchronously are significantly closer to the results of not logging at all. ## Configuring Custom Logging Settings By default, logging in Mule is done asynchronously and at a level greater than or equal to INFO. The default log level discards log messages at the DEBUG or TRACE level. To use synchronous logging, adjust the logging level or define custom categories. You can configure these properties using the `$MULE_HOME/conf/log4j2.xml` file, which specifies how the logger behaves. If you don’t edit this file, Mule uses the default properties. In Anypoint Studio, `log4j2.xml` appears in the `src/main/resources` path of each Mule object. The default configuration defines all loggers, including the root logger, as asynchronous. You can override this configuration at the domain or app level. To override this configuration at the app level, add a `logConfigFile` entry to the `mule-artifact.json` file. For example: ```json { "minMuleVersion": "4.0.0", "logConfigFile": "../../../test-classes/resources/logging/custom-log4j2.xml" } ``` The following is the default configuration for the `log4j2.xml` file: ```xml ``` ## Configuring Logs for the Runtime Manager Agent > [!NOTE] This configuration is only valid when using the Runtime Manager agent 1.5.2 and later. To log the Runtime Manager Agent state in a location other than the default `mule_agent.log` file, configure the `$MULE_HOME/conf/log4j2.xml` file to include a new Log4j 2 Appender called `mule-agent-appender`. If included, the Runtime Manager Agent plugin uses this appender to log its state. The `log4j2.xml` file should include something like the following snippet to enable this functionality: ```xml (...) %d %p %c{1.} [%t] %m%n (...) ``` The above example makes the Runtime Manager agent log its state to a rolling log file in `$MULE_HOME/logs/custom_mule_agent.log`. This file rolls over on a daily interval until it reaches a 250MB size. For other Log4j 2 appender configurations, see the Apache Log4j 2 documentation. ## Exception Handling with Asynchronous Logging If you’re using asynchronous logging and experience a system crash that might have caused incomplete logs, the LMAX `ExceptionHandler` handler can help. By default, Mule registers this handler to log events to the disk, console, and `logs/mule_ee.log`. To provide your own exception handler, set the system property `AsyncLoggerConfig.ExceptionHandler` to the canonical name of a class that implements the interface. The default exception handler is shown below: ```java /* * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.runtime.module.launcher.api.log4j2; import com.lmax.disruptor.ExceptionHandler; import org.apache.logging.log4j.status.StatusLogger; /** * Implementation of {@link com.lmax.disruptor.ExceptionHandler} to be used when async loggers fail to log their messages. It will * log this event using the {@link org.apache.logging.log4j.status.StatusLogger} * * @since 3.6.0 */ public class AsyncLoggerExceptionHandler implements ExceptionHandler { private static final StatusLogger LOGGER = StatusLogger.getLogger(); @Override public void handleEventException(Throwable ex, long sequence, Object event) { LOGGER.error("Failed to asynchronously log message: " + event, ex); } @Override public void handleOnStartException(Throwable ex) { LOGGER.error("Failed to start asynchronous logger", ex); } @Override public void handleOnShutdownException(Throwable ex) { LOGGER.error("Failed to stop asynchronous logger", ex); } } ``` There is a performance-reliability trade-off between asynchronous and synchronous logging. If the risk of losing log messages is a serious issue, then configure your loggers to be synchronous. You can have a mix of both synchronous and asynchronous logging. ## Configuration Reloading Mule runtime uses Log4j 2 as the framework for logging. To add or change the monitoring interval at which Log4j 2 checks for changes, add the `monitorInterval` to the `log4j2.xml` configuration file: 1. In the Mule installation folder, open `conf/log4j2.xml`. 2. Add `` after the first line. For example: ```xml ... ``` In this example, Log4j 2 checks for changes every 15 seconds. 3. Save the file, and restart the Mule server. For more information, see the Apache documentation on automatically configuring Log4j 2. ## Debugging Projects that Use the HTTP Connector To debug projects that use the HTTP connector, you might want to make the logging more verbose than usual and track all of the behavior of the HTTP connector’s `http-listener` and `http-request` operations in your project. See [HTTP Connector Troubleshooting Guide](https://docs.mulesoft.com/http-connector/1.10/http-troubleshooting) for information. ## Request and Response Logging for SOAP 1. Open the `log4j2.xml` file in `src/main/resources` and add the `HttpMessageLogger` to the config: ```xml ``` 2. Save your project. ## Troubleshooting Logging I don’t see any logging output Set the `log4j2.xml` at the root of your classpath. I reconfigured Log4j 2, but nothing happened This issue happens because there is another `log4j2.xml` file on your classpath that is getting picked up before your modified one. To find out which configuration file Log4j 2 is using, add the following switch when starting Mule (or add it to the container startup script if you are embedding Mule): \-M-Dlog4j.debug=true This switch writes the Log4j 2 startup information, including the location of the configuration file being used, to `stdout`. You must remove that configuration file before your modified configuration can work. --- product: Mule Runtime version: 4.12 keywords: mule, studio, logger, logs, log, notifications, errors, debug --- # Configuring Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides application logs and a runtime log to help you monitor and troubleshoot your Mule applications and the Mule instance. ## App Logs Every app that you build in Studio comes with its own `log4j2.xml` file. The log contains information about any errors raised in the app (unless you have app logic to handle those errors). It also contains anything you want to explicitly log, if you build the logic in the app. Mule automatically logs multiple messages and specific elements in your app flows to help you debug and keep track of events. You can also include the [Logger component](https://docs.mulesoft.com/mule-runtime/4.12/logger-component-reference) anywhere in a flow and set it up to output any message you want. You can view an app log as follows: - If you’re running an app from Anypoint Studio, the output from the app log is visible in Anypoint Studio’s console window. - If you’re using Mule from the command line to run an app, the app log is visible in your OS console. By default, Mule stores application log files in the following location: `MULE_HOME/logs/.log`. You can customize the log file path in the `log4j2.xml` file of the Mule app. ## Runtime Log The runtime log (`mule_ee.log`) contains information about the apps and lifecycle events. For example, the log records an entry when a Mule service or app starts, deploys, stops, or undeploys. The runtime log configuration is located in the `log4j2.xml` file, in the `/conf` directory. You can customize this file when running Mule on-premises. ### View the Runtime Log in Anypoint Studio: Click **Anypoint Studio > About Anypoint Studio > Installation Details > Configuration > View Error Log**: ![An Anypoint Studio error log viewer interface](/mulesoft/current/en-us/mule-runtime/4.12/_images/logging-in-mule-view-error-log.png) ### Change the Log Level You can change the runtime log level by modifying the `level` value of the following packages in the `log4j2.xml` file: ```xml ``` Accepted values are: `DEBUG`, `ERROR`, `INFO`, `TRACE`, and `WARN`. To change the log level only for specific Connectors, see [Enable Verbose Logging](https://docs.mulesoft.com/mule-runtime/4.12/enable-verbose-logging). ## Configure Logging You can create a configuration file to define: - What kinds of messages to log - How to log the messages (asynchronously or synchronously) - Where to log the messages, such as to the console or disk, or to an endpoint or database Mule uses `slf4j`, which is a logging facade that discovers and uses a logging strategy from the classpath, such as Apache Log4j 2 or the JDK Logger. By default, Mule includes Log4j 2, which is configured with a file called `log4j2.xml`. ## Synchronous Versus Asynchronous Logging By default, Mule logs messages asynchronously. When logging synchronously, the execution of the thread that is processing your message is interrupted to wait for the log message to be fully handled before it can continue: ![A synchronous logging in a threaded environment](/mulesoft/current/en-us/mule-runtime/4.12/_images/logger-synch.png) When logging asynchronously, the logging operation occurs in a separate thread, so the message can process before the logging completes: ![An asynchronous logging in a threaded environment](/mulesoft/current/en-us/mule-runtime/4.12/_images/logger-asynch-alternativo.png) In most situations, MuleSoft recommends that you use **asynchronous logging** because it substantially improves the throughput and lowers the latency of message processing. When asynchronous logging is used, some actions might not be logged if there is a system crash. This situation occurs because log writing is performed on a separate thread that runs independently of other actions. See [Exception Handling with Asynchronous Logging](#exception_handling) for information on mitigating this issue. If you use app logs as audit trails, configure your app to always use **synchronous** logging. This prevents the loss of any log messages. > [!NOTE] Mule 4 introduced thread-local functionality to optimize the memory usage of log4j. To > enhance the use of this feature, you can set the system property > `AsyncLoggerConfig.RingBufferSize` (see [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.12/configuring-properties)). `20000` > is the suggested value, but you need to tune it to meet your needs. ### Performance tests The chart below shows the performance difference between synchronous and asynchronous logging, and how much latency increased as more concurrent messages were added. In this test, an app logged about one million messages, using an increasingly higher amount of threads on each run. Each transaction resulted in 1000 messages. ![A line chart comparing latency versus concurrency](/mulesoft/current/en-us/mule-runtime/4.12/_images/logging-latency-vs-concurrency.png) As indicated by the chart, the results of logging asynchronously are significantly closer to the results of not logging at all. ## Configuring Custom Logging Settings By default, logging in Mule is done asynchronously and at a level greater than or equal to INFO. The default log level discards log messages at the DEBUG or TRACE level. To use synchronous logging, adjust the logging level or define custom categories. You can configure these properties using the `$MULE_HOME/conf/log4j2.xml` file, which specifies how the logger behaves. If you don’t edit this file, Mule uses the default properties. In Anypoint Studio, `log4j2.xml` appears in the `src/main/resources` path of each Mule object. The default configuration defines all loggers, including the root logger, as asynchronous. You can override this configuration at the domain or app level. To override this configuration at the app level, add a `logConfigFile` entry to the `mule-artifact.json` file. For example: ```json { "minMuleVersion": "4.0.0", "logConfigFile": "../../../test-classes/resources/logging/custom-log4j2.xml" } ``` The following is the default configuration for the `log4j2.xml` file: ```xml ``` ## Configuring Logs for the Runtime Manager Agent > [!NOTE] This configuration is only valid when using the Runtime Manager agent 1.5.2 and later. To log the Runtime Manager Agent state in a location other than the default `mule_agent.log` file, configure the `$MULE_HOME/conf/log4j2.xml` file to include a new Log4j 2 Appender called `mule-agent-appender`. If included, the Runtime Manager Agent plugin uses this appender to log its state. The `log4j2.xml` file should include something like the following snippet to enable this functionality: ```xml (...) %d %p %c{1.} [%t] %m%n (...) ``` The above example makes the Runtime Manager agent log its state to a rolling log file in `$MULE_HOME/logs/custom_mule_agent.log`. This file rolls over on a daily interval until it reaches a 250MB size. For other Log4j 2 appender configurations, see the Apache Log4j 2 documentation. ## Exception Handling with Asynchronous Logging If you’re using asynchronous logging and experience a system crash that might have caused incomplete logs, the LMAX `ExceptionHandler` handler can help. By default, Mule registers this handler to log events to the disk, console, and `logs/mule_ee.log`. To provide your own exception handler, set the system property `AsyncLoggerConfig.ExceptionHandler` to the canonical name of a class that implements the interface. The default exception handler is shown below: ```java /* * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.runtime.module.launcher.api.log4j2; import com.lmax.disruptor.ExceptionHandler; import org.apache.logging.log4j.status.StatusLogger; /** * Implementation of {@link com.lmax.disruptor.ExceptionHandler} to be used when async loggers fail to log their messages. It will * log this event using the {@link org.apache.logging.log4j.status.StatusLogger} * * @since 3.6.0 */ public class AsyncLoggerExceptionHandler implements ExceptionHandler { private static final StatusLogger LOGGER = StatusLogger.getLogger(); @Override public void handleEventException(Throwable ex, long sequence, Object event) { LOGGER.error("Failed to asynchronously log message: " + event, ex); } @Override public void handleOnStartException(Throwable ex) { LOGGER.error("Failed to start asynchronous logger", ex); } @Override public void handleOnShutdownException(Throwable ex) { LOGGER.error("Failed to stop asynchronous logger", ex); } } ``` There is a performance-reliability trade-off between asynchronous and synchronous logging. If the risk of losing log messages is a serious issue, then configure your loggers to be synchronous. You can have a mix of both synchronous and asynchronous logging. ## Configuration Reloading Mule runtime uses Log4j 2 as the framework for logging. To add or change the monitoring interval at which Log4j 2 checks for changes, add the `monitorInterval` to the `log4j2.xml` configuration file: 1. In the Mule installation folder, open `conf/log4j2.xml`. 2. Add `` after the first line. For example: ```xml ... ``` In this example, Log4j 2 checks for changes every 15 seconds. 3. Save the file, and restart the Mule server. For more information, see the Apache documentation on automatically configuring Log4j 2. ## Debugging Projects that Use the HTTP Connector To debug projects that use the HTTP connector, you might want to make the logging more verbose than usual and track all of the behavior of the HTTP connector’s `http-listener` and `http-request` operations in your project. See [HTTP Connector Troubleshooting Guide](https://docs.mulesoft.com/http-connector/1.10/http-troubleshooting) for information. ## Request and Response Logging for SOAP 1. Open the `log4j2.xml` file in `src/main/resources` and add the `HttpMessageLogger` to the config: ```xml ``` 2. Save your project. ## Troubleshooting Logging I don’t see any logging output Set the `log4j2.xml` at the root of your classpath. I reconfigured Log4j 2, but nothing happened This issue happens because there is another `log4j2.xml` file on your classpath that is getting picked up before your modified one. To find out which configuration file Log4j 2 is using, add the following switch when starting Mule (or add it to the container startup script if you are embedding Mule): \-M-Dlog4j.debug=true This switch writes the Log4j 2 startup information, including the location of the configuration file being used, to `stdout`. You must remove that configuration file before your modified configuration can work. --- product: Mule Runtime version: 4.3 keywords: mule, studio, logger, logs, log, notifications, errors, debug --- # Configuring Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides application logs and a runtime log to help you monitor and troubleshoot your Mule applications and the Mule instance. ## App Logs Every app that you build in Studio comes with its own `log4j2.xml` file. The log contains information about any errors raised in the app (unless you have app logic to handle those errors). It also contains anything you want to explicitly log, if you build the logic in the app. Mule automatically logs multiple messages and specific elements in your app flows to help you debug and keep track of events. You can also include the [Logger component](https://docs.mulesoft.com/mule-runtime/4.3/logger-component-reference) anywhere in a flow and set it up to output any message you want. You can view an app log as follows: - If you’re running an app from Anypoint Studio, the output from the app log is visible in Anypoint Studio’s console window. - If you’re using Mule from the command line to run an app, the app log is visible in your OS console. By default, Mule stores application log files in the following location: `MULE_HOME/logs/.log`. You can customize the log file path in the `log4j2.xml` file of the Mule app. ## Runtime Log The runtime log (`mule_ee.log`) contains information about the apps and lifecycle events. For example, the log records an entry when a Mule service or app starts, deploys, stops, or undeploys. The runtime log configuration is located in the `log4j2.xml` file, in the `/conf` directory. You can customize this file when running Mule on-premises. ### View the Runtime Log in Anypoint Studio: Click **Anypoint Studio > About Anypoint Studio > Installation Details > Configuration > View Error Log**: ![View Error Log](/mulesoft/current/en-us/mule-runtime/4.3/_images/logging-in-mule-view-error-log.png) ### Change the Log Level You can change the runtime log level by modifying the `level` value of the following packages in the `log4j2.xml` file: ```xml ``` Accepted values are: `DEBUG`, `ERROR`, `INFO`, `TRACE`, and `WARN`. To change the log level only for specific Connectors, see [Enable Verbose Logging](https://docs.mulesoft.com/mule-runtime/4.3/enable-verbose-logging). ## Configure Logging You can create a configuration file to define: - What kinds of messages to log - How to log the messages (asynchronously or synchronously) - Where to log the messages, such as to the console or disk, or to an endpoint or database Mule uses `slf4j`, which is a logging facade that discovers and uses a logging strategy from the classpath, such as Apache Log4j 2 or the JDK Logger. By default, Mule includes Log4j 2, which is configured with a file called `log4j2.xml`. ## Synchronous Versus Asynchronous Logging By default, Mule logs messages asynchronously. When logging synchronously, the execution of the thread that is processing your message is interrupted to wait for the log message to be fully handled before it can continue: ![logger synch](/mulesoft/current/en-us/mule-runtime/4.3/_images/logger-synch.png) When logging asynchronously, the logging operation occurs in a separate thread, so the message can process before the logging completes: ![logger asynch alternativo](/mulesoft/current/en-us/mule-runtime/4.3/_images/logger-asynch-alternativo.png) In most situations, MuleSoft recommends that you use **asynchronous logging** because it substantially improves the throughput and lowers the latency of message processing. When asynchronous logging is used, some actions might not be logged if there is a system crash. This situation occurs because log writing is performed on a separate thread that runs independently of other actions. See [Exception Handling with Asynchronous Logging](#exception_handling) for information on mitigating this issue. If you use app logs as audit trails, configure your app to always use **synchronous** logging. This prevents the loss of any log messages. > [!NOTE] Mule 4 introduced thread-local functionality to optimize the memory usage of log4j. To > enhance the use of this feature, you can set the system property > `AsyncLoggerConfig.RingBufferSize` (see [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.3/configuring-properties)). `20000` > is the suggested value, but you need to tune it to meet your needs. ### Performance tests The chart below shows the performance difference between synchronous and asynchronous logging, and how much latency increased as more concurrent messages were added. In this test, an app logged about one million messages, using an increasingly higher amount of threads on each run. Each transaction resulted in 1000 messages. ![logging latency vs concurrency](/mulesoft/current/en-us/mule-runtime/4.3/_images/logging-latency-vs-concurrency.png) As indicated by the chart, the results of logging asynchronously are significantly closer to the results of not logging at all. ## Configuring Custom Logging Settings By default, logging in Mule is done asynchronously and at a level greater than or equal to INFO. The default log level discards log messages at the DEBUG or TRACE level. To use synchronous logging, adjust the logging level or define custom categories. You can configure these properties using the `$MULE_HOME/conf/log4j2.xml` file, which specifies how the logger behaves. If you don’t edit this file, Mule uses the default properties. In Anypoint Studio, `log4j2.xml` appears in the `src/main/resources` path of each Mule object. The default configuration defines all loggers, including the root logger, as asynchronous. You can override this configuration at the domain or app level. To override this configuration at the app level, add a `logConfigFile` entry to the `mule-artifact.json` file. For example: ```json { "minMuleVersion": "4.0.0", "logConfigFile": "../../../test-classes/resources/logging/custom-log4j2.xml" } ``` The following is the default configuration for the `log4j2.xml` file: ```xml ``` ## Configuring Logs for the Runtime Manager Agent > [!NOTE] This configuration is only valid when using the Runtime Manager agent 1.5.2 and later. To log the Runtime Manager Agent state in a location other than the default `mule_agent.log` file, configure the `$MULE_HOME/conf/log4j2.xml` file to include a new Log4j 2 Appender called `mule-agent-appender`. If included, the Runtime Manager Agent plugin uses this appender to log its state. The `log4j2.xml` file should include something like the following snippet to enable this functionality: ```xml (...) %d %p %c{1.} [%t] %m%n (...) ``` The above example makes the Runtime Manager agent log its state to a rolling log file in `$MULE_HOME/logs/custom_mule_agent.log`. This file rolls over on a daily interval until it reaches a 250MB size. For other Log4j 2 appender configurations, see the Apache Log4j 2 documentation. ## Exception Handling with Asynchronous Logging If you’re using asynchronous logging and experience a system crash that might have caused incomplete logs, the LMAX `ExceptionHandler` handler can help. By default, Mule registers this handler to log events to the disk, console, and `logs/mule_ee.log`. To provide your own exception handler, set the system property `AsyncLoggerConfig.ExceptionHandler` to the canonical name of a class that implements the interface. The default exception handler is shown below: ```java /* * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.runtime.module.launcher.api.log4j2; import com.lmax.disruptor.ExceptionHandler; import org.apache.logging.log4j.status.StatusLogger; /** * Implementation of {@link com.lmax.disruptor.ExceptionHandler} to be used when async loggers fail to log their messages. It will * log this event using the {@link org.apache.logging.log4j.status.StatusLogger} * * @since 3.6.0 */ public class AsyncLoggerExceptionHandler implements ExceptionHandler { private static final StatusLogger LOGGER = StatusLogger.getLogger(); @Override public void handleEventException(Throwable ex, long sequence, Object event) { LOGGER.error("Failed to asynchronously log message: " + event, ex); } @Override public void handleOnStartException(Throwable ex) { LOGGER.error("Failed to start asynchronous logger", ex); } @Override public void handleOnShutdownException(Throwable ex) { LOGGER.error("Failed to stop asynchronous logger", ex); } } ``` There is a performance-reliability trade-off between asynchronous and synchronous logging. If the risk of losing log messages is a serious issue, then configure your loggers to be synchronous. You can have a mix of both synchronous and asynchronous logging. ## Configuration Reloading Mule runtime uses Log4j 2 as the framework for logging. To add or change the monitoring interval at which Log4j 2 checks for changes, add the `monitorInterval` to the `log4j2.xml` configuration file: 1. In the Mule installation folder, open `conf/log4j2.xml`. 2. Add `` after the first line. For example: ```xml ... ``` In this example, Log4j 2 checks for changes every 15 seconds. 3. Save the file, and restart the Mule server. For more information, see the Apache documentation on automatically configuring Log4j 2. ## Debugging Projects that Use the HTTP Connector To debug projects that use the HTTP connector, you might want to make the logging more verbose than usual and track all of the behavior of the HTTP connector’s `http-listener` and `http-request` operations in your project. See [HTTP Connector Troubleshooting Guide](https://docs.mulesoft.com/http-connector/1.10/http-troubleshooting) for information. ## Request and Response Logging for SOAP 1. Open the `log4j2.xml` file in `src/main/resources` and add the `HttpMessageLogger` to the config: ```xml ``` 2. Save your project. ## Troubleshooting Logging I don’t see any logging output Set the `log4j2.xml` at the root of your classpath. I reconfigured Log4j 2, but nothing happened This issue happens because there is another `log4j2.xml` file on your classpath that is getting picked up before your modified one. To find out which configuration file Log4j 2 is using, add the following switch when starting Mule (or add it to the container startup script if you are embedding Mule): \-M-Dlog4j.debug=true This switch writes the Log4j 2 startup information, including the location of the configuration file being used, to `stdout`. You must remove that configuration file before your modified configuration can work. --- product: Mule Runtime version: 4.4 keywords: mule, studio, logger, logs, log, notifications, errors, debug --- # Configuring Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides application logs and a runtime log to help you monitor and troubleshoot your Mule applications and the Mule instance. ## App Logs Every app that you build in Studio comes with its own `log4j2.xml` file. The log contains information about any errors raised in the app (unless you have app logic to handle those errors). It also contains anything you want to explicitly log, if you build the logic in the app. Mule automatically logs multiple messages and specific elements in your app flows to help you debug and keep track of events. You can also include the [Logger component](https://docs.mulesoft.com/mule-runtime/4.4/logger-component-reference) anywhere in a flow and set it up to output any message you want. You can view an app log as follows: - If you’re running an app from Anypoint Studio, the output from the app log is visible in Anypoint Studio’s console window. - If you’re using Mule from the command line to run an app, the app log is visible in your OS console. By default, Mule stores application log files in the following location: `MULE_HOME/logs/.log`. You can customize the log file path in the `log4j2.xml` file of the Mule app. ## Runtime Log The runtime log (`mule_ee.log`) contains information about the apps and lifecycle events. For example, the log records an entry when a Mule service or app starts, deploys, stops, or undeploys. The runtime log configuration is located in the `log4j2.xml` file, in the `/conf` directory. You can customize this file when running Mule on-premises. ### View the Runtime Log in Anypoint Studio: Click **Anypoint Studio > About Anypoint Studio > Installation Details > Configuration > View Error Log**: ![View Error Log](/mulesoft/current/en-us/mule-runtime/4.4/_images/logging-in-mule-view-error-log.png) ### Change the Log Level You can change the runtime log level by modifying the `level` value of the following packages in the `log4j2.xml` file: ```xml ``` Accepted values are: `DEBUG`, `ERROR`, `INFO`, `TRACE`, and `WARN`. To change the log level only for specific Connectors, see [Enable Verbose Logging](https://docs.mulesoft.com/mule-runtime/4.4/enable-verbose-logging). ## Configure Logging You can create a configuration file to define: - What kinds of messages to log - How to log the messages (asynchronously or synchronously) - Where to log the messages, such as to the console or disk, or to an endpoint or database Mule uses `slf4j`, which is a logging facade that discovers and uses a logging strategy from the classpath, such as Apache Log4j 2 or the JDK Logger. By default, Mule includes Log4j 2, which is configured with a file called `log4j2.xml`. ## Synchronous Versus Asynchronous Logging By default, Mule logs messages asynchronously. When logging synchronously, the execution of the thread that is processing your message is interrupted to wait for the log message to be fully handled before it can continue: ![logger synch](/mulesoft/current/en-us/mule-runtime/4.4/_images/logger-synch.png) When logging asynchronously, the logging operation occurs in a separate thread, so the message can process before the logging completes: ![logger asynch alternativo](/mulesoft/current/en-us/mule-runtime/4.4/_images/logger-asynch-alternativo.png) In most situations, MuleSoft recommends that you use **asynchronous logging** because it substantially improves the throughput and lowers the latency of message processing. When asynchronous logging is used, some actions might not be logged if there is a system crash. This situation occurs because log writing is performed on a separate thread that runs independently of other actions. See [Exception Handling with Asynchronous Logging](#exception_handling) for information on mitigating this issue. If you use app logs as audit trails, configure your app to always use **synchronous** logging. This prevents the loss of any log messages. > [!NOTE] Mule 4 introduced thread-local functionality to optimize the memory usage of log4j. To > enhance the use of this feature, you can set the system property > `AsyncLoggerConfig.RingBufferSize` (see [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.4/configuring-properties)). `20000` > is the suggested value, but you need to tune it to meet your needs. ### Performance tests The chart below shows the performance difference between synchronous and asynchronous logging, and how much latency increased as more concurrent messages were added. In this test, an app logged about one million messages, using an increasingly higher amount of threads on each run. Each transaction resulted in 1000 messages. ![logging latency vs concurrency](/mulesoft/current/en-us/mule-runtime/4.4/_images/logging-latency-vs-concurrency.png) As indicated by the chart, the results of logging asynchronously are significantly closer to the results of not logging at all. ## Configuring Custom Logging Settings By default, logging in Mule is done asynchronously and at a level greater than or equal to INFO. The default log level discards log messages at the DEBUG or TRACE level. To use synchronous logging, adjust the logging level or define custom categories. You can configure these properties using the `$MULE_HOME/conf/log4j2.xml` file, which specifies how the logger behaves. If you don’t edit this file, Mule uses the default properties. In Anypoint Studio, `log4j2.xml` appears in the `src/main/resources` path of each Mule object. The default configuration defines all loggers, including the root logger, as asynchronous. You can override this configuration at the domain or app level. To override this configuration at the app level, add a `logConfigFile` entry to the `mule-artifact.json` file. For example: ```json { "minMuleVersion": "4.0.0", "logConfigFile": "../../../test-classes/resources/logging/custom-log4j2.xml" } ``` The following is the default configuration for the `log4j2.xml` file: ```xml ``` ## Configuring Logs for the Runtime Manager Agent > [!NOTE] This configuration is only valid when using the Runtime Manager agent 1.5.2 and later. To log the Runtime Manager Agent state in a location other than the default `mule_agent.log` file, configure the `$MULE_HOME/conf/log4j2.xml` file to include a new Log4j 2 Appender called `mule-agent-appender`. If included, the Runtime Manager Agent plugin uses this appender to log its state. The `log4j2.xml` file should include something like the following snippet to enable this functionality: ```xml (...) %d %p %c{1.} [%t] %m%n (...) ``` The above example makes the Runtime Manager agent log its state to a rolling log file in `$MULE_HOME/logs/custom_mule_agent.log`. This file rolls over on a daily interval until it reaches a 250MB size. For other Log4j 2 appender configurations, see the Apache Log4j 2 documentation. ## Exception Handling with Asynchronous Logging If you’re using asynchronous logging and experience a system crash that might have caused incomplete logs, the LMAX `ExceptionHandler` handler can help. By default, Mule registers this handler to log events to the disk, console, and `logs/mule_ee.log`. To provide your own exception handler, set the system property `AsyncLoggerConfig.ExceptionHandler` to the canonical name of a class that implements the interface. The default exception handler is shown below: ```java /* * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.runtime.module.launcher.api.log4j2; import com.lmax.disruptor.ExceptionHandler; import org.apache.logging.log4j.status.StatusLogger; /** * Implementation of {@link com.lmax.disruptor.ExceptionHandler} to be used when async loggers fail to log their messages. It will * log this event using the {@link org.apache.logging.log4j.status.StatusLogger} * * @since 3.6.0 */ public class AsyncLoggerExceptionHandler implements ExceptionHandler { private static final StatusLogger LOGGER = StatusLogger.getLogger(); @Override public void handleEventException(Throwable ex, long sequence, Object event) { LOGGER.error("Failed to asynchronously log message: " + event, ex); } @Override public void handleOnStartException(Throwable ex) { LOGGER.error("Failed to start asynchronous logger", ex); } @Override public void handleOnShutdownException(Throwable ex) { LOGGER.error("Failed to stop asynchronous logger", ex); } } ``` There is a performance-reliability trade-off between asynchronous and synchronous logging. If the risk of losing log messages is a serious issue, then configure your loggers to be synchronous. You can have a mix of both synchronous and asynchronous logging. ## Configuration Reloading Mule runtime uses Log4j 2 as the framework for logging. To add or change the monitoring interval at which Log4j 2 checks for changes, add the `monitorInterval` to the `log4j2.xml` configuration file: 1. In the Mule installation folder, open `conf/log4j2.xml`. 2. Add `` after the first line. For example: ```xml ... ``` In this example, Log4j 2 checks for changes every 15 seconds. 3. Save the file, and restart the Mule server. For more information, see the Apache documentation on automatically configuring Log4j 2. ## Debugging Projects that Use the HTTP Connector To debug projects that use the HTTP connector, you might want to make the logging more verbose than usual and track all of the behavior of the HTTP connector’s `http-listener` and `http-request` operations in your project. See [HTTP Connector Troubleshooting Guide](https://docs.mulesoft.com/http-connector/1.10/http-troubleshooting) for information. ## Request and Response Logging for SOAP 1. Open the `log4j2.xml` file in `src/main/resources` and add the `HttpMessageLogger` to the config: ```xml ``` 2. Save your project. ## Troubleshooting Logging I don’t see any logging output Set the `log4j2.xml` at the root of your classpath. I reconfigured Log4j 2, but nothing happened This issue happens because there is another `log4j2.xml` file on your classpath that is getting picked up before your modified one. To find out which configuration file Log4j 2 is using, add the following switch when starting Mule (or add it to the container startup script if you are embedding Mule): \-M-Dlog4j.debug=true This switch writes the Log4j 2 startup information, including the location of the configuration file being used, to `stdout`. You must remove that configuration file before your modified configuration can work. --- product: Mule Runtime version: 4.6 keywords: mule, studio, logger, logs, log, notifications, errors, debug --- # Configuring Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides application logs and a runtime log to help you monitor and troubleshoot your Mule applications and the Mule instance. ## App Logs Every app that you build in Studio comes with its own `log4j2.xml` file. The log contains information about any errors raised in the app (unless you have app logic to handle those errors). It also contains anything you want to explicitly log, if you build the logic in the app. Mule automatically logs multiple messages and specific elements in your app flows to help you debug and keep track of events. You can also include the [Logger component](https://docs.mulesoft.com/mule-runtime/4.6/logger-component-reference) anywhere in a flow and set it up to output any message you want. You can view an app log as follows: - If you’re running an app from Anypoint Studio, the output from the app log is visible in Anypoint Studio’s console window. - If you’re using Mule from the command line to run an app, the app log is visible in your OS console. By default, Mule stores application log files in the following location: `MULE_HOME/logs/.log`. You can customize the log file path in the `log4j2.xml` file of the Mule app. ## Runtime Log The runtime log (`mule_ee.log`) contains information about the apps and lifecycle events. For example, the log records an entry when a Mule service or app starts, deploys, stops, or undeploys. The runtime log configuration is located in the `log4j2.xml` file, in the `/conf` directory. You can customize this file when running Mule on-premises. ### View the Runtime Log in Anypoint Studio: Click **Anypoint Studio > About Anypoint Studio > Installation Details > Configuration > View Error Log**: ![View Error Log](/mulesoft/current/en-us/mule-runtime/4.6/_images/logging-in-mule-view-error-log.png) ### Change the Log Level You can change the runtime log level by modifying the `level` value of the following packages in the `log4j2.xml` file: ```xml ``` Accepted values are: `DEBUG`, `ERROR`, `INFO`, `TRACE`, and `WARN`. To change the log level only for specific Connectors, see [Enable Verbose Logging](https://docs.mulesoft.com/mule-runtime/4.6/enable-verbose-logging). ## Configure Logging You can create a configuration file to define: - What kinds of messages to log - How to log the messages (asynchronously or synchronously) - Where to log the messages, such as to the console or disk, or to an endpoint or database Mule uses `slf4j`, which is a logging facade that discovers and uses a logging strategy from the classpath, such as Apache Log4j 2 or the JDK Logger. By default, Mule includes Log4j 2, which is configured with a file called `log4j2.xml`. ## Synchronous Versus Asynchronous Logging By default, Mule logs messages asynchronously. When logging synchronously, the execution of the thread that is processing your message is interrupted to wait for the log message to be fully handled before it can continue: ![logger synch](/mulesoft/current/en-us/mule-runtime/4.6/_images/logger-synch.png) When logging asynchronously, the logging operation occurs in a separate thread, so the message can process before the logging completes: ![logger asynch alternativo](/mulesoft/current/en-us/mule-runtime/4.6/_images/logger-asynch-alternativo.png) In most situations, MuleSoft recommends that you use **asynchronous logging** because it substantially improves the throughput and lowers the latency of message processing. When asynchronous logging is used, some actions might not be logged if there is a system crash. This situation occurs because log writing is performed on a separate thread that runs independently of other actions. See [Exception Handling with Asynchronous Logging](#exception_handling) for information on mitigating this issue. If you use app logs as audit trails, configure your app to always use **synchronous** logging. This prevents the loss of any log messages. > [!NOTE] Mule 4 introduced thread-local functionality to optimize the memory usage of log4j. To > enhance the use of this feature, you can set the system property > `AsyncLoggerConfig.RingBufferSize` (see [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.6/configuring-properties)). `20000` > is the suggested value, but you need to tune it to meet your needs. ### Performance tests The chart below shows the performance difference between synchronous and asynchronous logging, and how much latency increased as more concurrent messages were added. In this test, an app logged about one million messages, using an increasingly higher amount of threads on each run. Each transaction resulted in 1000 messages. ![logging latency vs concurrency](/mulesoft/current/en-us/mule-runtime/4.6/_images/logging-latency-vs-concurrency.png) As indicated by the chart, the results of logging asynchronously are significantly closer to the results of not logging at all. ## Configuring Custom Logging Settings By default, logging in Mule is done asynchronously and at a level greater than or equal to INFO. The default log level discards log messages at the DEBUG or TRACE level. To use synchronous logging, adjust the logging level or define custom categories. You can configure these properties using the `$MULE_HOME/conf/log4j2.xml` file, which specifies how the logger behaves. If you don’t edit this file, Mule uses the default properties. In Anypoint Studio, `log4j2.xml` appears in the `src/main/resources` path of each Mule object. The default configuration defines all loggers, including the root logger, as asynchronous. You can override this configuration at the domain or app level. To override this configuration at the app level, add a `logConfigFile` entry to the `mule-artifact.json` file. For example: ```json { "minMuleVersion": "4.0.0", "logConfigFile": "../../../test-classes/resources/logging/custom-log4j2.xml" } ``` The following is the default configuration for the `log4j2.xml` file: ```xml ``` ## Configuring Logs for the Runtime Manager Agent > [!NOTE] This configuration is only valid when using the Runtime Manager agent 1.5.2 and later. To log the Runtime Manager Agent state in a location other than the default `mule_agent.log` file, configure the `$MULE_HOME/conf/log4j2.xml` file to include a new Log4j 2 Appender called `mule-agent-appender`. If included, the Runtime Manager Agent plugin uses this appender to log its state. The `log4j2.xml` file should include something like the following snippet to enable this functionality: ```xml (...) %d %p %c{1.} [%t] %m%n (...) ``` The above example makes the Runtime Manager agent log its state to a rolling log file in `$MULE_HOME/logs/custom_mule_agent.log`. This file rolls over on a daily interval until it reaches a 250MB size. For other Log4j 2 appender configurations, see the Apache Log4j 2 documentation. ## Exception Handling with Asynchronous Logging If you’re using asynchronous logging and experience a system crash that might have caused incomplete logs, the LMAX `ExceptionHandler` handler can help. By default, Mule registers this handler to log events to the disk, console, and `logs/mule_ee.log`. To provide your own exception handler, set the system property `AsyncLoggerConfig.ExceptionHandler` to the canonical name of a class that implements the interface. The default exception handler is shown below: ```java /* * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.runtime.module.launcher.api.log4j2; import com.lmax.disruptor.ExceptionHandler; import org.apache.logging.log4j.status.StatusLogger; /** * Implementation of {@link com.lmax.disruptor.ExceptionHandler} to be used when async loggers fail to log their messages. It will * log this event using the {@link org.apache.logging.log4j.status.StatusLogger} * * @since 3.6.0 */ public class AsyncLoggerExceptionHandler implements ExceptionHandler { private static final StatusLogger LOGGER = StatusLogger.getLogger(); @Override public void handleEventException(Throwable ex, long sequence, Object event) { LOGGER.error("Failed to asynchronously log message: " + event, ex); } @Override public void handleOnStartException(Throwable ex) { LOGGER.error("Failed to start asynchronous logger", ex); } @Override public void handleOnShutdownException(Throwable ex) { LOGGER.error("Failed to stop asynchronous logger", ex); } } ``` There is a performance-reliability trade-off between asynchronous and synchronous logging. If the risk of losing log messages is a serious issue, then configure your loggers to be synchronous. You can have a mix of both synchronous and asynchronous logging. ## Configuration Reloading Mule runtime uses Log4j 2 as the framework for logging. To add or change the monitoring interval at which Log4j 2 checks for changes, add the `monitorInterval` to the `log4j2.xml` configuration file: 1. In the Mule installation folder, open `conf/log4j2.xml`. 2. Add `` after the first line. For example: ```xml ... ``` In this example, Log4j 2 checks for changes every 15 seconds. 3. Save the file, and restart the Mule server. For more information, see the Apache documentation on automatically configuring Log4j 2. ## Debugging Projects that Use the HTTP Connector To debug projects that use the HTTP connector, you might want to make the logging more verbose than usual and track all of the behavior of the HTTP connector’s `http-listener` and `http-request` operations in your project. See [HTTP Connector Troubleshooting Guide](https://docs.mulesoft.com/http-connector/1.10/http-troubleshooting) for information. ## Request and Response Logging for SOAP 1. Open the `log4j2.xml` file in `src/main/resources` and add the `HttpMessageLogger` to the config: ```xml ``` 2. Save your project. ## Troubleshooting Logging I don’t see any logging output Set the `log4j2.xml` at the root of your classpath. I reconfigured Log4j 2, but nothing happened This issue happens because there is another `log4j2.xml` file on your classpath that is getting picked up before your modified one. To find out which configuration file Log4j 2 is using, add the following switch when starting Mule (or add it to the container startup script if you are embedding Mule): \-M-Dlog4j.debug=true This switch writes the Log4j 2 startup information, including the location of the configuration file being used, to `stdout`. You must remove that configuration file before your modified configuration can work. --- product: Mule Runtime version: 4.9 keywords: mule, studio, logger, logs, log, notifications, errors, debug --- # Configuring Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides application logs and a runtime log to help you monitor and troubleshoot your Mule applications and the Mule instance. ## App Logs Every app that you build in Studio comes with its own `log4j2.xml` file. The log contains information about any errors raised in the app (unless you have app logic to handle those errors). It also contains anything you want to explicitly log, if you build the logic in the app. Mule automatically logs multiple messages and specific elements in your app flows to help you debug and keep track of events. You can also include the [Logger component](https://docs.mulesoft.com/mule-runtime/4.9/logger-component-reference) anywhere in a flow and set it up to output any message you want. You can view an app log as follows: - If you’re running an app from Anypoint Studio, the output from the app log is visible in Anypoint Studio’s console window. - If you’re using Mule from the command line to run an app, the app log is visible in your OS console. By default, Mule stores application log files in the following location: `MULE_HOME/logs/.log`. You can customize the log file path in the `log4j2.xml` file of the Mule app. ## Runtime Log The runtime log (`mule_ee.log`) contains information about the apps and lifecycle events. For example, the log records an entry when a Mule service or app starts, deploys, stops, or undeploys. The runtime log configuration is located in the `log4j2.xml` file, in the `/conf` directory. You can customize this file when running Mule on-premises. ### View the Runtime Log in Anypoint Studio: Click **Anypoint Studio > About Anypoint Studio > Installation Details > Configuration > View Error Log**: ![An Anypoint Studio error log viewer interface](/mulesoft/current/en-us/mule-runtime/4.9/_images/logging-in-mule-view-error-log.png) ### Change the Log Level You can change the runtime log level by modifying the `level` value of the following packages in the `log4j2.xml` file: ```xml ``` Accepted values are: `DEBUG`, `ERROR`, `INFO`, `TRACE`, and `WARN`. To change the log level only for specific Connectors, see [Enable Verbose Logging](https://docs.mulesoft.com/mule-runtime/4.9/enable-verbose-logging). ## Configure Logging You can create a configuration file to define: - What kinds of messages to log - How to log the messages (asynchronously or synchronously) - Where to log the messages, such as to the console or disk, or to an endpoint or database Mule uses `slf4j`, which is a logging facade that discovers and uses a logging strategy from the classpath, such as Apache Log4j 2 or the JDK Logger. By default, Mule includes Log4j 2, which is configured with a file called `log4j2.xml`. ## Synchronous Versus Asynchronous Logging By default, Mule logs messages asynchronously. When logging synchronously, the execution of the thread that is processing your message is interrupted to wait for the log message to be fully handled before it can continue: ![A synchronous logging in a threaded environment](/mulesoft/current/en-us/mule-runtime/4.9/_images/logger-synch.png) When logging asynchronously, the logging operation occurs in a separate thread, so the message can process before the logging completes: ![An asynchronous logging in a threaded environment](/mulesoft/current/en-us/mule-runtime/4.9/_images/logger-asynch-alternativo.png) In most situations, MuleSoft recommends that you use **asynchronous logging** because it substantially improves the throughput and lowers the latency of message processing. When asynchronous logging is used, some actions might not be logged if there is a system crash. This situation occurs because log writing is performed on a separate thread that runs independently of other actions. See [Exception Handling with Asynchronous Logging](#exception_handling) for information on mitigating this issue. If you use app logs as audit trails, configure your app to always use **synchronous** logging. This prevents the loss of any log messages. > [!NOTE] Mule 4 introduced thread-local functionality to optimize the memory usage of log4j. To > enhance the use of this feature, you can set the system property > `AsyncLoggerConfig.RingBufferSize` (see [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.9/configuring-properties)). `20000` > is the suggested value, but you need to tune it to meet your needs. ### Performance tests The chart below shows the performance difference between synchronous and asynchronous logging, and how much latency increased as more concurrent messages were added. In this test, an app logged about one million messages, using an increasingly higher amount of threads on each run. Each transaction resulted in 1000 messages. ![A line chart comparing latency versus concurrency](/mulesoft/current/en-us/mule-runtime/4.9/_images/logging-latency-vs-concurrency.png) As indicated by the chart, the results of logging asynchronously are significantly closer to the results of not logging at all. ## Configuring Custom Logging Settings By default, logging in Mule is done asynchronously and at a level greater than or equal to INFO. The default log level discards log messages at the DEBUG or TRACE level. To use synchronous logging, adjust the logging level or define custom categories. You can configure these properties using the `$MULE_HOME/conf/log4j2.xml` file, which specifies how the logger behaves. If you don’t edit this file, Mule uses the default properties. In Anypoint Studio, `log4j2.xml` appears in the `src/main/resources` path of each Mule object. The default configuration defines all loggers, including the root logger, as asynchronous. You can override this configuration at the domain or app level. To override this configuration at the app level, add a `logConfigFile` entry to the `mule-artifact.json` file. For example: ```json { "minMuleVersion": "4.0.0", "logConfigFile": "../../../test-classes/resources/logging/custom-log4j2.xml" } ``` The following is the default configuration for the `log4j2.xml` file: ```xml ``` ## Configuring Logs for the Runtime Manager Agent > [!NOTE] This configuration is only valid when using the Runtime Manager agent 1.5.2 and later. To log the Runtime Manager Agent state in a location other than the default `mule_agent.log` file, configure the `$MULE_HOME/conf/log4j2.xml` file to include a new Log4j 2 Appender called `mule-agent-appender`. If included, the Runtime Manager Agent plugin uses this appender to log its state. The `log4j2.xml` file should include something like the following snippet to enable this functionality: ```xml (...) %d %p %c{1.} [%t] %m%n (...) ``` The above example makes the Runtime Manager agent log its state to a rolling log file in `$MULE_HOME/logs/custom_mule_agent.log`. This file rolls over on a daily interval until it reaches a 250MB size. For other Log4j 2 appender configurations, see the Apache Log4j 2 documentation. ## Exception Handling with Asynchronous Logging If you’re using asynchronous logging and experience a system crash that might have caused incomplete logs, the LMAX `ExceptionHandler` handler can help. By default, Mule registers this handler to log events to the disk, console, and `logs/mule_ee.log`. To provide your own exception handler, set the system property `AsyncLoggerConfig.ExceptionHandler` to the canonical name of a class that implements the interface. The default exception handler is shown below: ```java /* * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package org.mule.runtime.module.launcher.api.log4j2; import com.lmax.disruptor.ExceptionHandler; import org.apache.logging.log4j.status.StatusLogger; /** * Implementation of {@link com.lmax.disruptor.ExceptionHandler} to be used when async loggers fail to log their messages. It will * log this event using the {@link org.apache.logging.log4j.status.StatusLogger} * * @since 3.6.0 */ public class AsyncLoggerExceptionHandler implements ExceptionHandler { private static final StatusLogger LOGGER = StatusLogger.getLogger(); @Override public void handleEventException(Throwable ex, long sequence, Object event) { LOGGER.error("Failed to asynchronously log message: " + event, ex); } @Override public void handleOnStartException(Throwable ex) { LOGGER.error("Failed to start asynchronous logger", ex); } @Override public void handleOnShutdownException(Throwable ex) { LOGGER.error("Failed to stop asynchronous logger", ex); } } ``` There is a performance-reliability trade-off between asynchronous and synchronous logging. If the risk of losing log messages is a serious issue, then configure your loggers to be synchronous. You can have a mix of both synchronous and asynchronous logging. ## Configuration Reloading Mule runtime uses Log4j 2 as the framework for logging. To add or change the monitoring interval at which Log4j 2 checks for changes, add the `monitorInterval` to the `log4j2.xml` configuration file: 1. In the Mule installation folder, open `conf/log4j2.xml`. 2. Add `` after the first line. For example: ```xml ... ``` In this example, Log4j 2 checks for changes every 15 seconds. 3. Save the file, and restart the Mule server. For more information, see the Apache documentation on automatically configuring Log4j 2. ## Debugging Projects that Use the HTTP Connector To debug projects that use the HTTP connector, you might want to make the logging more verbose than usual and track all of the behavior of the HTTP connector’s `http-listener` and `http-request` operations in your project. See [HTTP Connector Troubleshooting Guide](https://docs.mulesoft.com/http-connector/1.10/http-troubleshooting) for information. ## Request and Response Logging for SOAP 1. Open the `log4j2.xml` file in `src/main/resources` and add the `HttpMessageLogger` to the config: ```xml ``` 2. Save your project. ## Troubleshooting Logging I don’t see any logging output Set the `log4j2.xml` at the root of your classpath. I reconfigured Log4j 2, but nothing happened This issue happens because there is another `log4j2.xml` file on your classpath that is getting picked up before your modified one. To find out which configuration file Log4j 2 is using, add the following switch when starting Mule (or add it to the container startup script if you are embedding Mule): \-M-Dlog4j.debug=true This switch writes the Log4j 2 startup information, including the location of the configuration file being used, to `stdout`. You must remove that configuration file before your modified configuration can work. --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: mule, studio, logger, logs, log, notifications, errors, debug --- # Configuring Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides application logs and a runtime log to help you monitor and troubleshoot your Mule applications and the Mule instance. ## App Logs Every app that you build in Studio comes with its own `log4j2.xml` configuration file, which defines how the app log is written. The app log contains information about any errors raised in the app (unless you have app logic to handle those errors). It also contains anything you explicitly log in the app. Mule automatically logs multiple messages and specific elements in your app flows to help you debug and keep track of events. You can also include the [Logger component](https://docs.mulesoft.com/mule-runtime/latest/logger-component-reference) anywhere in a flow and set it up to output any message you want. You can view an app log as follows: - If you’re running an app from Anypoint Studio, the output from the app log is visible in Anypoint Studio’s console window. - If you’re using Mule from the command line to run an app, the app log is visible in your OS console. By default, Mule stores application log files in the following location: `MULE_HOME/logs/.log`. You can customize the log file path in the `log4j2.xml` file of the Mule app. If you deploy your app to CloudHub or CloudHub 2.0, see [View Log Data](https://docs.mulesoft.com/cloudhub/viewing-log-data). If you deploy your app to Runtime Fabric, see [Integrating with Your Logging System Using Log4j](https://docs.mulesoft.com/runtime-fabric/latest/use-log4j-appender). ## Runtime Log The runtime log (`mule_ee.log`) contains information about the apps and lifecycle events. For example, the log records an entry when a Mule service or app starts, deploys, stops, or undeploys. The runtime log configuration is located in the `log4j2.xml` file, in the `/conf` directory. You can customize this file when running Mule on-premises. ### View the Runtime Log in Anypoint Studio Click **Anypoint Studio > About Anypoint Studio > Installation Details > Configuration > View Error Log**: ![An Anypoint Studio error log viewer interface](/mulesoft/current/en-us/mule-runtime/latest/_images/logging-in-mule-view-error-log.png) ## How Logging Works in Mule Mule uses `slf4j`, which is a logging facade that discovers and uses a logging strategy from the classpath, such as Apache Log4j 2 or the JDK Logger. By default, Mule includes Log4j 2, which is configured with a file called `log4j2.xml`. In the `log4j2.xml` file, you define: - What kinds of messages to log (the log level) - How to log the messages (asynchronously or synchronously) - Where to log the messages, such as to the console or disk, or to an endpoint or database (the appenders) ## Synchronous Versus Asynchronous Logging By default, Mule logs messages asynchronously. When logging synchronously, the execution of the thread that is processing your message is interrupted to wait for the log message to be fully handled before it can continue: ![A synchronous logging in a threaded environment](/mulesoft/current/en-us/mule-runtime/latest/_images/logger-synch.png) When logging asynchronously, the logging operation occurs in a separate thread, so the message can process before the logging completes: ![An asynchronous logging in a threaded environment](/mulesoft/current/en-us/mule-runtime/latest/_images/logger-asynch-alternativo.png) In most situations, MuleSoft recommends that you use **asynchronous logging** because it substantially improves the throughput and lowers the latency of message processing. When asynchronous logging is used, some actions might not be logged if there is a system crash. This situation occurs because log writing is performed on a separate thread that runs independently of other actions. See [Exception Handling with Asynchronous Logging](#exception_handling) for information on mitigating this issue. If you use app logs as audit trails, configure your app to always use **synchronous** logging. This prevents the loss of any log messages. > [!NOTE] Mule 4 introduced thread-local functionality to optimize the memory usage of log4j. To > enhance the use of this feature, you can set the system property > `AsyncLoggerConfig.RingBufferSize` (see [Configuring Properties](https://docs.mulesoft.com/mule-runtime/latest/configuring-properties)). `20000` > is the suggested value, but you need to tune it to meet your needs. ### Performance Tests The chart below shows the performance difference between synchronous and asynchronous logging, and how much latency increased as more concurrent messages were added. In this test, an app logged about one million messages, using an increasingly higher amount of threads on each run. Each transaction resulted in 1000 messages. ![A line chart comparing latency versus concurrency](/mulesoft/current/en-us/mule-runtime/latest/_images/logging-latency-vs-concurrency.png) As indicated by the chart, the results of logging asynchronously are significantly closer to the results of not logging at all. ## Configuring Custom Logging Settings By default, logging in Mule is done asynchronously and at a level greater than or equal to INFO. The default log level discards log messages at the DEBUG or TRACE level. To change this behavior, edit the `log4j2.xml` file, for example, to use synchronous logging, change the log level, or define custom logger categories. For the runtime, this file is `$MULE_HOME/conf/log4j2.xml`. If you don’t edit this file, Mule uses the default configuration. In Anypoint Studio, `log4j2.xml` appears in the `src/main/resources` path of each Mule project. The default configuration defines all loggers, including the root logger, as asynchronous. You can override this configuration at the domain or app level. To use a custom configuration file at the app level, add a `logConfigFile` entry to the `mule-artifact.json` file. The path is relative to the root of the app. For example: ```json { "minMuleVersion": "4.0.0", "logConfigFile": "custom-log4j2.xml" } ``` ### Change the Log Level To change the log level, modify the `level` value of the logger for the package you want to configure. For example, to change the runtime log level, modify these loggers in the `log4j2.xml` file: ```xml ``` Accepted values, from most to least verbose, are: `TRACE`, `DEBUG`, `INFO`, `WARN`, and `ERROR`. To change the log level only for specific connectors, see [Enable Verbose Logging](https://docs.mulesoft.com/mule-runtime/latest/enable-verbose-logging). ### Use Synchronous Logging To log synchronously, use the `Logger` and `Root` elements instead of `AsyncLogger` and `AsyncRoot` in your `log4j2.xml` file. This example makes all logging synchronous: ```xml ``` ### Default Configuration The following is the default configuration for the `log4j2.xml` file: ```xml ``` ## Configuring Logs for the Runtime Manager Agent > [!NOTE] This configuration is only valid when using the Runtime Manager agent 1.5.2 and later. To log the Runtime Manager Agent state in a location other than the default `mule_agent.log` file, configure the `$MULE_HOME/conf/log4j2.xml` file to include a new Log4j 2 Appender called `mule-agent-appender`. If included, the Runtime Manager Agent plugin uses this appender to log its state. The `log4j2.xml` file should include something like the following snippet to enable this functionality: ```xml (...) %d %p %c{1.} [%t] %m%n (...) ``` The above example makes the Runtime Manager agent log its state to a rolling log file in `$MULE_HOME/logs/custom_mule_agent.log`. The file rolls over daily, or sooner if it reaches 250 MB. For other Log4j 2 appender configurations, see the [Apache Log4j 2 Appenders documentation](https://logging.apache.org/log4j/2.x/manual/appenders.html). ## Exception Handling with Asynchronous Logging If you’re using asynchronous logging and experience a system crash that might have caused incomplete logs, the LMAX `ExceptionHandler` handler can help. By default, Mule registers this handler to log events to the disk, console, and `logs/mule_ee.log`. To provide your own exception handler, set the system property `AsyncLoggerConfig.ExceptionHandler` to the canonical name of a class that implements the interface. The default exception handler, `org.mule.runtime.module.launcher.api.log4j2.AsyncLoggerExceptionHandler`, logs the failure through the Log4j 2 `StatusLogger`. Use it as a reference for your own implementation: ```java import com.lmax.disruptor.ExceptionHandler; import org.apache.logging.log4j.status.StatusLogger; public class AsyncLoggerExceptionHandler implements ExceptionHandler { private static final StatusLogger LOGGER = StatusLogger.getLogger(); @Override public void handleEventException(Throwable ex, long sequence, Object event) { LOGGER.error("Failed to asynchronously log message: " + event, ex); } @Override public void handleOnStartException(Throwable ex) { LOGGER.error("Failed to start asynchronous logger", ex); } @Override public void handleOnShutdownException(Throwable ex) { LOGGER.error("Failed to stop asynchronous logger", ex); } } ``` There is a performance-reliability trade-off between asynchronous and synchronous logging. If the risk of losing log messages is a serious issue, then configure your loggers to be synchronous. You can have a mix of both synchronous and asynchronous logging. ## Configuration Reloading Log4j 2 can check the `log4j2.xml` file for changes at a set interval and apply them without a restart. To enable this behavior, add the `monitorInterval` attribute to the `log4j2.xml` configuration file: 1. In the Mule installation folder, open `conf/log4j2.xml`. 2. Add the `monitorInterval` attribute, in seconds, to the `` element. For example: ```xml ... ``` In this example, Log4j 2 checks for changes every 15 seconds. 3. Save the file, and restart Mule so that it loads the `monitorInterval` setting. After this restart, Log4j 2 applies later changes to `log4j2.xml` automatically within the configured interval. For more information, see the [Apache Log4j 2 Configuration documentation](https://logging.apache.org/log4j/2.x/manual/configuration.html). ## Debugging Projects that Use the HTTP Connector To debug projects that use the HTTP connector, you might want to make the logging more verbose than usual and track all of the behavior of the HTTP connector’s `http-listener` and `http-request` operations in your project. See [HTTP Connector Troubleshooting Guide](https://docs.mulesoft.com/http-connector/1.10/http-troubleshooting) for information. ## Request and Response Logging for SOAP Mule sends and receives SOAP messages over HTTP, so to log the full SOAP requests and responses of your app, enable debug logging for the HTTP message logger: 1. In Anypoint Studio, open the `log4j2.xml` file in `src/main/resources` and add the `HttpMessageLogger` logger inside the `` element: ```xml ``` 2. Save your project. ## Troubleshooting Logging I don’t see any logging output Make sure the `log4j2.xml` file is at the root of your classpath. In an Anypoint Studio project, place it in `src/main/resources`. I reconfigured Log4j 2, but nothing happened This issue happens because there is another `log4j2.xml` file on your classpath that is getting picked up before your modified one. To find out which configuration file Log4j 2 is using, add the following switch when starting Mule (or add it to the container startup script if you are embedding Mule): \-M-Dlog4j.debug=true This switch writes the Log4j 2 startup information, including the location of the configuration file being used, to `stdout`. You must remove that configuration file before your modified configuration can work. --- product: Mule Runtime version: 4.11 keywords: anypoint, studio, mule, on premises, on premise, amc, logs, stack traces, verbose --- # Configuring Mule Stack Traces > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule does not display all stack traces by default. When Mule does show stack traces, it filters out some internal class references from to produce a more readable output. You can control Mule stack trace behavior in two ways: - Use command-line arguments - Set properties in Mule Studio ## Use Command-Line Arguments Use `-M-DpropertyName` with the following command-line arguments to control the behavior of stack traces: - `mule.verbose.exceptions` - If set to **true**, Mule shows filtered stack traces. - `mule.stacktrace.filter` - A comma-separated list of packages and/or classes to remove from the stack traces, which are matched using `string.startsWith()`. > [!NOTE] These arguments are available for Mule developers and administrators to use while > troubleshooting. They are not intended for use by end users. ## Set Properties in Anypoint Studio In Studio, you can set the properties specified above to instruct Mule to provide stack traces and to filter out packages or classes to remove. To adjust these settings: 1. Select **Run** > **Run Configurations…​** 2. Define the properties to specify the behavior you want. In the example below, the `mule.verbose.exceptions` property is set to **true**. ![A configuration panel including VM arguments](/mulesoft/current/en-us/mule-runtime/4.11/_images/stack-traces-studio.png) ## Obtain the Stack Trace and Thread Dump Follow these steps to troubleshoot Mule if it stops and you need more information to find the cause: 1. Identify the Mule process ID (`MULE_PID`). 2. Retrieve the thread dump. 3. Retrieve the heap dump if the Mule server throws an Out Of Memory error: `java.lang.OutOfMemoryError: Java heap space` ### Identify the Mule process ID To identify the Mule process ID, use the Unix/Linux `ps` command, or execute the `jps` command from the terminal. The `jps` tool ships with the JDK used to run Mule. For example, a line containing `MuleContainerBootstrap`, `ApplicationDeployer`, or similar identifies the Mule process. ### Retrieve the Thread Dump Use the `jstack` tool, which is available in modern JDKs, to retrieve the thread dump: jstack -l MULE\_PID > filename.tdump ### Retrieve the Heap Dump Retrieve the heap dump if the Mule server throws an out of memory error: `java.lang.OutOfMemoryError: Java heap space` The Oracle JVM provides a JVM modifier to gather this information. You must restart the Mule server after applying this change and reproduce the out of memory error one more time. To apply this modifier to the JVM that Mule uses, set the following parameters in Mule’s `/conf/wrapper.conf` file to automatically trigger the creation of a heap dump: wrapper.java.additional.=-XX:+HeapDumpOnOutOfMemoryError wrapper.java.additional.=-XX:HeapDumpPath=path/to/dumps When you set the parameters, change to a number that follows the sequence in `wrapper.conf`. > [!NOTE] By default, Mule includes the `HeapDumpOnOutOfMemoryError` property, but it does not > define a path for heap dumps. If no path is defined for a heap dump, the file is created in the directory where the java process was launched. The heap dump file is then generated as `java_pid.hprof.`. --- product: Mule Runtime version: 4.12 keywords: anypoint, studio, mule, on premises, on premise, amc, logs, stack traces, verbose --- # Configuring Mule Stack Traces > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule does not display all stack traces by default. When Mule does show stack traces, it filters out some internal class references from to produce a more readable output. You can control Mule stack trace behavior in two ways: - Use command-line arguments - Set properties in Mule Studio ## Use Command-Line Arguments Use `-M-DpropertyName` with the following command-line arguments to control the behavior of stack traces: - `mule.verbose.exceptions` - If set to **true**, Mule shows filtered stack traces. - `mule.stacktrace.filter` - A comma-separated list of packages and/or classes to remove from the stack traces, which are matched using `string.startsWith()`. > [!NOTE] These arguments are available for Mule developers and administrators to use while > troubleshooting. They are not intended for use by end users. ## Set Properties in Anypoint Studio In Studio, you can set the properties specified above to instruct Mule to provide stack traces and to filter out packages or classes to remove. To adjust these settings: 1. Select **Run** > **Run Configurations…​** 2. Define the properties to specify the behavior you want. In the example below, the `mule.verbose.exceptions` property is set to **true**. ![A configuration panel including VM arguments](/mulesoft/current/en-us/mule-runtime/4.12/_images/stack-traces-studio.png) ## Obtain the Stack Trace and Thread Dump Follow these steps to troubleshoot Mule if it stops and you need more information to find the cause: 1. Identify the Mule process ID (`MULE_PID`). 2. Retrieve the thread dump. 3. Retrieve the heap dump if the Mule server throws an Out Of Memory error: `java.lang.OutOfMemoryError: Java heap space` ### Identify the Mule process ID To identify the Mule process ID, use the Unix/Linux `ps` command, or execute the `jps` command from the terminal. The `jps` tool ships with the JDK used to run Mule. For example, a line containing `MuleContainerBootstrap`, `ApplicationDeployer`, or similar identifies the Mule process. ### Retrieve the Thread Dump Use the `jstack` tool, which is available in modern JDKs, to retrieve the thread dump: jstack -l MULE\_PID > filename.tdump ### Retrieve the Heap Dump Retrieve the heap dump if the Mule server throws an out of memory error: `java.lang.OutOfMemoryError: Java heap space` The Oracle JVM provides a JVM modifier to gather this information. You must restart the Mule server after applying this change and reproduce the out of memory error one more time. To apply this modifier to the JVM that Mule uses, set the following parameters in Mule’s `/conf/wrapper.conf` file to automatically trigger the creation of a heap dump: wrapper.java.additional.=-XX:+HeapDumpOnOutOfMemoryError wrapper.java.additional.=-XX:HeapDumpPath=path/to/dumps When you set the parameters, change to a number that follows the sequence in `wrapper.conf`. > [!NOTE] By default, Mule includes the `HeapDumpOnOutOfMemoryError` property, but it does not > define a path for heap dumps. If no path is defined for a heap dump, the file is created in the directory where the java process was launched. The heap dump file is then generated as `java_pid.hprof.`. --- product: Mule Runtime version: 4.3 keywords: anypoint, studio, mule, on premises, on premise, amc, logs, stack traces, verbose --- # Configuring Mule Stack Traces > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule does not display all stack traces by default. When Mule does show stack traces, it filters out some internal class references from to produce a more readable output. You can control Mule stack trace behavior in two ways: - Use command-line arguments - Set properties in Mule Studio ## Use Command-Line Arguments Use `-M-DpropertyName` with the following command-line arguments to control the behavior of stack traces: - `mule.verbose.exceptions` - If set to **true**, Mule shows filtered stack traces. - `mule.stacktrace.filter` - A comma-separated list of packages and/or classes to remove from the stack traces, which are matched using `string.startsWith()`. > [!NOTE] These arguments are available for Mule developers and administrators to use while > troubleshooting. They are not intended for use by end users. ## Set Properties in Anypoint Studio In Studio, you can set the properties specified above to instruct Mule to provide stack traces and to filter out packages or classes to remove. To adjust these settings: 1. Select **Run** > **Run Configurations…​** 2. Define the properties to specify the behavior you want. In the example below, the `mule.verbose.exceptions` property is set to **true**. ![Studio-config-stacktrace](/mulesoft/current/en-us/mule-runtime/4.3/_images/stack-traces-studio.png) ## Obtain the Stack Trace and Thread Dump Follow these steps to troubleshoot Mule if it stops and you need more information to find the cause: 1. Identify the Mule process ID (`MULE_PID`). 2. Retrieve the thread dump. 3. Retrieve the heap dump if the Mule server throws an Out Of Memory error: `java.lang.OutOfMemoryError: Java heap space` ### Identify the Mule process ID To identify the Mule process ID, use the Unix/Linux `ps` command, or execute the `jps` command from the terminal. The `jps` tool ships with the JDK used to run Mule. For example, a line containing `MuleContainerBootstrap`, `ApplicationDeployer`, or similar identifies the Mule process. ### Retrieve the Thread Dump Use the `jstack` tool, which is available in modern JDKs, to retrieve the thread dump: jstack -l MULE\_PID > filename.tdump ### Retrieve the Heap Dump Retrieve the heap dump if the Mule server throws an out of memory error: `java.lang.OutOfMemoryError: Java heap space` The Oracle JVM provides a JVM modifier to gather this information. You must restart the Mule server after applying this change and reproduce the out of memory error one more time. To apply this modifier to the JVM that Mule uses, set the following parameters in Mule’s `/conf/wrapper.conf` file to automatically trigger the creation of a heap dump: wrapper.java.additional.=-XX:+HeapDumpOnOutOfMemoryError wrapper.java.additional.=-XX:HeapDumpPath=path/to/dumps When you set the parameters, change to a number that follows the sequence in `wrapper.conf`. > [!NOTE] By default, Mule includes the `HeapDumpOnOutOfMemoryError` property, but it does not > define a path for heap dumps. If no path is defined for a heap dump, the file is created in the directory where the java process was launched. The heap dump file is then generated as `java_pid.hprof.`. --- product: Mule Runtime version: 4.4 keywords: anypoint, studio, mule, on premises, on premise, amc, logs, stack traces, verbose --- # Configuring Mule Stack Traces > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule does not display all stack traces by default. When Mule does show stack traces, it filters out some internal class references from to produce a more readable output. You can control Mule stack trace behavior in two ways: - Use command-line arguments - Set properties in Mule Studio ## Use Command-Line Arguments Use `-M-DpropertyName` with the following command-line arguments to control the behavior of stack traces: - `mule.verbose.exceptions` - If set to **true**, Mule shows filtered stack traces. - `mule.stacktrace.filter` - A comma-separated list of packages and/or classes to remove from the stack traces, which are matched using `string.startsWith()`. > [!NOTE] These arguments are available for Mule developers and administrators to use while > troubleshooting. They are not intended for use by end users. ## Set Properties in Anypoint Studio In Studio, you can set the properties specified above to instruct Mule to provide stack traces and to filter out packages or classes to remove. To adjust these settings: 1. Select **Run** > **Run Configurations…​** 2. Define the properties to specify the behavior you want. In the example below, the `mule.verbose.exceptions` property is set to **true**. ![Studio-config-stacktrace](/mulesoft/current/en-us/mule-runtime/4.4/_images/stack-traces-studio.png) ## Obtain the Stack Trace and Thread Dump Follow these steps to troubleshoot Mule if it stops and you need more information to find the cause: 1. Identify the Mule process ID (`MULE_PID`). 2. Retrieve the thread dump. 3. Retrieve the heap dump if the Mule server throws an Out Of Memory error: `java.lang.OutOfMemoryError: Java heap space` ### Identify the Mule process ID To identify the Mule process ID, use the Unix/Linux `ps` command, or execute the `jps` command from the terminal. The `jps` tool ships with the JDK used to run Mule. For example, a line containing `MuleContainerBootstrap`, `ApplicationDeployer`, or similar identifies the Mule process. ### Retrieve the Thread Dump Use the `jstack` tool, which is available in modern JDKs, to retrieve the thread dump: jstack -l MULE\_PID > filename.tdump ### Retrieve the Heap Dump Retrieve the heap dump if the Mule server throws an out of memory error: `java.lang.OutOfMemoryError: Java heap space` The Oracle JVM provides a JVM modifier to gather this information. You must restart the Mule server after applying this change and reproduce the out of memory error one more time. To apply this modifier to the JVM that Mule uses, set the following parameters in Mule’s `/conf/wrapper.conf` file to automatically trigger the creation of a heap dump: wrapper.java.additional.=-XX:+HeapDumpOnOutOfMemoryError wrapper.java.additional.=-XX:HeapDumpPath=path/to/dumps When you set the parameters, change to a number that follows the sequence in `wrapper.conf`. > [!NOTE] By default, Mule includes the `HeapDumpOnOutOfMemoryError` property, but it does not > define a path for heap dumps. If no path is defined for a heap dump, the file is created in the directory where the java process was launched. The heap dump file is then generated as `java_pid.hprof.`. --- product: Mule Runtime version: 4.6 keywords: anypoint, studio, mule, on premises, on premise, amc, logs, stack traces, verbose --- # Configuring Mule Stack Traces > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule does not display all stack traces by default. When Mule does show stack traces, it filters out some internal class references from to produce a more readable output. You can control Mule stack trace behavior in two ways: - Use command-line arguments - Set properties in Mule Studio ## Use Command-Line Arguments Use `-M-DpropertyName` with the following command-line arguments to control the behavior of stack traces: - `mule.verbose.exceptions` - If set to **true**, Mule shows filtered stack traces. - `mule.stacktrace.filter` - A comma-separated list of packages and/or classes to remove from the stack traces, which are matched using `string.startsWith()`. > [!NOTE] These arguments are available for Mule developers and administrators to use while > troubleshooting. They are not intended for use by end users. ## Set Properties in Anypoint Studio In Studio, you can set the properties specified above to instruct Mule to provide stack traces and to filter out packages or classes to remove. To adjust these settings: 1. Select **Run** > **Run Configurations…​** 2. Define the properties to specify the behavior you want. In the example below, the `mule.verbose.exceptions` property is set to **true**. ![Studio-config-stacktrace](/mulesoft/current/en-us/mule-runtime/4.6/_images/stack-traces-studio.png) ## Obtain the Stack Trace and Thread Dump Follow these steps to troubleshoot Mule if it stops and you need more information to find the cause: 1. Identify the Mule process ID (`MULE_PID`). 2. Retrieve the thread dump. 3. Retrieve the heap dump if the Mule server throws an Out Of Memory error: `java.lang.OutOfMemoryError: Java heap space` ### Identify the Mule process ID To identify the Mule process ID, use the Unix/Linux `ps` command, or execute the `jps` command from the terminal. The `jps` tool ships with the JDK used to run Mule. For example, a line containing `MuleContainerBootstrap`, `ApplicationDeployer`, or similar identifies the Mule process. ### Retrieve the Thread Dump Use the `jstack` tool, which is available in modern JDKs, to retrieve the thread dump: jstack -l MULE\_PID > filename.tdump ### Retrieve the Heap Dump Retrieve the heap dump if the Mule server throws an out of memory error: `java.lang.OutOfMemoryError: Java heap space` The Oracle JVM provides a JVM modifier to gather this information. You must restart the Mule server after applying this change and reproduce the out of memory error one more time. To apply this modifier to the JVM that Mule uses, set the following parameters in Mule’s `/conf/wrapper.conf` file to automatically trigger the creation of a heap dump: wrapper.java.additional.=-XX:+HeapDumpOnOutOfMemoryError wrapper.java.additional.=-XX:HeapDumpPath=path/to/dumps When you set the parameters, change to a number that follows the sequence in `wrapper.conf`. > [!NOTE] By default, Mule includes the `HeapDumpOnOutOfMemoryError` property, but it does not > define a path for heap dumps. If no path is defined for a heap dump, the file is created in the directory where the java process was launched. The heap dump file is then generated as `java_pid.hprof.`. --- product: Mule Runtime version: 4.9 keywords: anypoint, studio, mule, on premises, on premise, amc, logs, stack traces, verbose --- # Configuring Mule Stack Traces > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule does not display all stack traces by default. When Mule does show stack traces, it filters out some internal class references from to produce a more readable output. You can control Mule stack trace behavior in two ways: - Use command-line arguments - Set properties in Mule Studio ## Use Command-Line Arguments Use `-M-DpropertyName` with the following command-line arguments to control the behavior of stack traces: - `mule.verbose.exceptions` - If set to **true**, Mule shows filtered stack traces. - `mule.stacktrace.filter` - A comma-separated list of packages and/or classes to remove from the stack traces, which are matched using `string.startsWith()`. > [!NOTE] These arguments are available for Mule developers and administrators to use while > troubleshooting. They are not intended for use by end users. ## Set Properties in Anypoint Studio In Studio, you can set the properties specified above to instruct Mule to provide stack traces and to filter out packages or classes to remove. To adjust these settings: 1. Select **Run** > **Run Configurations…​** 2. Define the properties to specify the behavior you want. In the example below, the `mule.verbose.exceptions` property is set to **true**. ![A configuration panel including VM arguments](/mulesoft/current/en-us/mule-runtime/4.9/_images/stack-traces-studio.png) ## Obtain the Stack Trace and Thread Dump Follow these steps to troubleshoot Mule if it stops and you need more information to find the cause: 1. Identify the Mule process ID (`MULE_PID`). 2. Retrieve the thread dump. 3. Retrieve the heap dump if the Mule server throws an Out Of Memory error: `java.lang.OutOfMemoryError: Java heap space` ### Identify the Mule process ID To identify the Mule process ID, use the Unix/Linux `ps` command, or execute the `jps` command from the terminal. The `jps` tool ships with the JDK used to run Mule. For example, a line containing `MuleContainerBootstrap`, `ApplicationDeployer`, or similar identifies the Mule process. ### Retrieve the Thread Dump Use the `jstack` tool, which is available in modern JDKs, to retrieve the thread dump: jstack -l MULE\_PID > filename.tdump ### Retrieve the Heap Dump Retrieve the heap dump if the Mule server throws an out of memory error: `java.lang.OutOfMemoryError: Java heap space` The Oracle JVM provides a JVM modifier to gather this information. You must restart the Mule server after applying this change and reproduce the out of memory error one more time. To apply this modifier to the JVM that Mule uses, set the following parameters in Mule’s `/conf/wrapper.conf` file to automatically trigger the creation of a heap dump: wrapper.java.additional.=-XX:+HeapDumpOnOutOfMemoryError wrapper.java.additional.=-XX:HeapDumpPath=path/to/dumps When you set the parameters, change to a number that follows the sequence in `wrapper.conf`. > [!NOTE] By default, Mule includes the `HeapDumpOnOutOfMemoryError` property, but it does not > define a path for heap dumps. If no path is defined for a heap dump, the file is created in the directory where the java process was launched. The heap dump file is then generated as `java_pid.hprof.`. --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: anypoint, studio, mule, on premises, on premise, amc, logs, stack traces, verbose --- # Configuring Mule Stack Traces > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule does not display all stack traces by default. When Mule does show stack traces, it filters out some internal class references from to produce a more readable output. You can control Mule stack trace behavior in two ways: - Use command-line arguments - Set properties in Mule Studio ## Use Command-Line Arguments Use `-M-DpropertyName` with the following command-line arguments to control the behavior of stack traces: - `mule.verbose.exceptions` - If set to **true**, Mule shows filtered stack traces. - `mule.stacktrace.filter` - A comma-separated list of packages and/or classes to remove from the stack traces, which are matched using `string.startsWith()`. > [!NOTE] These arguments are available for Mule developers and administrators to use while > troubleshooting. They are not intended for use by end users. ## Set Properties in Anypoint Studio In Studio, you can set the properties specified above to instruct Mule to provide stack traces and to filter out packages or classes to remove. To adjust these settings: 1. Select **Run** > **Run Configurations…​** 2. Define the properties to specify the behavior you want. In the example below, the `mule.verbose.exceptions` property is set to **true**. ![A configuration panel including VM arguments](/mulesoft/current/en-us/mule-runtime/latest/_images/stack-traces-studio.png) ## Obtain the Stack Trace and Thread Dump Follow these steps to troubleshoot Mule if it stops and you need more information to find the cause: 1. Identify the Mule process ID (`MULE_PID`). 2. Retrieve the thread dump. 3. Retrieve the heap dump if the Mule server throws an Out Of Memory error: `java.lang.OutOfMemoryError: Java heap space` ### Identify the Mule process ID To identify the Mule process ID, use the Unix/Linux `ps` command, or execute the `jps` command from the terminal. The `jps` tool ships with the JDK used to run Mule. For example, a line containing `MuleContainerBootstrap`, `ApplicationDeployer`, or similar identifies the Mule process. ### Retrieve the Thread Dump Use the `jstack` tool, which is available in modern JDKs, to retrieve the thread dump: jstack -l MULE\_PID > filename.tdump ### Retrieve the Heap Dump Retrieve the heap dump if the Mule server throws an out of memory error: `java.lang.OutOfMemoryError: Java heap space` The Oracle JVM provides a JVM modifier to gather this information. You must restart the Mule server after applying this change and reproduce the out of memory error one more time. To apply this modifier to the JVM that Mule uses, set the following parameters in Mule’s `/conf/wrapper.conf` file to automatically trigger the creation of a heap dump: wrapper.java.additional.=-XX:+HeapDumpOnOutOfMemoryError wrapper.java.additional.=-XX:HeapDumpPath=path/to/dumps When you set the parameters, change to a number that follows the sequence in `wrapper.conf`. > [!NOTE] By default, Mule includes the `HeapDumpOnOutOfMemoryError` property, but it does not > define a path for heap dumps. If no path is defined for a heap dump, the file is created in the directory where the java process was launched. The heap dump file is then generated as `java_pid.hprof.`. --- product: Mule Runtime version: 4.11 --- # Configuring Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure properties, such as property placeholders and system properties. ## Property Placeholders You can use [Ant](https://ant.apache.org/)\-style property placeholders in your Mule configuration. For example: ```xml ``` The values for these placeholders can be made available in a variety of ways, as described in the sections that follow. You can also escape the resolution of property placeholder values: ```xml ``` Instead of returning the value of the property, the Logger component returns the string `"${property.value}"`. You can also use the escape character `\` to escape the resolution of the property prefix (the `${` character sequence). ## Global Properties You can use the `` element to set a placeholder value from within your Mule configuration, such as from within another Mule configuration file. You can use the global property syntax to reference the values from a `.yaml` or `.properties` file, and create new (global) properties that depends on configuration properties, or secure configuration properties. To reference configuration properties, read the section on properties files. ```xml ``` ## Properties Files To load properties from a custom file, you can place your custom properties file at `src/main/resources` and use the tag ``: ```xml ``` To load multiple properties files simply define a `` tag for each file you want to load. - If a property is defined in more than one file referenced in `` tags, the first definition will be preserved. These files must be located at `src/main/resources`, inside your Mule project, or you can also use absolute paths. ## Supported Files The Configuration Properties support both YAML configuration files (`.yaml`) and Properties configuration files (`.properties`). `String` is the only supported type in both file formats. Use the format that you find easier to read and edit. YAML file example: ```xml ``` Where `ports.yaml` is: ```yaml smtp: port: "8957" http: port: "8081" ``` Properties file example: ```xml ``` Where `ports.properties` is: ```xml smtp.port=8957 http.port=8081 ``` ## File Properties The placeholder value can also be the entire content of the file. The placeholder value becomes the string value, for example: properties-file.txt Some content ```xml ``` The payload’s value becomes `"Some content"`. Just like other properties files, these files must be located in `src/main/resources`, inside your Mule project. Absolute paths can also be used. This practice is useful for modularizing the configuration file: You can extract large contents from the config file, SQL queries, or transformations to make the config file clearer, and you can reuse the contents. ## System Properties You can set JDK system properties when running Mule On-Premises, and later use these properties to configure components or modules in a Mule application. There are two ways to specify properties: - From the command line, when starting the Mule instance: mule -M-Dsmtp.username=JSmith -M-Dsmtp.password=ChangeMe - Editing the `wrapper.conf` file located in the `$MULE_HOME/conf` directory, adding entries for each property: wrapper.java.additional.999=-Dsmtp.username=JSmith wrapper.java.additional.1000=-Dsmtp.password=ChangeMe See [System Properties](https://docs.mulesoft.com/mule-runtime/4.11/mule-app-properties-system#set-properties) for additional configuration details. ## Custom Properties Provider It is possible to create a custom properties provider implementation using the Mule API. See [Custom Configuration Properties Provider](https://docs.mulesoft.com/mule-runtime/4.11/custom-configuration-properties-provider) for more details. ### Setting System Properties in Anypoint Studio You can add properties when you launch your project on Anypoint Studio, through the Run Configurations menu: 1. Right-click your project in Package Explorer. 2. Click **Run As** > **Run Configurations**. 3. Pick the **Arguments** tab. 4. Add your arguments to the **VM arguments** field, preceding property names with **\-D**: ![Arguments tab showing settings for JVM arguments in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/arguments-tab.png) Your properties are now available each time you deploy your app through Studio. You can then reference them with the following syntax: ```xml ``` ## Environment Variables Environment variables can be defined in various different ways, there are also several ways to access these from your apps. Regardless of how an environment variable is defined, the recommended way to reference it is through the following syntax: ${variableName} ### Environment Variables From the OS To reference a variable that is defined in the OS, you can simply use the following syntax: ```xml ``` ### Setting Environment Variables in Anypoint Studio You can set variables in Studio through the Run Configuration menu: 1. Right-click your project in Package Explorer. 2. Select **Run As** > **Run Configurations**. 3. Pick the Environment tab. 4. Click the **New** button and assign your variable a name and value. ![An Environment tab with options including New](/mulesoft/current/en-us/mule-runtime/4.11/_images/environment-tab.png) Your variable is now available each time you deploy through Studio. You can reference it with the following syntax: ```xml ``` > [!NOTE] The syntax is the same for referencing variables defined in the OS and variables defined > in Studio. You can select if variables defined in Studio replace variables with the same name > defined in the OS or not, by checking the corresponding radio button in the UI when creating the > variables. ![An Environment tab with options to define variables](/mulesoft/current/en-us/mule-runtime/4.11/_images/environment-tab2.png) ## Setting the Properties File Dynamically A common configuration use case is to set the file to depend on a property (for example, `env`) to determine which file to use, for example, to use a `development-properties` file in development stage or a production file. ```xml ``` This way, the value of the property `env` determines which file to use to load the configuration properties. That `env` property can be set by a global property, system property, or environment property. You can use global properties as a way to define default values for configuration properties. System and environment properties with the same name as a global property will override that global property. ```xml ``` This way, the default value for the `env` property is `dev`, which can still be overridden with a system or environment property. Please note that this configuration is **required** for metadata resolution in Anypoint Studio. If you do not define default values for the properties that are passed through the command line, you receive an error while creating an application model for all message processors that depend on them. Another thing to consider is that placeholders of a configuration property setting cannot depend on the properties loaded from another configuration property. In the example above, the property `env` couldn’t have been defined in a configuration property. The example below **is not correct**: ```xml ``` This also includes other type of properties, such as Secure Configuration Properties or Custom Configuration Properties. ## Setting Properties Values in Runtime Manager If you deploy your application to [Runtime Manager](https://docs.mulesoft.com/runtime-manager/), you can also set properties through the Runtime Manager console. These can be defined when [Deploying to CloudHub](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub), or on an [already running application](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub). To create an environment variable or application property: 1. Log in to your Anypoint Platform account. 2. Click Runtime Manager. 3. Either click **Deploy Application** to deploy a new application, or select a running application and click **Manage Application**. 4. Select the **Properties** tab in the **Settings** section. See [Managing Applications on CloudHub](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub) and [Secure Application Properties](https://docs.mulesoft.com/cloudhub/secure-application-properties) for more details. ## Properties Hierarchy Configuration properties can be overwritten. The Mule runtime engine uses the following hierarchy to determine which properties take precedence if they have the same name. In this hierarchy, deployment properties are at the top, so they take precedence over the other types of properties. 1. Deployment properties 2. System properties 3. Environment properties 4. Application properties (includes configuration properties, secure configuration properties, and other custom configuration properties) 5. Global Properties So, for example, if a configuration property named `size` is defined as a system property, and there is also an application configuration property named `size`, the value for the application is the value of the property with the most precedence (in this case, the system property). Also, a property can derive its value from other properties that are higher in the hierarchy. Therefore, an application property can derive its value from environment, system, and deployment properties. A system property can derive its value from a deployment property, and so on. For example, if there is a system property named `env`, an application configuration property can have the value `file.${env}.xml`. However, an application property cannot depend on an application property’s value unless it’s defined in the same file. For example, a Secure Configuration property cannot depend on a Configuration property. Because of this hierarchical structure, Mule components that load files cannot depend on an application or a global property. Mule runtime engine loads both, the component and the application property, at the same hierarchy. For example, if Mule loads an `import` component before loading the application property, the deployment fails because the property is not resolved by the time the `import` component needs to load. ## Built-in Properties Mule runtime engine defines internal Application properties and assigns a value to them based on the configuration of the Mule instance and the deployed applications:
PropertyDescription

app.home

The path to the Mule application /home directory

app.name

The name of the Mule application

domain.name

The name of the Domain

api.name

The name of the API

mule.home

The path to the Mule instance /home directory

Do not overwrite any of these properties; Mule uses some of these values internally and overwriting them might cause unexpected behaviors. --- product: Mule Runtime version: 4.12 --- # Configuring Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure properties, such as property placeholders and system properties. ## Property Placeholders You can use [Ant](https://ant.apache.org/)\-style property placeholders in your Mule configuration. For example: ```xml ``` The values for these placeholders can be made available in a variety of ways, as described in the sections that follow. You can also escape the resolution of property placeholder values: ```xml ``` Instead of returning the value of the property, the Logger component returns the string `"${property.value}"`. You can also use the escape character `\` to escape the resolution of the property prefix (the `${` character sequence). ## Global Properties You can use the `` element to set a placeholder value from within your Mule configuration, such as from within another Mule configuration file. You can use the global property syntax to reference the values from a `.yaml` or `.properties` file, and create new (global) properties that depends on configuration properties, or secure configuration properties. To reference configuration properties, read the section on properties files. ```xml ``` ## Properties Files To load properties from a custom file, you can place your custom properties file at `src/main/resources` and use the tag ``: ```xml ``` To load multiple properties files simply define a `` tag for each file you want to load. - If a property is defined in more than one file referenced in `` tags, the first definition will be preserved. These files must be located at `src/main/resources`, inside your Mule project, or you can also use absolute paths. ## Supported Files The Configuration Properties support both YAML configuration files (`.yaml`) and Properties configuration files (`.properties`). `String` is the only supported type in both file formats. Use the format that you find easier to read and edit. YAML file example: ```xml ``` Where `ports.yaml` is: ```yaml smtp: port: "8957" http: port: "8081" ``` Properties file example: ```xml ``` Where `ports.properties` is: ```xml smtp.port=8957 http.port=8081 ``` ## File Properties The placeholder value can also be the entire content of the file. The placeholder value becomes the string value, for example: properties-file.txt Some content ```xml ``` The payload’s value becomes `"Some content"`. Just like other properties files, these files must be located in `src/main/resources`, inside your Mule project. Absolute paths can also be used. This practice is useful for modularizing the configuration file: You can extract large contents from the config file, SQL queries, or transformations to make the config file clearer, and you can reuse the contents. ## System Properties You can set JDK system properties when running Mule On-Premises, and later use these properties to configure components or modules in a Mule application. There are two ways to specify properties: - From the command line, when starting the Mule instance: mule -M-Dsmtp.username=JSmith -M-Dsmtp.password=ChangeMe - Editing the `wrapper.conf` file located in the `$MULE_HOME/conf` directory, adding entries for each property: wrapper.java.additional.999=-Dsmtp.username=JSmith wrapper.java.additional.1000=-Dsmtp.password=ChangeMe See [System Properties](https://docs.mulesoft.com/mule-runtime/4.12/mule-app-properties-system#set-properties) for additional configuration details. ## Custom Properties Provider It is possible to create a custom properties provider implementation using the Mule API. See [Custom Configuration Properties Provider](https://docs.mulesoft.com/mule-runtime/4.12/custom-configuration-properties-provider) for more details. ### Setting System Properties in Anypoint Studio You can add properties when you launch your project on Anypoint Studio, through the Run Configurations menu: 1. Right-click your project in Package Explorer. 2. Click **Run As** > **Run Configurations**. 3. Pick the **Arguments** tab. 4. Add your arguments to the **VM arguments** field, preceding property names with **\-D**: ![Arguments tab showing settings for JVM arguments in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/arguments-tab.png) Your properties are now available each time you deploy your app through Studio. You can then reference them with the following syntax: ```xml ``` ## Environment Variables Environment variables can be defined in various different ways, there are also several ways to access these from your apps. Regardless of how an environment variable is defined, the recommended way to reference it is through the following syntax: ${variableName} ### Environment Variables From the OS To reference a variable that is defined in the OS, you can simply use the following syntax: ```xml ``` ### Setting Environment Variables in Anypoint Studio You can set variables in Studio through the Run Configuration menu: 1. Right-click your project in Package Explorer. 2. Select **Run As** > **Run Configurations**. 3. Pick the Environment tab. 4. Click the **New** button and assign your variable a name and value. ![An Environment tab with options including New](/mulesoft/current/en-us/mule-runtime/4.12/_images/environment-tab.png) Your variable is now available each time you deploy through Studio. You can reference it with the following syntax: ```xml ``` > [!NOTE] The syntax is the same for referencing variables defined in the OS and variables defined > in Studio. You can select if variables defined in Studio replace variables with the same name > defined in the OS or not, by checking the corresponding radio button in the UI when creating the > variables. ![An Environment tab with options to define variables](/mulesoft/current/en-us/mule-runtime/4.12/_images/environment-tab2.png) ## Setting the Properties File Dynamically A common configuration use case is to set the file to depend on a property (for example, `env`) to determine which file to use, for example, to use a `development-properties` file in development stage or a production file. ```xml ``` This way, the value of the property `env` determines which file to use to load the configuration properties. That `env` property can be set by a global property, system property, or environment property. You can use global properties as a way to define default values for configuration properties. System and environment properties with the same name as a global property will override that global property. ```xml ``` This way, the default value for the `env` property is `dev`, which can still be overridden with a system or environment property. Please note that this configuration is **required** for metadata resolution in Anypoint Studio. If you do not define default values for the properties that are passed through the command line, you receive an error while creating an application model for all message processors that depend on them. Another thing to consider is that placeholders of a configuration property setting cannot depend on the properties loaded from another configuration property. In the example above, the property `env` couldn’t have been defined in a configuration property. The example below **is not correct**: ```xml ``` This also includes other type of properties, such as Secure Configuration Properties or Custom Configuration Properties. ## Setting Properties Values in Runtime Manager If you deploy your application to [Runtime Manager](https://docs.mulesoft.com/runtime-manager/), you can also set properties through the Runtime Manager console. These can be defined when [Deploying to CloudHub](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub), or on an [already running application](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub). To create an environment variable or application property: 1. Log in to your Anypoint Platform account. 2. Click Runtime Manager. 3. Either click **Deploy Application** to deploy a new application, or select a running application and click **Manage Application**. 4. Select the **Properties** tab in the **Settings** section. See [Managing Applications on CloudHub](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub) and [Secure Application Properties](https://docs.mulesoft.com/cloudhub/secure-application-properties) for more details. ## Properties Hierarchy Configuration properties can be overwritten. The Mule runtime engine uses the following hierarchy to determine which properties take precedence if they have the same name. In this hierarchy, deployment properties are at the top, so they take precedence over the other types of properties. 1. Deployment properties 2. System properties 3. Environment properties 4. Application properties (includes configuration properties, secure configuration properties, and other custom configuration properties) 5. Global Properties So, for example, if a configuration property named `size` is defined as a system property, and there is also an application configuration property named `size`, the value for the application is the value of the property with the most precedence (in this case, the system property). Also, a property can derive its value from other properties that are higher in the hierarchy. Therefore, an application property can derive its value from environment, system, and deployment properties. A system property can derive its value from a deployment property, and so on. For example, if there is a system property named `env`, an application configuration property can have the value `file.${env}.xml`. However, an application property cannot depend on an application property’s value unless it’s defined in the same file. For example, a Secure Configuration property cannot depend on a Configuration property. Because of this hierarchical structure, Mule components that load files cannot depend on an application or a global property. Mule runtime engine loads both, the component and the application property, at the same hierarchy. For example, if Mule loads an `import` component before loading the application property, the deployment fails because the property is not resolved by the time the `import` component needs to load. ## Built-in Properties Mule runtime engine defines internal Application properties and assigns a value to them based on the configuration of the Mule instance and the deployed applications:
PropertyDescription

app.home

The path to the Mule application /home directory

app.name

The name of the Mule application

domain.name

The name of the Domain

api.name

The name of the API

mule.home

The path to the Mule instance /home directory

Do not overwrite any of these properties; Mule uses some of these values internally and overwriting them might cause unexpected behaviors. --- product: Mule Runtime version: 4.3 --- # Configuring Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure properties, such as property placeholders and system properties. ## Property Placeholders You can use [Ant](https://ant.apache.org/)\-style property placeholders in your Mule configuration. For example: ```xml ``` The values for these placeholders can be made available in a variety of ways, as described in the sections that follow. You can also escape the resolution of property placeholder values: ```xml ``` Instead of returning the value of the property, the Logger component returns the string `"${property.value}"`. You can also use the escape character `\` to escape the resolution of the property prefix (the `${` character sequence). ## Global Properties You can use the `` element to set a placeholder value from within your Mule configuration, such as from within another Mule configuration file. You can use the global property syntax to reference the values from a `.yaml` or `.properties` file, and create new (global) properties that depends on configuration properties, or secure configuration properties. To reference configuration properties, read the section on properties files. ```xml ``` ## Properties Files To load properties from a custom file, you can place your custom properties file at `src/main/resources` and use the tag ``: ```xml ``` To load multiple properties files simply define a `` tag for each file you want to load. - If a property is defined in more than one file referenced in `` tags, the first definition will be preserved. These files must be located at `src/main/resources`, inside your Mule project, or you can also use absolute paths. ## Supported Files The Configuration Properties support both YAML configuration files (`.yaml`) and Properties configuration files (`.properties`). `String` is the only supported type in both file formats. Use the format that you find easier to read and edit. YAML file example: ```xml ``` Where `ports.yaml` is: ```yaml smtp: port: "8957" http: port: "8081" ``` Properties file example: ```xml ``` Where `ports.properties` is: ```xml smtp.port=8957 http.port=8081 ``` ## File Properties The placeholder value can also be the entire content of the file. The placeholder value becomes the string value, for example: properties-file.txt Some content ```xml ``` The payload’s value becomes `"Some content"`. Just like other properties files, these files must be located in `src/main/resources`, inside your Mule project. Absolute paths can also be used. This practice is useful for modularizing the configuration file: You can extract large contents from the config file, SQL queries, or transformations to make the config file clearer, and you can reuse the contents. ## System Properties You can set JDK system properties when running Mule On-Premises, and later use these properties to configure components or modules in a Mule application. There are two ways to specify properties: - From the command line, when starting the Mule instance: mule -M-Dsmtp.username=JSmith -M-Dsmtp.password=ChangeMe - Editing the `wrapper.conf` file located in the `$MULE_HOME/conf` directory, adding entries for each property: wrapper.java.additional.999=-Dsmtp.username=JSmith wrapper.java.additional.1000=-Dsmtp.password=ChangeMe See [System Properties](https://docs.mulesoft.com/mule-runtime/4.3/mule-app-properties-system#set-properties) for additional configuration details. ## Custom Properties Provider It is possible to create a custom properties provider implementation using the Mule API. See [Custom Configuration Properties Provider](https://docs.mulesoft.com/mule-runtime/4.3/custom-configuration-properties-provider) for more details. ### Setting System Properties in Anypoint Studio You can add properties when you launch your project on Anypoint Studio, through the Run Configurations menu: 1. Right-click your project in Package Explorer. 2. Click **Run As** > **Run Configurations**. 3. Pick the **Arguments** tab. 4. Add your arguments to the **VM arguments** field, preceding property names with **\-D**: ![Arguments+Tab](/mulesoft/current/en-us/mule-runtime/4.3/_images/arguments-tab.png) Your properties are now available each time you deploy your app through Studio. You can then reference them with the following syntax: ```xml ``` ## Environment Variables Environment variables can be defined in various different ways, there are also several ways to access these from your apps. Regardless of how an environment variable is defined, the recommended way to reference it is through the following syntax: ${variableName} ### Environment Variables From the OS To reference a variable that is defined in the OS, you can simply use the following syntax: ```xml ``` ### Setting Environment Variables in Anypoint Studio You can set variables in Studio through the Run Configuration menu: 1. Right-click your project in Package Explorer. 2. Select **Run As** > **Run Configurations**. 3. Pick the Environment tab. 4. Click the **New** button and assign your variable a name and value. ![Environment+Tab](/mulesoft/current/en-us/mule-runtime/4.3/_images/environment-tab.png) Your variable is now available each time you deploy through Studio. You can reference it with the following syntax: ```xml ``` > [!NOTE] The syntax is the same for referencing variables defined in the OS and variables defined > in Studio. You can select if variables defined in Studio replace variables with the same name > defined in the OS or not, by checking the corresponding radio button in the UI when creating the > variables. ![Environment+Tab2](/mulesoft/current/en-us/mule-runtime/4.3/_images/environment-tab2.png) ## Setting the Properties File Dynamically A common configuration use case is to set the file to depend on a property (for example, `env`) to determine which file to use, for example, to use a `development-properties` file in development stage or a production file. ```xml ``` This way, the value of the property `env` determines which file to use to load the configuration properties. That `env` property can be set by a global property, system property, or environment property. You can use global properties as a way to define default values for configuration properties. System and environment properties with the same name as a global property will override that global property. ```xml ``` This way, the default value for the `env` property is `dev`, which can still be overridden with a system or environment property. Please note that this configuration is **required** for metadata resolution in Anypoint Studio. If you do not define default values for the properties that are passed through the command line, you receive an error while creating an application model for all message processors that depend on them. Another thing to consider is that placeholders of a configuration property setting cannot depend on the properties loaded from another configuration property. In the example above, the property `env` couldn’t have been defined in a configuration property. The example below **is not correct**: ```xml ``` This also includes other type of properties, such as Secure Configuration Properties or Custom Configuration Properties. ## Setting Properties Values in Runtime Manager If you deploy your application to [Runtime Manager](https://docs.mulesoft.com/runtime-manager/), you can also set properties through the Runtime Manager console. These can be defined when [Deploying to CloudHub](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub), or on an [already running application](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub). To create an environment variable or application property: 1. Log in to your Anypoint Platform account. 2. Click Runtime Manager. 3. Either click **Deploy Application** to deploy a new application, or select a running application and click **Manage Application**. 4. Select the **Properties** tab in the **Settings** section. See [Managing Applications on CloudHub](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub) and [Secure Application Properties](https://docs.mulesoft.com/cloudhub/secure-application-properties) for more details. ## Properties Hierarchy Configuration properties can be overwritten. The Mule runtime engine uses the following hierarchy to determine which properties take precedence if they have the same name. In this hierarchy, deployment properties are at the top, so they take precedence over the other types of properties. 1. Deployment properties 2. System properties 3. Environment properties 4. Application properties (includes configuration properties, secure configuration properties, and other custom configuration properties) 5. Global Properties So, for example, if a configuration property named `size` is defined as a system property, and there is also an application configuration property named `size`, the value for the application is the value of the property with the most precedence (in this case, the system property). Also, a property can derive its value from other properties that are higher in the hierarchy. Therefore, an application property can derive its value from environment, system, and deployment properties. A system property can derive its value from a deployment property, and so on. For example, if there is a system property named `env`, an application configuration property can have the value `file.${env}.xml`. On the other hand, an application property cannot depend on an application property’s value unless it’s defined in the same file. For example, a Secure Configuration property cannot depend on a Configuration property. Because of this hierarchical structure, Mule components that load files cannot depend on an application or a global property. Mule runtime engine loads both, the component and the application property, at the same hierarchy. For example, if Mule loads an `import` component before loading the application property, the deployment fails because the property is not resolved by the time the `import` component needs to load. --- product: Mule Runtime version: 4.4 --- # Configuring Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure properties, such as property placeholders and system properties. ## Property Placeholders You can use [Ant](https://ant.apache.org/)\-style property placeholders in your Mule configuration. For example: ```xml ``` The values for these placeholders can be made available in a variety of ways, as described in the sections that follow. You can also escape the resolution of property placeholder values: ```xml ``` Instead of returning the value of the property, the Logger component returns the string `"${property.value}"`. You can also use the escape character `\` to escape the resolution of the property prefix (the `${` character sequence). ## Global Properties You can use the `` element to set a placeholder value from within your Mule configuration, such as from within another Mule configuration file. You can use the global property syntax to reference the values from a `.yaml` or `.properties` file, and create new (global) properties that depends on configuration properties, or secure configuration properties. To reference configuration properties, read the section on properties files. ```xml ``` ## Properties Files To load properties from a custom file, you can place your custom properties file at `src/main/resources` and use the tag ``: ```xml ``` To load multiple properties files simply define a `` tag for each file you want to load. - If a property is defined in more than one file referenced in `` tags, the first definition will be preserved. These files must be located at `src/main/resources`, inside your Mule project, or you can also use absolute paths. ## Supported Files The Configuration Properties support both YAML configuration files (`.yaml`) and Properties configuration files (`.properties`). `String` is the only supported type in both file formats. Use the format that you find easier to read and edit. YAML file example: ```xml ``` Where `ports.yaml` is: ```yaml smtp: port: "8957" http: port: "8081" ``` Properties file example: ```xml ``` Where `ports.properties` is: ```xml smtp.port=8957 http.port=8081 ``` ## File Properties The placeholder value can also be the entire content of the file. The placeholder value becomes the string value, for example: properties-file.txt Some content ```xml ``` The payload’s value becomes `"Some content"`. Just like other properties files, these files must be located in `src/main/resources`, inside your Mule project. Absolute paths can also be used. This practice is useful for modularizing the configuration file: You can extract large contents from the config file, SQL queries, or transformations to make the config file clearer, and you can reuse the contents. ## System Properties You can set JDK system properties when running Mule On-Premises, and later use these properties to configure components or modules in a Mule application. There are two ways to specify properties: - From the command line, when starting the Mule instance: mule -M-Dsmtp.username=JSmith -M-Dsmtp.password=ChangeMe - Editing the `wrapper.conf` file located in the `$MULE_HOME/conf` directory, adding entries for each property: wrapper.java.additional.999=-Dsmtp.username=JSmith wrapper.java.additional.1000=-Dsmtp.password=ChangeMe See [System Properties](https://docs.mulesoft.com/mule-runtime/4.4/mule-app-properties-system#set-properties) for additional configuration details. ## Custom Properties Provider It is possible to create a custom properties provider implementation using the Mule API. See [Custom Configuration Properties Provider](https://docs.mulesoft.com/mule-runtime/4.4/custom-configuration-properties-provider) for more details. ### Setting System Properties in Anypoint Studio You can add properties when you launch your project on Anypoint Studio, through the Run Configurations menu: 1. Right-click your project in Package Explorer. 2. Click **Run As** > **Run Configurations**. 3. Pick the **Arguments** tab. 4. Add your arguments to the **VM arguments** field, preceding property names with **\-D**: ![Arguments+Tab](/mulesoft/current/en-us/mule-runtime/4.4/_images/arguments-tab.png) Your properties are now available each time you deploy your app through Studio. You can then reference them with the following syntax: ```xml ``` ## Environment Variables Environment variables can be defined in various different ways, there are also several ways to access these from your apps. Regardless of how an environment variable is defined, the recommended way to reference it is through the following syntax: ${variableName} ### Environment Variables From the OS To reference a variable that is defined in the OS, you can simply use the following syntax: ```xml ``` ### Setting Environment Variables in Anypoint Studio You can set variables in Studio through the Run Configuration menu: 1. Right-click your project in Package Explorer. 2. Select **Run As** > **Run Configurations**. 3. Pick the Environment tab. 4. Click the **New** button and assign your variable a name and value. ![Environment+Tab](/mulesoft/current/en-us/mule-runtime/4.4/_images/environment-tab.png) Your variable is now available each time you deploy through Studio. You can reference it with the following syntax: ```xml ``` > [!NOTE] The syntax is the same for referencing variables defined in the OS and variables defined > in Studio. You can select if variables defined in Studio replace variables with the same name > defined in the OS or not, by checking the corresponding radio button in the UI when creating the > variables. ![Environment+Tab2](/mulesoft/current/en-us/mule-runtime/4.4/_images/environment-tab2.png) ## Setting the Properties File Dynamically A common configuration use case is to set the file to depend on a property (for example, `env`) to determine which file to use, for example, to use a `development-properties` file in development stage or a production file. ```xml ``` This way, the value of the property `env` determines which file to use to load the configuration properties. That `env` property can be set by a global property, system property, or environment property. You can use global properties as a way to define default values for configuration properties. System and environment properties with the same name as a global property will override that global property. ```xml ``` This way, the default value for the `env` property is `dev`, which can still be overridden with a system or environment property. Please note that this configuration is **required** for metadata resolution in Anypoint Studio. If you do not define default values for the properties that are passed through the command line, you receive an error while creating an application model for all message processors that depend on them. Another thing to consider is that placeholders of a configuration property setting cannot depend on the properties loaded from another configuration property. In the example above, the property `env` couldn’t have been defined in a configuration property. The example below **is not correct**: ```xml ``` This also includes other type of properties, such as Secure Configuration Properties or Custom Configuration Properties. ## Setting Properties Values in Runtime Manager If you deploy your application to [Runtime Manager](https://docs.mulesoft.com/runtime-manager/), you can also set properties through the Runtime Manager console. These can be defined when [Deploying to CloudHub](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub), or on an [already running application](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub). To create an environment variable or application property: 1. Log in to your Anypoint Platform account. 2. Click Runtime Manager. 3. Either click **Deploy Application** to deploy a new application, or select a running application and click **Manage Application**. 4. Select the **Properties** tab in the **Settings** section. See [Managing Applications on CloudHub](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub) and [Secure Application Properties](https://docs.mulesoft.com/cloudhub/secure-application-properties) for more details. ## Properties Hierarchy Configuration properties can be overwritten. The Mule runtime engine uses the following hierarchy to determine which properties take precedence if they have the same name. In this hierarchy, deployment properties are at the top, so they take precedence over the other types of properties. 1. Deployment properties 2. System properties 3. Environment properties 4. Application properties (includes configuration properties, secure configuration properties, and other custom configuration properties) 5. Global Properties So, for example, if a configuration property named `size` is defined as a system property, and there is also an application configuration property named `size`, the value for the application is the value of the property with the most precedence (in this case, the system property). Also, a property can derive its value from other properties that are higher in the hierarchy. Therefore, an application property can derive its value from environment, system, and deployment properties. A system property can derive its value from a deployment property, and so on. For example, if there is a system property named `env`, an application configuration property can have the value `file.${env}.xml`. However, an application property cannot depend on an application property’s value unless it’s defined in the same file. For example, a Secure Configuration property cannot depend on a Configuration property. Because of this hierarchical structure, Mule components that load files cannot depend on an application or a global property. Mule runtime engine loads both, the component and the application property, at the same hierarchy. For example, if Mule loads an `import` component before loading the application property, the deployment fails because the property is not resolved by the time the `import` component needs to load. ## Built-in Properties Mule runtime engine defines internal Application properties and assigns a value to them based on the configuration of the Mule instance and the deployed applications:
PropertyDescription

app.home

The path to the Mule application /home directory

app.name

The name of the Mule application

domain.name

The name of the Domain

api.name

The name of the API

mule.home

The path to the Mule instance /home directory

Do not overwrite any of these properties; Mule uses some of these values internally and overwriting them might cause unexpected behaviors. --- product: Mule Runtime version: 4.6 --- # Configuring Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure properties, such as property placeholders and system properties. ## Property Placeholders You can use [Ant](https://ant.apache.org/)\-style property placeholders in your Mule configuration. For example: ```xml ``` The values for these placeholders can be made available in a variety of ways, as described in the sections that follow. You can also escape the resolution of property placeholder values: ```xml ``` Instead of returning the value of the property, the Logger component returns the string `"${property.value}"`. You can also use the escape character `\` to escape the resolution of the property prefix (the `${` character sequence). ## Global Properties You can use the `` element to set a placeholder value from within your Mule configuration, such as from within another Mule configuration file. You can use the global property syntax to reference the values from a `.yaml` or `.properties` file, and create new (global) properties that depends on configuration properties, or secure configuration properties. To reference configuration properties, read the section on properties files. ```xml ``` ## Properties Files To load properties from a custom file, you can place your custom properties file at `src/main/resources` and use the tag ``: ```xml ``` To load multiple properties files simply define a `` tag for each file you want to load. - If a property is defined in more than one file referenced in `` tags, the first definition will be preserved. These files must be located at `src/main/resources`, inside your Mule project, or you can also use absolute paths. ## Supported Files The Configuration Properties support both YAML configuration files (`.yaml`) and Properties configuration files (`.properties`). `String` is the only supported type in both file formats. Use the format that you find easier to read and edit. YAML file example: ```xml ``` Where `ports.yaml` is: ```yaml smtp: port: "8957" http: port: "8081" ``` Properties file example: ```xml ``` Where `ports.properties` is: ```xml smtp.port=8957 http.port=8081 ``` ## File Properties The placeholder value can also be the entire content of the file. The placeholder value becomes the string value, for example: properties-file.txt Some content ```xml ``` The payload’s value becomes `"Some content"`. Just like other properties files, these files must be located in `src/main/resources`, inside your Mule project. Absolute paths can also be used. This practice is useful for modularizing the configuration file: You can extract large contents from the config file, SQL queries, or transformations to make the config file clearer, and you can reuse the contents. ## System Properties You can set JDK system properties when running Mule On-Premises, and later use these properties to configure components or modules in a Mule application. There are two ways to specify properties: - From the command line, when starting the Mule instance: mule -M-Dsmtp.username=JSmith -M-Dsmtp.password=ChangeMe - Editing the `wrapper.conf` file located in the `$MULE_HOME/conf` directory, adding entries for each property: wrapper.java.additional.999=-Dsmtp.username=JSmith wrapper.java.additional.1000=-Dsmtp.password=ChangeMe See [System Properties](https://docs.mulesoft.com/mule-runtime/4.6/mule-app-properties-system#set-properties) for additional configuration details. ## Custom Properties Provider It is possible to create a custom properties provider implementation using the Mule API. See [Custom Configuration Properties Provider](https://docs.mulesoft.com/mule-runtime/4.6/custom-configuration-properties-provider) for more details. ### Setting System Properties in Anypoint Studio You can add properties when you launch your project on Anypoint Studio, through the Run Configurations menu: 1. Right-click your project in Package Explorer. 2. Click **Run As** > **Run Configurations**. 3. Pick the **Arguments** tab. 4. Add your arguments to the **VM arguments** field, preceding property names with **\-D**: ![Arguments+Tab](/mulesoft/current/en-us/mule-runtime/4.6/_images/arguments-tab.png) Your properties are now available each time you deploy your app through Studio. You can then reference them with the following syntax: ```xml ``` ## Environment Variables Environment variables can be defined in various different ways, there are also several ways to access these from your apps. Regardless of how an environment variable is defined, the recommended way to reference it is through the following syntax: ${variableName} ### Environment Variables From the OS To reference a variable that is defined in the OS, you can simply use the following syntax: ```xml ``` ### Setting Environment Variables in Anypoint Studio You can set variables in Studio through the Run Configuration menu: 1. Right-click your project in Package Explorer. 2. Select **Run As** > **Run Configurations**. 3. Pick the Environment tab. 4. Click the **New** button and assign your variable a name and value. ![Environment+Tab](/mulesoft/current/en-us/mule-runtime/4.6/_images/environment-tab.png) Your variable is now available each time you deploy through Studio. You can reference it with the following syntax: ```xml ``` > [!NOTE] The syntax is the same for referencing variables defined in the OS and variables defined > in Studio. You can select if variables defined in Studio replace variables with the same name > defined in the OS or not, by checking the corresponding radio button in the UI when creating the > variables. ![Environment+Tab2](/mulesoft/current/en-us/mule-runtime/4.6/_images/environment-tab2.png) ## Setting the Properties File Dynamically A common configuration use case is to set the file to depend on a property (for example, `env`) to determine which file to use, for example, to use a `development-properties` file in development stage or a production file. ```xml ``` This way, the value of the property `env` determines which file to use to load the configuration properties. That `env` property can be set by a global property, system property, or environment property. You can use global properties as a way to define default values for configuration properties. System and environment properties with the same name as a global property will override that global property. ```xml ``` This way, the default value for the `env` property is `dev`, which can still be overridden with a system or environment property. Please note that this configuration is **required** for metadata resolution in Anypoint Studio. If you do not define default values for the properties that are passed through the command line, you receive an error while creating an application model for all message processors that depend on them. Another thing to consider is that placeholders of a configuration property setting cannot depend on the properties loaded from another configuration property. In the example above, the property `env` couldn’t have been defined in a configuration property. The example below **is not correct**: ```xml ``` This also includes other type of properties, such as Secure Configuration Properties or Custom Configuration Properties. ## Setting Properties Values in Runtime Manager If you deploy your application to [Runtime Manager](https://docs.mulesoft.com/runtime-manager/), you can also set properties through the Runtime Manager console. These can be defined when [Deploying to CloudHub](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub), or on an [already running application](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub). To create an environment variable or application property: 1. Log in to your Anypoint Platform account. 2. Click Runtime Manager. 3. Either click **Deploy Application** to deploy a new application, or select a running application and click **Manage Application**. 4. Select the **Properties** tab in the **Settings** section. See [Managing Applications on CloudHub](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub) and [Secure Application Properties](https://docs.mulesoft.com/cloudhub/secure-application-properties) for more details. ## Properties Hierarchy Configuration properties can be overwritten. The Mule runtime engine uses the following hierarchy to determine which properties take precedence if they have the same name. In this hierarchy, deployment properties are at the top, so they take precedence over the other types of properties. 1. Deployment properties 2. System properties 3. Environment properties 4. Application properties (includes configuration properties, secure configuration properties, and other custom configuration properties) 5. Global Properties So, for example, if a configuration property named `size` is defined as a system property, and there is also an application configuration property named `size`, the value for the application is the value of the property with the most precedence (in this case, the system property). Also, a property can derive its value from other properties that are higher in the hierarchy. Therefore, an application property can derive its value from environment, system, and deployment properties. A system property can derive its value from a deployment property, and so on. For example, if there is a system property named `env`, an application configuration property can have the value `file.${env}.xml`. However, an application property cannot depend on an application property’s value unless it’s defined in the same file. For example, a Secure Configuration property cannot depend on a Configuration property. Because of this hierarchical structure, Mule components that load files cannot depend on an application or a global property. Mule runtime engine loads both, the component and the application property, at the same hierarchy. For example, if Mule loads an `import` component before loading the application property, the deployment fails because the property is not resolved by the time the `import` component needs to load. ## Built-in Properties Mule runtime engine defines internal Application properties and assigns a value to them based on the configuration of the Mule instance and the deployed applications:
PropertyDescription

app.home

The path to the Mule application /home directory

app.name

The name of the Mule application

domain.name

The name of the Domain

api.name

The name of the API

mule.home

The path to the Mule instance /home directory

Do not overwrite any of these properties; Mule uses some of these values internally and overwriting them might cause unexpected behaviors. --- product: Mule Runtime version: 4.9 --- # Configuring Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure properties, such as property placeholders and system properties. ## Property Placeholders You can use [Ant](https://ant.apache.org/)\-style property placeholders in your Mule configuration. For example: ```xml ``` The values for these placeholders can be made available in a variety of ways, as described in the sections that follow. You can also escape the resolution of property placeholder values: ```xml ``` Instead of returning the value of the property, the Logger component returns the string `"${property.value}"`. You can also use the escape character `\` to escape the resolution of the property prefix (the `${` character sequence). ## Global Properties You can use the `` element to set a placeholder value from within your Mule configuration, such as from within another Mule configuration file. You can use the global property syntax to reference the values from a `.yaml` or `.properties` file, and create new (global) properties that depends on configuration properties, or secure configuration properties. To reference configuration properties, read the section on properties files. ```xml ``` ## Properties Files To load properties from a custom file, you can place your custom properties file at `src/main/resources` and use the tag ``: ```xml ``` To load multiple properties files simply define a `` tag for each file you want to load. - If a property is defined in more than one file referenced in `` tags, the first definition will be preserved. These files must be located at `src/main/resources`, inside your Mule project, or you can also use absolute paths. ## Supported Files The Configuration Properties support both YAML configuration files (`.yaml`) and Properties configuration files (`.properties`). `String` is the only supported type in both file formats. Use the format that you find easier to read and edit. YAML file example: ```xml ``` Where `ports.yaml` is: ```yaml smtp: port: "8957" http: port: "8081" ``` Properties file example: ```xml ``` Where `ports.properties` is: ```xml smtp.port=8957 http.port=8081 ``` ## File Properties The placeholder value can also be the entire content of the file. The placeholder value becomes the string value, for example: properties-file.txt Some content ```xml ``` The payload’s value becomes `"Some content"`. Just like other properties files, these files must be located in `src/main/resources`, inside your Mule project. Absolute paths can also be used. This practice is useful for modularizing the configuration file: You can extract large contents from the config file, SQL queries, or transformations to make the config file clearer, and you can reuse the contents. ## System Properties You can set JDK system properties when running Mule On-Premises, and later use these properties to configure components or modules in a Mule application. There are two ways to specify properties: - From the command line, when starting the Mule instance: mule -M-Dsmtp.username=JSmith -M-Dsmtp.password=ChangeMe - Editing the `wrapper.conf` file located in the `$MULE_HOME/conf` directory, adding entries for each property: wrapper.java.additional.999=-Dsmtp.username=JSmith wrapper.java.additional.1000=-Dsmtp.password=ChangeMe See [System Properties](https://docs.mulesoft.com/mule-runtime/4.9/mule-app-properties-system#set-properties) for additional configuration details. ## Custom Properties Provider It is possible to create a custom properties provider implementation using the Mule API. See [Custom Configuration Properties Provider](https://docs.mulesoft.com/mule-runtime/4.9/custom-configuration-properties-provider) for more details. ### Setting System Properties in Anypoint Studio You can add properties when you launch your project on Anypoint Studio, through the Run Configurations menu: 1. Right-click your project in Package Explorer. 2. Click **Run As** > **Run Configurations**. 3. Pick the **Arguments** tab. 4. Add your arguments to the **VM arguments** field, preceding property names with **\-D**: ![Arguments tab showing settings for JVM arguments in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/arguments-tab.png) Your properties are now available each time you deploy your app through Studio. You can then reference them with the following syntax: ```xml ``` ## Environment Variables Environment variables can be defined in various different ways, there are also several ways to access these from your apps. Regardless of how an environment variable is defined, the recommended way to reference it is through the following syntax: ${variableName} ### Environment Variables From the OS To reference a variable that is defined in the OS, you can simply use the following syntax: ```xml ``` ### Setting Environment Variables in Anypoint Studio You can set variables in Studio through the Run Configuration menu: 1. Right-click your project in Package Explorer. 2. Select **Run As** > **Run Configurations**. 3. Pick the Environment tab. 4. Click the **New** button and assign your variable a name and value. ![An Environment tab with options including New](/mulesoft/current/en-us/mule-runtime/4.9/_images/environment-tab.png) Your variable is now available each time you deploy through Studio. You can reference it with the following syntax: ```xml ``` > [!NOTE] The syntax is the same for referencing variables defined in the OS and variables defined > in Studio. You can select if variables defined in Studio replace variables with the same name > defined in the OS or not, by checking the corresponding radio button in the UI when creating the > variables. ![An Environment tab with options to define variables](/mulesoft/current/en-us/mule-runtime/4.9/_images/environment-tab2.png) ## Setting the Properties File Dynamically A common configuration use case is to set the file to depend on a property (for example, `env`) to determine which file to use, for example, to use a `development-properties` file in development stage or a production file. ```xml ``` This way, the value of the property `env` determines which file to use to load the configuration properties. That `env` property can be set by a global property, system property, or environment property. You can use global properties as a way to define default values for configuration properties. System and environment properties with the same name as a global property will override that global property. ```xml ``` This way, the default value for the `env` property is `dev`, which can still be overridden with a system or environment property. Please note that this configuration is **required** for metadata resolution in Anypoint Studio. If you do not define default values for the properties that are passed through the command line, you receive an error while creating an application model for all message processors that depend on them. Another thing to consider is that placeholders of a configuration property setting cannot depend on the properties loaded from another configuration property. In the example above, the property `env` couldn’t have been defined in a configuration property. The example below **is not correct**: ```xml ``` This also includes other type of properties, such as Secure Configuration Properties or Custom Configuration Properties. ## Setting Properties Values in Runtime Manager If you deploy your application to [Runtime Manager](https://docs.mulesoft.com/runtime-manager/), you can also set properties through the Runtime Manager console. These can be defined when [Deploying to CloudHub](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub), or on an [already running application](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub). To create an environment variable or application property: 1. Log in to your Anypoint Platform account. 2. Click Runtime Manager. 3. Either click **Deploy Application** to deploy a new application, or select a running application and click **Manage Application**. 4. Select the **Properties** tab in the **Settings** section. See [Managing Applications on CloudHub](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub) and [Secure Application Properties](https://docs.mulesoft.com/cloudhub/secure-application-properties) for more details. ## Properties Hierarchy Configuration properties can be overwritten. The Mule runtime engine uses the following hierarchy to determine which properties take precedence if they have the same name. In this hierarchy, deployment properties are at the top, so they take precedence over the other types of properties. 1. Deployment properties 2. System properties 3. Environment properties 4. Application properties (includes configuration properties, secure configuration properties, and other custom configuration properties) 5. Global Properties So, for example, if a configuration property named `size` is defined as a system property, and there is also an application configuration property named `size`, the value for the application is the value of the property with the most precedence (in this case, the system property). Also, a property can derive its value from other properties that are higher in the hierarchy. Therefore, an application property can derive its value from environment, system, and deployment properties. A system property can derive its value from a deployment property, and so on. For example, if there is a system property named `env`, an application configuration property can have the value `file.${env}.xml`. However, an application property cannot depend on an application property’s value unless it’s defined in the same file. For example, a Secure Configuration property cannot depend on a Configuration property. Because of this hierarchical structure, Mule components that load files cannot depend on an application or a global property. Mule runtime engine loads both, the component and the application property, at the same hierarchy. For example, if Mule loads an `import` component before loading the application property, the deployment fails because the property is not resolved by the time the `import` component needs to load. ## Built-in Properties Mule runtime engine defines internal Application properties and assigns a value to them based on the configuration of the Mule instance and the deployed applications:
PropertyDescription

app.home

The path to the Mule application /home directory

app.name

The name of the Mule application

domain.name

The name of the Domain

api.name

The name of the API

mule.home

The path to the Mule instance /home directory

Do not overwrite any of these properties; Mule uses some of these values internally and overwriting them might cause unexpected behaviors. --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Configuring Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can configure properties, such as property placeholders and system properties. ## Property Placeholders You can use [Ant](https://ant.apache.org/)\-style property placeholders in your Mule configuration. For example: ```xml ``` The values for these placeholders can be made available in a variety of ways, as described in the sections that follow. You can also escape the resolution of property placeholder values: ```xml ``` Instead of returning the value of the property, the Logger component returns the string `"${property.value}"`. You can also use the escape character `\` to escape the resolution of the property prefix (the `${` character sequence). ## Global Properties You can use the `` element to set a placeholder value from within your Mule configuration, such as from within another Mule configuration file. You can use the global property syntax to reference the values from a `.yaml` or `.properties` file, and create new (global) properties that depends on configuration properties, or secure configuration properties. To reference configuration properties, read the section on properties files. ```xml ``` ## Properties Files To load properties from a custom file, you can place your custom properties file at `src/main/resources` and use the tag ``: ```xml ``` To load multiple properties files simply define a `` tag for each file you want to load. - If a property is defined in more than one file referenced in `` tags, the first definition will be preserved. These files must be located at `src/main/resources`, inside your Mule project, or you can also use absolute paths. ## Supported Files The Configuration Properties support both YAML configuration files (`.yaml`) and Properties configuration files (`.properties`). `String` is the only supported type in both file formats. Use the format that you find easier to read and edit. YAML file example: ```xml ``` Where `ports.yaml` is: ```yaml smtp: port: "8957" http: port: "8081" ``` Properties file example: ```xml ``` Where `ports.properties` is: ```xml smtp.port=8957 http.port=8081 ``` ## File Properties The placeholder value can also be the entire content of the file. The placeholder value becomes the string value, for example: properties-file.txt Some content ```xml ``` The payload’s value becomes `"Some content"`. Just like other properties files, these files must be located in `src/main/resources`, inside your Mule project. Absolute paths can also be used. This practice is useful for modularizing the configuration file: You can extract large contents from the config file, SQL queries, or transformations to make the config file clearer, and you can reuse the contents. ## System Properties You can set JDK system properties when running Mule On-Premises, and later use these properties to configure components or modules in a Mule application. There are two ways to specify properties: - From the command line, when starting the Mule instance: mule -M-Dsmtp.username=JSmith -M-Dsmtp.password=ChangeMe - Editing the `wrapper.conf` file located in the `$MULE_HOME/conf` directory, adding entries for each property: wrapper.java.additional.999=-Dsmtp.username=JSmith wrapper.java.additional.1000=-Dsmtp.password=ChangeMe See [System Properties](https://docs.mulesoft.com/mule-runtime/latest/mule-app-properties-system#set-properties) for additional configuration details. ## Custom Properties Provider It is possible to create a custom properties provider implementation using the Mule API. See [Custom Configuration Properties Provider](https://docs.mulesoft.com/mule-runtime/latest/custom-configuration-properties-provider) for more details. ### Setting System Properties in Anypoint Studio You can add properties when you launch your project on Anypoint Studio, through the Run Configurations menu: 1. Right-click your project in Package Explorer. 2. Click **Run As** > **Run Configurations**. 3. Pick the **Arguments** tab. 4. Add your arguments to the **VM arguments** field, preceding property names with **\-D**: ![Arguments tab showing settings for JVM arguments in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/arguments-tab.png) Your properties are now available each time you deploy your app through Studio. You can then reference them with the following syntax: ```xml ``` ## Environment Variables Environment variables can be defined in various different ways, there are also several ways to access these from your apps. Regardless of how an environment variable is defined, the recommended way to reference it is through the following syntax: ${variableName} ### Environment Variables From the OS To reference a variable that is defined in the OS, you can simply use the following syntax: ```xml ``` ### Setting Environment Variables in Anypoint Studio You can set variables in Studio through the Run Configuration menu: 1. Right-click your project in Package Explorer. 2. Select **Run As** > **Run Configurations**. 3. Pick the Environment tab. 4. Click the **New** button and assign your variable a name and value. ![An Environment tab with options including New](/mulesoft/current/en-us/mule-runtime/latest/_images/environment-tab.png) Your variable is now available each time you deploy through Studio. You can reference it with the following syntax: ```xml ``` > [!NOTE] The syntax is the same for referencing variables defined in the OS and variables defined > in Studio. You can select if variables defined in Studio replace variables with the same name > defined in the OS or not, by checking the corresponding radio button in the UI when creating the > variables. ![An Environment tab with options to define variables](/mulesoft/current/en-us/mule-runtime/latest/_images/environment-tab2.png) ## Setting the Properties File Dynamically A common configuration use case is to set the file to depend on a property (for example, `env`) to determine which file to use, for example, to use a `development-properties` file in development stage or a production file. ```xml ``` This way, the value of the property `env` determines which file to use to load the configuration properties. That `env` property can be set by a global property, system property, or environment property. You can use global properties as a way to define default values for configuration properties. System and environment properties with the same name as a global property will override that global property. ```xml ``` This way, the default value for the `env` property is `dev`, which can still be overridden with a system or environment property. Please note that this configuration is **required** for metadata resolution in Anypoint Studio. If you do not define default values for the properties that are passed through the command line, you receive an error while creating an application model for all message processors that depend on them. Another thing to consider is that placeholders of a configuration property setting cannot depend on the properties loaded from another configuration property. In the example above, the property `env` couldn’t have been defined in a configuration property. The example below **is not correct**: ```xml ``` This also includes other type of properties, such as Secure Configuration Properties or Custom Configuration Properties. ## Setting Properties Values in Runtime Manager If you deploy your application to [Runtime Manager](https://docs.mulesoft.com/runtime-manager/), you can also set properties through the Runtime Manager console. These can be defined when [Deploying to CloudHub](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub), or on an [already running application](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub). To create an environment variable or application property: 1. Log in to your Anypoint Platform account. 2. Click Runtime Manager. 3. Either click **Deploy Application** to deploy a new application, or select a running application and click **Manage Application**. 4. Select the **Properties** tab in the **Settings** section. See [Managing Applications on CloudHub](https://docs.mulesoft.com/cloudhub/managing-applications-on-cloudhub) and [Secure Application Properties](https://docs.mulesoft.com/cloudhub/secure-application-properties) for more details. ## Properties Hierarchy Configuration properties can be overwritten. The Mule runtime engine uses the following hierarchy to determine which properties take precedence if they have the same name. In this hierarchy, deployment properties are at the top, so they take precedence over the other types of properties. 1. Deployment properties 2. System properties 3. Environment properties 4. Application properties (includes configuration properties, secure configuration properties, and other custom configuration properties) 5. Global Properties So, for example, if a configuration property named `size` is defined as a system property, and there is also an application configuration property named `size`, the value for the application is the value of the property with the most precedence (in this case, the system property). Also, a property can derive its value from other properties that are higher in the hierarchy. Therefore, an application property can derive its value from environment, system, and deployment properties. A system property can derive its value from a deployment property, and so on. For example, if there is a system property named `env`, an application configuration property can have the value `file.${env}.xml`. However, an application property cannot depend on an application property’s value unless it’s defined in the same file. For example, a Secure Configuration property cannot depend on a Configuration property. Because of this hierarchical structure, Mule components that load files cannot depend on an application or a global property. Mule runtime engine loads both, the component and the application property, at the same hierarchy. For example, if Mule loads an `import` component before loading the application property, the deployment fails because the property is not resolved by the time the `import` component needs to load. ## Built-in Properties Mule runtime engine defines internal Application properties and assigns a value to them based on the configuration of the Mule instance and the deployed applications:
PropertyDescription

app.home

The path to the Mule application /home directory

app.name

The name of the Mule application

domain.name

The name of the Domain

api.name

The name of the API

mule.home

The path to the Mule instance /home directory

Do not overwrite any of these properties; Mule uses some of these values internally and overwriting them might cause unexpected behaviors. --- product: Mule Runtime version: 4.11 --- # Consume Data from an API > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you build your application, you can start consuming data from an API. Review the following processes to consume data from a SOAP or REST API. ## Consume Data from a SOAP API To consume data from a SOAP API that does not have its own Anypoint Connector, configure Anypoint Connector for Web Service Consumer (Web Service Consumer Connector). Using the host, port, and address metadata retrieved from the API’s WSDL file, the connector provides the connection configuration you need for consuming a service from within your Mule application: See [Web Service Consumer Connector](https://docs.mulesoft.com/web-service-consumer-connector/latest/) for details. ## Consume Data from a REST API The following process focuses on configuring the HTTP Request Connector to call the REST API. It helps you to understand the basic anatomy of how a Mule application consumes a REST API, the minimum configuration required, how to consume examples, how to configure dynamic requests, how to manage HTTP Content-Type and encoding, and how to work with custom headers and security requirements. To consume data from a REST API from within a Mule application, you can configure Anypoint Connector for HTTP Request (HTTP Request Connector). If you connect to the same REST API many times or work with an API that has complex authentication protocols, consider [developing your own connector using the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). Check whether a connector already exists in [Anypoint Exchange](https://anypoint.mulesoft.com/exchange/) for the API you want to connect to. You can search in Exchange through Anypoint Studio’s Mule Palette. ## Basic Anatomy A Mule application consuming a REST API consists of the following: - One or more message processors configured to build your request - An HTTP request operation configured to call the REST API - One or more message processors configured to accept and process the response ![Consuming REST API Flow](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-consume-rest-api-flow.png) Figure 1. Consuming REST API Flow. You configure the portions of the application that build the request and process the response. ## Minimum Configuration The REST API you are consuming must have a [RAML](https://raml.org/) file that describes the API, so that the HTTP connector proactively presents you with smart suggestions. In the RAML file, you define the following: - Authentication - A base URI for configuring the outbound HTTP endpoint - Scope Based on authentication credentials, the application can limit calls to only GET requests on certain resources, for example, or otherwise limit access to a resource. - Resources You must configure the path of the resources for the outbound HTTP endpoint. - Methods You can accept POST as the default method for the HTTP outbound endpoint, or you can change this default to the method supported by your resource. - Input validation For POST and PUT calls, the API almost always requires that the input format, such as JSON or XML, match its schema. In Mule runtime engine, you can define or configure the following: - Output format After the HTTP request operation, your flow must include message processors to accept the response from the API and translate the response into a useable format. - Redirects If the API uses redirects, enable redirects in your HTTP request operation. - Timeout - Headers for methods POST, PUT, and DELETE requests almost always require headers. - URI and Query Parameters - Error handling See [HTTP Connector documentation](https://docs.mulesoft.com/http-connector/latest/#input-sources) for more information about how to configure the request operation. ### Consume REST API Example The following example consumes the [JSONPlaceholder API](https://jsonplaceholder.typicode.com/todos/1). The example shows only the configuration of the HTTP Request Connector, and to make it work, you must configure at least one Mule event source to trigger a message in the flow and at least one message processor to accept the response. See [REST API Examples documentation](https://docs.mulesoft.com/mule-runtime/4.11/rest-api-examples) for more information. In this API example: - The API doesn’t require authentication. - The base URL is `jsonplaceholder.typicode.com`. - The API is a mock API for development purposes. - The sample API requests show that to get information about user with `id=1` the request must be: https://jsonplaceholder.typicode.com/users/1 The parts of the URL are as follows: - Protocol: `http` - API Base URL: `jsonplaceholder.typicode.com` - Resource path: `/users/1` - Query Parameters: None, in this case. To implement this call in your Mule application, configure your HTTP request operation. ### Configure HTTP Request Operation in Anypoint Studio 1. From the Mule Palette in Studio, add an HTTP Request Connector to your application. 2. In the HTTP Request Configuration window, provide `jsonplaceholder.typicode.com` as the value for **Host**. 3. Set the **Port** value to 80. 4. Click **OK**: ![An HTTP Request configuration with Host and Port](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-consume-rest-api-configuration-1.png) Figure 2. HTTP Request configuration with Host and Port. 5. Navigate to the Request section from the HTTP Request operation’s properties editor > General tab and add `/users/1` in the **Path** field. Specifying this path completes the URL that you began to identify by specifying the host in the first step. 6. Select a method from the **Method** drop-down list (in this example, `GET`). 7. Save your application. ![An HTTP Request GET Method and Path](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-consume-rest-api-configuration-2.png) Figure 3. HTTP Request GET Method and Path. ### Configure HTTP Request Operation in XML The following XML code shows the configuration of the HTTP Request operation for the example: ```xml <...> ``` ### Example JSON Response For the JSONPlaceholder API example, the JSON response has the following structure: ```json { "userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": false } ``` You can transform the data in the **Advanced** tab of the HTTP Request operation. You can also define the target variable, which by default is the Payload. If this API has an associated RAML file, you can reference it in the configuration element of the connector. With that in place, after you select the verb and asset to call, Studio exposes the metadata corresponding to the output. Integration with other elements in a flow is simplified. ## Configure Dynamic Requests with DataWeave Expressions Most use cases require that you change the call to the API change dynamically based on data in the message. You can configure these dynamic requests by using DataWeave expressions. In the configuration examples documented in "Consume REST API Example", the request was hardcoded in the URL: https://jsonplaceholder.typicode.com/users/1 In the following GET request example, the call instructs Mule runtime engine to extract the user ID from the payload of the message, using the DataWeave expression `#[payload.user_id]`. https://jsonplaceholder.typicode.com/users/#\[payload.user\_id\] ### Configure Dynamic Requests in Anypoint Studio To perform the same operation by using Anypoint Studio, modify the path configuration with the desired DataWeave expression: in this case `#['/users/' ++ payload.user_id]`. ![A configure Dynamic Requests with DataWeave expressions in Path field](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-consume-rest-api-configuration-3.png) Figure 4. Configure Dynamic Requests with DataWeave expressions in Path field. You can also configure dynamic requests for the query or URI parameters, or for the HTTP method. Additionally, you can use [Configuration Properties](https://docs.mulesoft.com/mule-runtime/4.11/configuring-properties) to set any of these dynamic requests. ### Configure Dynamic Requests in XML The following example code in XML, shows the configuration of dynamic requests: ```xml <...> ``` ## HTTP Content-Type and Encoding When you send a POST request, Mule runtime engine adheres to the following rules regarding Content-Type and encoding of the body.

Content

Rules

For a String, char[]`, Reader, or similar*

* If the endpoint has explicitly set encoding, Mule runtime engine uses that encoding. * If the endpoint does not have explicitly set encoding, Mule runtime engine determines the encoding from the message property Content-Type. * If the Content-Type message property is not set, Mule runtime engine uses the Mule Context default configuration. * For Content-Type, Mule runtime engine sends the message property Content-Type, but with the actual encoding set.

For binary content

Encoding is not relevant. Mule runtime engine sets Content-Type as follows:

  • If the Content-Type property is set on the message, Mule runtime engine uses the defined content type.

  • If the Content-Type property is not set on the message, Mule runtime engine sets "application/octet-stream" as Content-Type.

## Custom Headers Some APIs require that you pass custom headers, such as your developer key, along with your requests. As with the query parameters, you can also add headers to your request on the HTTP Connector. For example, if the API you are consuming requires a developer key, then specify that key as a header on your requests by using the header name `accessKey`. You can add a property to set custom headers by using Anypoint Studio. ### Custom Headers in Anypoint Studio To set custom headers in Studio, review the following steps: - In the HTTP Request operation’s properties editor, select the **Headers** tab. - Click **Add**. - Define **Name** and **Value**. Both can be defined using expressions or properties placeholders. ![A custom header configuration in Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-consume-rest-api-configuration-4.png) Figure 5. Configure Custom Headers in the HTTP Request operation’s properties editor. ## Security Requirements If the API that you are calling requires complex authentication protocols, you can build your own connector to consume it. Otherwise, you can meet API security requirements by setting basic authentication credentials or configuring a global HTTPS connector. ### Basic Authentication If the REST API that you are consuming requires you to supply basic authentication credentials, you can provide them within the outbound HTTP endpoint configuration: 1. In Studio, go to the HTTP Request configuration window. 2. In Authentication, select **Basic Authentication**. 3. Type your username and password. These can also be set as properties placeholders. 4. Click **OK**. ![An HTTP Request showing settings for connection timeout, response buffer size, and TLS configuration](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-consume-rest-api-configuration-7.png) ### HTTPS Configuration If you are consuming a REST API that requires that incoming requests arrive via HTTPS, you can configure a global HTTPS Request connector in your Mule application, then reference the connector in your request operation. In the following example, you configure the HTTPS Request connector, create a Java keystore file (JKS) and [configure TLS](https://docs.mulesoft.com/mule-runtime/4.11/tls-configuration). #### Configure the HTTP Request Connector for HTTPS 1. In the HTTP Request Configuration window, navigate to General tab > Connection Configuration section. 2. Select **HTTPS** for the **Protocol**. 3. Click **OK**. ![An HTTP Request showing settings for protocol, host, port, and persistent connections configuration](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-consume-rest-api-configuration-5.png) Figure 6. Configure HTTPS Request Connector. #### Create a Keystore File Using the Java keytool in the bin directory of the Java installation, create a keystore file to certify the communication: 1. Using the command line, navigate to the Java installation directory on your machine. 2. Execute the following command: keytool -genkey -alias mule -keyalg RSA -keystore keystore.jks 3. When prompted, create two passwords and remember them for later use. This action creates a `jks` file in the local directory called `keystore.jks`. 4. Place your `keystore.jks` file: - If you use Studio, place the `keystore.jks` file into the `appname/src/main/resources` directory in Studio Package Explorer. - If you use XML in Mule runtime engine and want to use the file across multiple applications, place the file in the `MULE_HOME/conf` directory. - If you use XML in Mule runtime engine and want to use the file within this application, place the file in the `yourappname/src/main/resources` directory. 5. Reference the keystore in a global HTTPS Request connector. This connector is then referenced by the HTTP outbound endpoint within your flow. #### Configure TLS Follow these steps to configure TLS: 1. In Studio, go to the Global Elements view. 2. Select **Create** and search for "TLS Context". 3. In the Key Store Configuration section, select a type of keystore configuration from the drop-down menu: for example, **JKS** (Java Key Store) which is the default type. 4. For **Path**, specify the name of the keystore if you placed your keystore in the `appname/src/main/resources` directory; otherwise, specify `"/keystore.jks"`. 5. For **Key Password**, and **Password**, enter the passwords that you created when creating your keystore file. 6. Click **OK**. ![A TLS configuration showing settings for trust store and key store configurations](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-consume-rest-api-configuration-6.png) Figure 7. Configure TLS. 7. Go to the HTTP Request configuration window. 8. In TLS Configuration, select **Global Reference** and the **TLS context** value that you created earlier. You can also create the TLS context inline. ![An HTTP Request configuration including TLS and proxy details](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-consume-rest-api-configuration-8.png) Figure 8. Configure TLS in HTTP Request Configuration. --- product: Mule Runtime version: 4.12 --- # Consume Data from an API > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you build your application, you can start consuming data from an API. Review the following processes to consume data from a SOAP or REST API. ## Consume Data from a SOAP API To consume data from a SOAP API that does not have its own Anypoint Connector, configure Anypoint Connector for Web Service Consumer (Web Service Consumer Connector). Using the host, port, and address metadata retrieved from the API’s WSDL file, the connector provides the connection configuration you need for consuming a service from within your Mule application: See [Web Service Consumer Connector](https://docs.mulesoft.com/web-service-consumer-connector/latest/) for details. ## Consume Data from a REST API The following process focuses on configuring the HTTP Request Connector to call the REST API. It helps you to understand the basic anatomy of how a Mule application consumes a REST API, the minimum configuration required, how to consume examples, how to configure dynamic requests, how to manage HTTP Content-Type and encoding, and how to work with custom headers and security requirements. To consume data from a REST API from within a Mule application, you can configure Anypoint Connector for HTTP Request (HTTP Request Connector). If you connect to the same REST API many times or work with an API that has complex authentication protocols, consider [developing your own connector using the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). Check whether a connector already exists in [Anypoint Exchange](https://anypoint.mulesoft.com/exchange/) for the API you want to connect to. You can search in Exchange through Anypoint Studio’s Mule Palette. ## Basic Anatomy A Mule application consuming a REST API consists of the following: - One or more message processors configured to build your request - An HTTP request operation configured to call the REST API - One or more message processors configured to accept and process the response ![Consuming REST API Flow](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-consume-rest-api-flow.png) Figure 1. Consuming REST API Flow. You configure the portions of the application that build the request and process the response. ## Minimum Configuration The REST API you are consuming must have a [RAML](https://raml.org/) file that describes the API, so that the HTTP connector proactively presents you with smart suggestions. In the RAML file, you define the following: - Authentication - A base URI for configuring the outbound HTTP endpoint - Scope Based on authentication credentials, the application can limit calls to only GET requests on certain resources, for example, or otherwise limit access to a resource. - Resources You must configure the path of the resources for the outbound HTTP endpoint. - Methods You can accept POST as the default method for the HTTP outbound endpoint, or you can change this default to the method supported by your resource. - Input validation For POST and PUT calls, the API almost always requires that the input format, such as JSON or XML, match its schema. In Mule runtime engine, you can define or configure the following: - Output format After the HTTP request operation, your flow must include message processors to accept the response from the API and translate the response into a useable format. - Redirects If the API uses redirects, enable redirects in your HTTP request operation. - Timeout - Headers for methods POST, PUT, and DELETE requests almost always require headers. - URI and Query Parameters - Error handling See [HTTP Connector documentation](https://docs.mulesoft.com/http-connector/latest/#input-sources) for more information about how to configure the request operation. ### Consume REST API Example The following example consumes the [JSONPlaceholder API](https://jsonplaceholder.typicode.com/todos/1). The example shows only the configuration of the HTTP Request Connector, and to make it work, you must configure at least one Mule event source to trigger a message in the flow and at least one message processor to accept the response. See [REST API Examples documentation](https://docs.mulesoft.com/mule-runtime/4.12/rest-api-examples) for more information. In this API example: - The API doesn’t require authentication. - The base URL is `jsonplaceholder.typicode.com`. - The API is a mock API for development purposes. - The sample API requests show that to get information about user with `id=1` the request must be: https://jsonplaceholder.typicode.com/users/1 The parts of the URL are as follows: - Protocol: `http` - API Base URL: `jsonplaceholder.typicode.com` - Resource path: `/users/1` - Query Parameters: None, in this case. To implement this call in your Mule application, configure your HTTP request operation. ### Configure HTTP Request Operation in Anypoint Studio 1. From the Mule Palette in Studio, add an HTTP Request Connector to your application. 2. In the HTTP Request Configuration window, provide `jsonplaceholder.typicode.com` as the value for **Host**. 3. Set the **Port** value to 80. 4. Click **OK**: ![An HTTP Request configuration with Host and Port](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-consume-rest-api-configuration-1.png) Figure 2. HTTP Request configuration with Host and Port. 5. Navigate to the Request section from the HTTP Request operation’s properties editor > General tab and add `/users/1` in the **Path** field. Specifying this path completes the URL that you began to identify by specifying the host in the first step. 6. Select a method from the **Method** drop-down list (in this example, `GET`). 7. Save your application. ![An HTTP Request GET Method and Path](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-consume-rest-api-configuration-2.png) Figure 3. HTTP Request GET Method and Path. ### Configure HTTP Request Operation in XML The following XML code shows the configuration of the HTTP Request operation for the example: ```xml <...> ``` ### Example JSON Response For the JSONPlaceholder API example, the JSON response has the following structure: ```json { "userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": false } ``` You can transform the data in the **Advanced** tab of the HTTP Request operation. You can also define the target variable, which by default is the Payload. If this API has an associated RAML file, you can reference it in the configuration element of the connector. With that in place, after you select the verb and asset to call, Studio exposes the metadata corresponding to the output. Integration with other elements in a flow is simplified. ## Configure Dynamic Requests with DataWeave Expressions Most use cases require that you change the call to the API change dynamically based on data in the message. You can configure these dynamic requests by using DataWeave expressions. In the configuration examples documented in "Consume REST API Example", the request was hardcoded in the URL: https://jsonplaceholder.typicode.com/users/1 In the following GET request example, the call instructs Mule runtime engine to extract the user ID from the payload of the message, using the DataWeave expression `#[payload.user_id]`. https://jsonplaceholder.typicode.com/users/#\[payload.user\_id\] ### Configure Dynamic Requests in Anypoint Studio To perform the same operation by using Anypoint Studio, modify the path configuration with the desired DataWeave expression: in this case `#['/users/' ++ payload.user_id]`. ![A configure Dynamic Requests with DataWeave expressions in Path field](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-consume-rest-api-configuration-3.png) Figure 4. Configure Dynamic Requests with DataWeave expressions in Path field. You can also configure dynamic requests for the query or URI parameters, or for the HTTP method. Additionally, you can use [Configuration Properties](https://docs.mulesoft.com/mule-runtime/4.12/configuring-properties) to set any of these dynamic requests. ### Configure Dynamic Requests in XML The following example code in XML, shows the configuration of dynamic requests: ```xml <...> ``` ## HTTP Content-Type and Encoding When you send a POST request, Mule runtime engine adheres to the following rules regarding Content-Type and encoding of the body.

Content

Rules

For a String, char[]`, Reader, or similar*

* If the endpoint has explicitly set encoding, Mule runtime engine uses that encoding. * If the endpoint does not have explicitly set encoding, Mule runtime engine determines the encoding from the message property Content-Type. * If the Content-Type message property is not set, Mule runtime engine uses the Mule Context default configuration. * For Content-Type, Mule runtime engine sends the message property Content-Type, but with the actual encoding set.

For binary content

Encoding is not relevant. Mule runtime engine sets Content-Type as follows:

  • If the Content-Type property is set on the message, Mule runtime engine uses the defined content type.

  • If the Content-Type property is not set on the message, Mule runtime engine sets "application/octet-stream" as Content-Type.

## Custom Headers Some APIs require that you pass custom headers, such as your developer key, along with your requests. As with the query parameters, you can also add headers to your request on the HTTP Connector. For example, if the API you are consuming requires a developer key, then specify that key as a header on your requests by using the header name `accessKey`. You can add a property to set custom headers by using Anypoint Studio. ### Custom Headers in Anypoint Studio To set custom headers in Studio, review the following steps: - In the HTTP Request operation’s properties editor, select the **Headers** tab. - Click **Add**. - Define **Name** and **Value**. Both can be defined using expressions or properties placeholders. ![A custom header configuration in Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-consume-rest-api-configuration-4.png) Figure 5. Configure Custom Headers in the HTTP Request operation’s properties editor. ## Security Requirements If the API that you are calling requires complex authentication protocols, you can build your own connector to consume it. Otherwise, you can meet API security requirements by setting basic authentication credentials or configuring a global HTTPS connector. ### Basic Authentication If the REST API that you are consuming requires you to supply basic authentication credentials, you can provide them within the outbound HTTP endpoint configuration: 1. In Studio, go to the HTTP Request configuration window. 2. In Authentication, select **Basic Authentication**. 3. Type your username and password. These can also be set as properties placeholders. 4. Click **OK**. ![An HTTP Request showing settings for connection timeout, response buffer size, and TLS configuration](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-consume-rest-api-configuration-7.png) ### HTTPS Configuration If you are consuming a REST API that requires that incoming requests arrive via HTTPS, you can configure a global HTTPS Request connector in your Mule application, then reference the connector in your request operation. In the following example, you configure the HTTPS Request connector, create a Java keystore file (JKS) and [configure TLS](https://docs.mulesoft.com/mule-runtime/4.12/tls-configuration). #### Configure the HTTP Request Connector for HTTPS 1. In the HTTP Request Configuration window, navigate to General tab > Connection Configuration section. 2. Select **HTTPS** for the **Protocol**. 3. Click **OK**. ![An HTTP Request showing settings for protocol, host, port, and persistent connections configuration](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-consume-rest-api-configuration-5.png) Figure 6. Configure HTTPS Request Connector. #### Create a Keystore File Using the Java keytool in the bin directory of the Java installation, create a keystore file to certify the communication: 1. Using the command line, navigate to the Java installation directory on your machine. 2. Execute the following command: keytool -genkey -alias mule -keyalg RSA -keystore keystore.jks 3. When prompted, create two passwords and remember them for later use. This action creates a `jks` file in the local directory called `keystore.jks`. 4. Place your `keystore.jks` file: - If you use Studio, place the `keystore.jks` file into the `appname/src/main/resources` directory in Studio Package Explorer. - If you use XML in Mule runtime engine and want to use the file across multiple applications, place the file in the `MULE_HOME/conf` directory. - If you use XML in Mule runtime engine and want to use the file within this application, place the file in the `yourappname/src/main/resources` directory. 5. Reference the keystore in a global HTTPS Request connector. This connector is then referenced by the HTTP outbound endpoint within your flow. #### Configure TLS Follow these steps to configure TLS: 1. In Studio, go to the Global Elements view. 2. Select **Create** and search for "TLS Context". 3. In the Key Store Configuration section, select a type of keystore configuration from the drop-down menu: for example, **JKS** (Java Key Store) which is the default type. 4. For **Path**, specify the name of the keystore if you placed your keystore in the `appname/src/main/resources` directory; otherwise, specify `"/keystore.jks"`. 5. For **Key Password**, and **Password**, enter the passwords that you created when creating your keystore file. 6. Click **OK**. ![A TLS configuration showing settings for trust store and key store configurations](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-consume-rest-api-configuration-6.png) Figure 7. Configure TLS. 7. Go to the HTTP Request configuration window. 8. In TLS Configuration, select **Global Reference** and the **TLS context** value that you created earlier. You can also create the TLS context inline. ![An HTTP Request configuration including TLS and proxy details](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-consume-rest-api-configuration-8.png) Figure 8. Configure TLS in HTTP Request Configuration. --- product: Mule Runtime version: 4.3 --- # Consume Data from an API > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you build your application, you can start consuming data from an API. Review the following processes to consume data from a SOAP or REST API. ## Consume Data from a SOAP API To consume data from a SOAP API that does not have its own Anypoint Connector, configure Anypoint Connector for Web Service Consumer (Web Service Consumer Connector). Using the host, port, and address metadata retrieved from the API’s WSDL file, the connector provides the connection configuration you need for consuming a service from within your Mule application: See [Web Service Consumer Connector](https://docs.mulesoft.com/web-service-consumer-connector/latest/) for details. ## Consume Data from a REST API The following process focuses on configuring the HTTP Request Connector to call the REST API. It helps you to understand the basic anatomy of how a Mule application consumes a REST API, the minimum configuration required, how to consume examples, how to configure dynamic requests, how to manage HTTP Content-Type and encoding, and how to work with custom headers and security requirements. To consume data from a REST API from within a Mule application, you can configure Anypoint Connector for HTTP Request (HTTP Request Connector). If you connect to the same REST API many times or work with an API that has complex authentication protocols, consider [developing your own connector using the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). Check whether a connector already exists in [Anypoint Exchange](https://anypoint.mulesoft.com/exchange/) for the API you want to connect to. You can search in Exchange through Anypoint Studio’s Mule Palette. ## Basic Anatomy A Mule application consuming a REST API consists of the following: - One or more message processors configured to build your request - An HTTP request operation configured to call the REST API - One or more message processors configured to accept and process the response ![Consuming REST API Flow](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-consume-rest-api-flow.png) Figure 1. Consuming REST API Flow. You configure the portions of the application that build the request and process the response. ## Minimum Configuration The REST API you are consuming must have a [RAML](https://raml.org/) file that describes the API, so that the HTTP connector proactively presents you with smart suggestions. In the RAML file, you define the following: - Authentication - A base URI for configuring the outbound HTTP endpoint - Scope Based on authentication credentials, the application can limit calls to only GET requests on certain resources, for example, or otherwise limit access to a resource. - Resources You must configure the path of the resources for the outbound HTTP endpoint. - Methods You can accept POST as the default method for the HTTP outbound endpoint, or you can change this default to the method supported by your resource. - Input validation For POST and PUT calls, the API almost always requires that the input format, such as JSON or XML, match its schema. In Mule runtime engine, you can define or configure the following: - Output format After the HTTP request operation, your flow must include message processors to accept the response from the API and translate the response into a useable format. - Redirects If the API uses redirects, enable redirects in your HTTP request operation. - Timeout - Headers for methods POST, PUT, and DELETE requests almost always require headers. - URI and Query Parameters - Error handling See [HTTP Connector documentation](https://docs.mulesoft.com/http-connector/latest/#input-sources) for more information about how to configure the request operation. ### Consume REST API Example The following example consumes the [JSONPlaceholder API](https://jsonplaceholder.typicode.com/todos/1). The example shows only the configuration of the HTTP Request Connector, and to make it work, you must configure at least a message source to trigger a message in the flow and at least one message processor to accept the response. See [REST API Examples documentation](https://docs.mulesoft.com/mule-runtime/4.3/rest-api-examples) for more information. In this API example: - The API doesn’t require authentication. - The base URL is `jsonplaceholder.typicode.com`. - The API is a mock API for development purposes. - The sample API requests show that to get information about user with `id=1` the request must be: https://jsonplaceholder.typicode.com/users/1 The parts of the URL are as follows: - Protocol: `http` - API Base URL: `jsonplaceholder.typicode.com` - Resource path: `/users/1` - Query Parameters: None, in this case. To implement this call in your Mule application, configure your HTTP request operation. ### Configure HTTP Request Operation in Anypoint Studio 1. From the Mule Palette in Studio, add an HTTP Request Connector to your application. 2. In the HTTP Request Configuration window, provide `jsonplaceholder.typicode.com` as the value for **Host**. 3. Set the **Port** value to 80. 4. Click **OK**: ![HTTP Request configuration with Host and Port](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-consume-rest-api-configuration-1.png) Figure 2. HTTP Request configuration with Host and Port. 5. Navigate to the Request section from the HTTP Request operation’s properties editor > General tab and add `/users/1` in the **Path** field. Specifying this path completes the URL that you began to identify by specifying the host in the first step. 6. Select a method from the **Method** drop-down list (in this example, `GET`). 7. Save your application. ![HTTP Request GET Method and Path](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-consume-rest-api-configuration-2.png) Figure 3. HTTP Request GET Method and Path. ### Configure HTTP Request Operation in XML The following XML code shows the configuration of the HTTP Request operation for the example: ```xml <...> ``` ### Example JSON Response For the JSONPlaceholder API example, the JSON response has the following structure: ```json { "userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": false } ``` You can transform the data in the **Advanced** tab of the HTTP Request operation. You can also define the target variable, which by default is the Payload. If this API has an associated RAML file, you can reference it in the configuration element of the connector. With that in place, after you select the verb and asset to call, Studio exposes the metadata corresponding to the output. Integration with other elements in a flow is simplified. ## Configure Dynamic Requests with DataWeave Expressions Most use cases require that you change the call to the API change dynamically based on data in the message. You can configure these dynamic requests by using DataWeave expressions. In the configuration examples documented in "Consume REST API Example", the request was hardcoded in the URL: https://jsonplaceholder.typicode.com/users/1 In the following GET request example, the call instructs Mule runtime engine to extract the user ID from the payload of the message, using the DataWeave expression `#[payload.user_id]`. https://jsonplaceholder.typicode.com/users/#\[payload.user\_id\] ### Configure Dynamic Requests in Anypoint Studio To perform the same operation by using Anypoint Studio, modify the path configuration with the desired DataWeave expression: in this case `#['/users/' ++ payload.user_id]`. ![Configure Dynamic Requests with DataWeave expressions in Path field](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-consume-rest-api-configuration-3.png) Figure 4. Configure Dynamic Requests with DataWeave expressions in Path field. You can also configure dynamic requests for the query or URI parameters, or for the HTTP method. Additionally, you can use [Configuration Properties](https://docs.mulesoft.com/mule-runtime/4.3/configuring-properties) to set any of these dynamic requests. ### Configure Dynamic Requests in XML The following example code in XML, shows the configuration of dynamic requests: ```xml <...> ``` ## HTTP Content-Type and Encoding When you send a POST request, Mule runtime engine adheres to the following rules regarding Content-Type and encoding of the body.

Content

Rules

For a String, char[]`, Reader, or similar*

* If the endpoint has explicitly set encoding, Mule runtime engine uses that encoding. * If the endpoint does not have explicitly set encoding, Mule runtime engine determines the encoding from the message property Content-Type. * If the Content-Type message property is not set, Mule runtime engine uses the Mule Context default configuration. * For Content-Type, Mule runtime engine sends the message property Content-Type, but with the actual encoding set.

For binary content

Encoding is not relevant. Mule runtime engine sets Content-Type as follows:

  • If the Content-Type property is set on the message, Mule runtime engine uses the defined content type.

  • If the Content-Type property is not set on the message, Mule runtime engine sets "application/octet-stream" as Content-Type.

## Custom Headers Some APIs require that you pass custom headers, such as your developer key, along with your requests. As with the query parameters, you can also add headers to your request on the HTTP Connector. For example, if the API you are consuming requires a developer key, then specify that key as a header on your requests by using the header name `accessKey`. You can add a property to set custom headers by using Anypoint Studio. ### Custom Headers in Anypoint Studio To set custom headers in Studio, review the following steps: - In the HTTP Request operation’s properties editor, select the **Headers** tab. - Click **Add**. - Define **Name** and **Value**. Both can be defined using expressions or properties placeholders. ![Configure Customer Headers in Studio](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-consume-rest-api-configuration-4.png) Figure 5. Configure Custom Headers in the HTTP Request operation’s properties editor. ## Security Requirements If the API that you are calling requires complex authentication protocols, you can build your own connector to consume it. Otherwise, you can meet API security requirements by setting basic authentication credentials or configuring a global HTTPS connector. ### Basic Authentication If the REST API that you are consuming requires you to supply basic authentication credentials, you can provide them within the outbound HTTP endpoint configuration: 1. In Studio, go to the HTTP Request configuration window. 2. In Authentication, select **Basic Authentication**. 3. Type your username and password. These can also be set as properties placeholders. 4. Click **OK**. ![mruntime consume rest api configuration 7](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-consume-rest-api-configuration-7.png) ### HTTPS Configuration If you are consuming a REST API that requires that incoming requests arrive via HTTPS, you can configure a global HTTPS Request connector in your Mule application, then reference the connector in your request operation. In the following example, you configure the HTTPS Request connector, create a Java keystore file (JKS) and [configure TLS](https://docs.mulesoft.com/mule-runtime/4.3/tls-configuration). #### Configure the HTTP Request Connector for HTTPS 1. In the HTTP Request Configuration window, navigate to General tab > Connection Configuration section. 2. Select **HTTPS** for the **Protocol**. 3. Click **OK**. ![Configure HTTPS Request connector](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-consume-rest-api-configuration-5.png) Figure 6. Configure HTTPS Request Connector. #### Create a Keystore File Using the Java keytool in the bin directory of the Java installation, create a keystore file to certify the communication: 1. Using the command line, navigate to the Java installation directory on your machine. 2. Execute the following command: keytool -genkey -alias mule -keyalg RSA -keystore keystore.jks 3. When prompted, create two passwords and remember them for later use. This action creates a `jks` file in the local directory called `keystore.jks`. 4. Place your `keystore.jks` file: - If you use Studio, place the `keystore.jks` file into the `appname/src/main/resources` directory in Studio Package Explorer. - If you use XML in Mule runtime engine and want to use the file across multiple applications, place the file in the `MULE_HOME/conf` directory. - If you use XML in Mule runtime engine and want to use the file within this application, place the file in the `yourappname/src/main/resources` directory. 5. Reference the keystore in a global HTTPS Request connector. This connector is then referenced by the HTTP outbound endpoint within your flow. #### Configure TLS Follow these steps to configure TLS: 1. In Studio, go to the Global Elements view. 2. Select **Create** and search for "TLS Context". 3. In the Key Store Configuration section, select a type of keystore configuration from the drop-down menu: for example, **JKS** (Java Key Store) which is the default type. 4. For **Path**, specify the name of the keystore if you placed your keystore in the `appname/src/main/resources` directory; otherwise, specify `"/keystore.jks"`. 5. For **Key Password**, and **Password**, enter the passwords that you created when creating your keystore file. 6. Click **OK**. ![Configure TLS](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-consume-rest-api-configuration-6.png) Figure 7. Configure TLS. 7. Go to the HTTP Request configuration window. 8. In TLS Configuration, select **Global Reference** and the **TLS context** value that you created earlier. You can also create the TLS context inline. ![Configure TLS in HTTP Request Configuration](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-consume-rest-api-configuration-8.png) Figure 8. Configure TLS in HTTP Request Configuration. --- product: Mule Runtime version: 4.4 --- # Consume Data from an API > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you build your application, you can start consuming data from an API. Review the following processes to consume data from a SOAP or REST API. ## Consume Data from a SOAP API To consume data from a SOAP API that does not have its own Anypoint Connector, configure Anypoint Connector for Web Service Consumer (Web Service Consumer Connector). Using the host, port, and address metadata retrieved from the API’s WSDL file, the connector provides the connection configuration you need for consuming a service from within your Mule application: See [Web Service Consumer Connector](https://docs.mulesoft.com/web-service-consumer-connector/latest/) for details. ## Consume Data from a REST API The following process focuses on configuring the HTTP Request Connector to call the REST API. It helps you to understand the basic anatomy of how a Mule application consumes a REST API, the minimum configuration required, how to consume examples, how to configure dynamic requests, how to manage HTTP Content-Type and encoding, and how to work with custom headers and security requirements. To consume data from a REST API from within a Mule application, you can configure Anypoint Connector for HTTP Request (HTTP Request Connector). If you connect to the same REST API many times or work with an API that has complex authentication protocols, consider [developing your own connector using the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). Check whether a connector already exists in [Anypoint Exchange](https://anypoint.mulesoft.com/exchange/) for the API you want to connect to. You can search in Exchange through Anypoint Studio’s Mule Palette. ## Basic Anatomy A Mule application consuming a REST API consists of the following: - One or more message processors configured to build your request - An HTTP request operation configured to call the REST API - One or more message processors configured to accept and process the response ![Consuming REST API Flow](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-consume-rest-api-flow.png) Figure 1. Consuming REST API Flow. You configure the portions of the application that build the request and process the response. ## Minimum Configuration The REST API you are consuming must have a [RAML](https://raml.org/) file that describes the API, so that the HTTP connector proactively presents you with smart suggestions. In the RAML file, you define the following: - Authentication - A base URI for configuring the outbound HTTP endpoint - Scope Based on authentication credentials, the application can limit calls to only GET requests on certain resources, for example, or otherwise limit access to a resource. - Resources You must configure the path of the resources for the outbound HTTP endpoint. - Methods You can accept POST as the default method for the HTTP outbound endpoint, or you can change this default to the method supported by your resource. - Input validation For POST and PUT calls, the API almost always requires that the input format, such as JSON or XML, match its schema. In Mule runtime engine, you can define or configure the following: - Output format After the HTTP request operation, your flow must include message processors to accept the response from the API and translate the response into a useable format. - Redirects If the API uses redirects, enable redirects in your HTTP request operation. - Timeout - Headers for methods POST, PUT, and DELETE requests almost always require headers. - URI and Query Parameters - Error handling See [HTTP Connector documentation](https://docs.mulesoft.com/http-connector/latest/#input-sources) for more information about how to configure the request operation. ### Consume REST API Example The following example consumes the [JSONPlaceholder API](https://jsonplaceholder.typicode.com/todos/1). The example shows only the configuration of the HTTP Request Connector, and to make it work, you must configure at least one Mule event source to trigger a message in the flow and at least one message processor to accept the response. See [REST API Examples documentation](https://docs.mulesoft.com/mule-runtime/4.4/rest-api-examples) for more information. In this API example: - The API doesn’t require authentication. - The base URL is `jsonplaceholder.typicode.com`. - The API is a mock API for development purposes. - The sample API requests show that to get information about user with `id=1` the request must be: https://jsonplaceholder.typicode.com/users/1 The parts of the URL are as follows: - Protocol: `http` - API Base URL: `jsonplaceholder.typicode.com` - Resource path: `/users/1` - Query Parameters: None, in this case. To implement this call in your Mule application, configure your HTTP request operation. ### Configure HTTP Request Operation in Anypoint Studio 1. From the Mule Palette in Studio, add an HTTP Request Connector to your application. 2. In the HTTP Request Configuration window, provide `jsonplaceholder.typicode.com` as the value for **Host**. 3. Set the **Port** value to 80. 4. Click **OK**: ![HTTP Request configuration with Host and Port](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-consume-rest-api-configuration-1.png) Figure 2. HTTP Request configuration with Host and Port. 5. Navigate to the Request section from the HTTP Request operation’s properties editor > General tab and add `/users/1` in the **Path** field. Specifying this path completes the URL that you began to identify by specifying the host in the first step. 6. Select a method from the **Method** drop-down list (in this example, `GET`). 7. Save your application. ![HTTP Request GET Method and Path](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-consume-rest-api-configuration-2.png) Figure 3. HTTP Request GET Method and Path. ### Configure HTTP Request Operation in XML The following XML code shows the configuration of the HTTP Request operation for the example: ```xml <...> ``` ### Example JSON Response For the JSONPlaceholder API example, the JSON response has the following structure: ```json { "userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": false } ``` You can transform the data in the **Advanced** tab of the HTTP Request operation. You can also define the target variable, which by default is the Payload. If this API has an associated RAML file, you can reference it in the configuration element of the connector. With that in place, after you select the verb and asset to call, Studio exposes the metadata corresponding to the output. Integration with other elements in a flow is simplified. ## Configure Dynamic Requests with DataWeave Expressions Most use cases require that you change the call to the API change dynamically based on data in the message. You can configure these dynamic requests by using DataWeave expressions. In the configuration examples documented in "Consume REST API Example", the request was hardcoded in the URL: https://jsonplaceholder.typicode.com/users/1 In the following GET request example, the call instructs Mule runtime engine to extract the user ID from the payload of the message, using the DataWeave expression `#[payload.user_id]`. https://jsonplaceholder.typicode.com/users/#\[payload.user\_id\] ### Configure Dynamic Requests in Anypoint Studio To perform the same operation by using Anypoint Studio, modify the path configuration with the desired DataWeave expression: in this case `#['/users/' ++ payload.user_id]`. ![Configure Dynamic Requests with DataWeave expressions in Path field](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-consume-rest-api-configuration-3.png) Figure 4. Configure Dynamic Requests with DataWeave expressions in Path field. You can also configure dynamic requests for the query or URI parameters, or for the HTTP method. Additionally, you can use [Configuration Properties](https://docs.mulesoft.com/mule-runtime/4.4/configuring-properties) to set any of these dynamic requests. ### Configure Dynamic Requests in XML The following example code in XML, shows the configuration of dynamic requests: ```xml <...> ``` ## HTTP Content-Type and Encoding When you send a POST request, Mule runtime engine adheres to the following rules regarding Content-Type and encoding of the body.

Content

Rules

For a String, char[]`, Reader, or similar*

* If the endpoint has explicitly set encoding, Mule runtime engine uses that encoding. * If the endpoint does not have explicitly set encoding, Mule runtime engine determines the encoding from the message property Content-Type. * If the Content-Type message property is not set, Mule runtime engine uses the Mule Context default configuration. * For Content-Type, Mule runtime engine sends the message property Content-Type, but with the actual encoding set.

For binary content

Encoding is not relevant. Mule runtime engine sets Content-Type as follows:

  • If the Content-Type property is set on the message, Mule runtime engine uses the defined content type.

  • If the Content-Type property is not set on the message, Mule runtime engine sets "application/octet-stream" as Content-Type.

## Custom Headers Some APIs require that you pass custom headers, such as your developer key, along with your requests. As with the query parameters, you can also add headers to your request on the HTTP Connector. For example, if the API you are consuming requires a developer key, then specify that key as a header on your requests by using the header name `accessKey`. You can add a property to set custom headers by using Anypoint Studio. ### Custom Headers in Anypoint Studio To set custom headers in Studio, review the following steps: - In the HTTP Request operation’s properties editor, select the **Headers** tab. - Click **Add**. - Define **Name** and **Value**. Both can be defined using expressions or properties placeholders. ![Configure Customer Headers in Studio](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-consume-rest-api-configuration-4.png) Figure 5. Configure Custom Headers in the HTTP Request operation’s properties editor. ## Security Requirements If the API that you are calling requires complex authentication protocols, you can build your own connector to consume it. Otherwise, you can meet API security requirements by setting basic authentication credentials or configuring a global HTTPS connector. ### Basic Authentication If the REST API that you are consuming requires you to supply basic authentication credentials, you can provide them within the outbound HTTP endpoint configuration: 1. In Studio, go to the HTTP Request configuration window. 2. In Authentication, select **Basic Authentication**. 3. Type your username and password. These can also be set as properties placeholders. 4. Click **OK**. ![mruntime consume rest api configuration 7](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-consume-rest-api-configuration-7.png) ### HTTPS Configuration If you are consuming a REST API that requires that incoming requests arrive via HTTPS, you can configure a global HTTPS Request connector in your Mule application, then reference the connector in your request operation. In the following example, you configure the HTTPS Request connector, create a Java keystore file (JKS) and [configure TLS](https://docs.mulesoft.com/mule-runtime/4.4/tls-configuration). #### Configure the HTTP Request Connector for HTTPS 1. In the HTTP Request Configuration window, navigate to General tab > Connection Configuration section. 2. Select **HTTPS** for the **Protocol**. 3. Click **OK**. ![Configure HTTPS Request connector](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-consume-rest-api-configuration-5.png) Figure 6. Configure HTTPS Request Connector. #### Create a Keystore File Using the Java keytool in the bin directory of the Java installation, create a keystore file to certify the communication: 1. Using the command line, navigate to the Java installation directory on your machine. 2. Execute the following command: keytool -genkey -alias mule -keyalg RSA -keystore keystore.jks 3. When prompted, create two passwords and remember them for later use. This action creates a `jks` file in the local directory called `keystore.jks`. 4. Place your `keystore.jks` file: - If you use Studio, place the `keystore.jks` file into the `appname/src/main/resources` directory in Studio Package Explorer. - If you use XML in Mule runtime engine and want to use the file across multiple applications, place the file in the `MULE_HOME/conf` directory. - If you use XML in Mule runtime engine and want to use the file within this application, place the file in the `yourappname/src/main/resources` directory. 5. Reference the keystore in a global HTTPS Request connector. This connector is then referenced by the HTTP outbound endpoint within your flow. #### Configure TLS Follow these steps to configure TLS: 1. In Studio, go to the Global Elements view. 2. Select **Create** and search for "TLS Context". 3. In the Key Store Configuration section, select a type of keystore configuration from the drop-down menu: for example, **JKS** (Java Key Store) which is the default type. 4. For **Path**, specify the name of the keystore if you placed your keystore in the `appname/src/main/resources` directory; otherwise, specify `"/keystore.jks"`. 5. For **Key Password**, and **Password**, enter the passwords that you created when creating your keystore file. 6. Click **OK**. ![Configure TLS](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-consume-rest-api-configuration-6.png) Figure 7. Configure TLS. 7. Go to the HTTP Request configuration window. 8. In TLS Configuration, select **Global Reference** and the **TLS context** value that you created earlier. You can also create the TLS context inline. ![Configure TLS in HTTP Request Configuration](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-consume-rest-api-configuration-8.png) Figure 8. Configure TLS in HTTP Request Configuration. --- product: Mule Runtime version: 4.6 --- # Consume Data from an API > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you build your application, you can start consuming data from an API. Review the following processes to consume data from a SOAP or REST API. ## Consume Data from a SOAP API To consume data from a SOAP API that does not have its own Anypoint Connector, configure Anypoint Connector for Web Service Consumer (Web Service Consumer Connector). Using the host, port, and address metadata retrieved from the API’s WSDL file, the connector provides the connection configuration you need for consuming a service from within your Mule application: See [Web Service Consumer Connector](https://docs.mulesoft.com/web-service-consumer-connector/latest/) for details. ## Consume Data from a REST API The following process focuses on configuring the HTTP Request Connector to call the REST API. It helps you to understand the basic anatomy of how a Mule application consumes a REST API, the minimum configuration required, how to consume examples, how to configure dynamic requests, how to manage HTTP Content-Type and encoding, and how to work with custom headers and security requirements. To consume data from a REST API from within a Mule application, you can configure Anypoint Connector for HTTP Request (HTTP Request Connector). If you connect to the same REST API many times or work with an API that has complex authentication protocols, consider [developing your own connector using the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). Check whether a connector already exists in [Anypoint Exchange](https://anypoint.mulesoft.com/exchange/) for the API you want to connect to. You can search in Exchange through Anypoint Studio’s Mule Palette. ## Basic Anatomy A Mule application consuming a REST API consists of the following: - One or more message processors configured to build your request - An HTTP request operation configured to call the REST API - One or more message processors configured to accept and process the response ![Consuming REST API Flow](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-consume-rest-api-flow.png) Figure 1. Consuming REST API Flow. You configure the portions of the application that build the request and process the response. ## Minimum Configuration The REST API you are consuming must have a [RAML](https://raml.org/) file that describes the API, so that the HTTP connector proactively presents you with smart suggestions. In the RAML file, you define the following: - Authentication - A base URI for configuring the outbound HTTP endpoint - Scope Based on authentication credentials, the application can limit calls to only GET requests on certain resources, for example, or otherwise limit access to a resource. - Resources You must configure the path of the resources for the outbound HTTP endpoint. - Methods You can accept POST as the default method for the HTTP outbound endpoint, or you can change this default to the method supported by your resource. - Input validation For POST and PUT calls, the API almost always requires that the input format, such as JSON or XML, match its schema. In Mule runtime engine, you can define or configure the following: - Output format After the HTTP request operation, your flow must include message processors to accept the response from the API and translate the response into a useable format. - Redirects If the API uses redirects, enable redirects in your HTTP request operation. - Timeout - Headers for methods POST, PUT, and DELETE requests almost always require headers. - URI and Query Parameters - Error handling See [HTTP Connector documentation](https://docs.mulesoft.com/http-connector/latest/#input-sources) for more information about how to configure the request operation. ### Consume REST API Example The following example consumes the [JSONPlaceholder API](https://jsonplaceholder.typicode.com/todos/1). The example shows only the configuration of the HTTP Request Connector, and to make it work, you must configure at least one Mule event source to trigger a message in the flow and at least one message processor to accept the response. See [REST API Examples documentation](https://docs.mulesoft.com/mule-runtime/4.6/rest-api-examples) for more information. In this API example: - The API doesn’t require authentication. - The base URL is `jsonplaceholder.typicode.com`. - The API is a mock API for development purposes. - The sample API requests show that to get information about user with `id=1` the request must be: https://jsonplaceholder.typicode.com/users/1 The parts of the URL are as follows: - Protocol: `http` - API Base URL: `jsonplaceholder.typicode.com` - Resource path: `/users/1` - Query Parameters: None, in this case. To implement this call in your Mule application, configure your HTTP request operation. ### Configure HTTP Request Operation in Anypoint Studio 1. From the Mule Palette in Studio, add an HTTP Request Connector to your application. 2. In the HTTP Request Configuration window, provide `jsonplaceholder.typicode.com` as the value for **Host**. 3. Set the **Port** value to 80. 4. Click **OK**: ![HTTP Request configuration with Host and Port](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-consume-rest-api-configuration-1.png) Figure 2. HTTP Request configuration with Host and Port. 5. Navigate to the Request section from the HTTP Request operation’s properties editor > General tab and add `/users/1` in the **Path** field. Specifying this path completes the URL that you began to identify by specifying the host in the first step. 6. Select a method from the **Method** drop-down list (in this example, `GET`). 7. Save your application. ![HTTP Request GET Method and Path](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-consume-rest-api-configuration-2.png) Figure 3. HTTP Request GET Method and Path. ### Configure HTTP Request Operation in XML The following XML code shows the configuration of the HTTP Request operation for the example: ```xml <...> ``` ### Example JSON Response For the JSONPlaceholder API example, the JSON response has the following structure: ```json { "userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": false } ``` You can transform the data in the **Advanced** tab of the HTTP Request operation. You can also define the target variable, which by default is the Payload. If this API has an associated RAML file, you can reference it in the configuration element of the connector. With that in place, after you select the verb and asset to call, Studio exposes the metadata corresponding to the output. Integration with other elements in a flow is simplified. ## Configure Dynamic Requests with DataWeave Expressions Most use cases require that you change the call to the API change dynamically based on data in the message. You can configure these dynamic requests by using DataWeave expressions. In the configuration examples documented in "Consume REST API Example", the request was hardcoded in the URL: https://jsonplaceholder.typicode.com/users/1 In the following GET request example, the call instructs Mule runtime engine to extract the user ID from the payload of the message, using the DataWeave expression `#[payload.user_id]`. https://jsonplaceholder.typicode.com/users/#\[payload.user\_id\] ### Configure Dynamic Requests in Anypoint Studio To perform the same operation by using Anypoint Studio, modify the path configuration with the desired DataWeave expression: in this case `#['/users/' ++ payload.user_id]`. ![Configure Dynamic Requests with DataWeave expressions in Path field](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-consume-rest-api-configuration-3.png) Figure 4. Configure Dynamic Requests with DataWeave expressions in Path field. You can also configure dynamic requests for the query or URI parameters, or for the HTTP method. Additionally, you can use [Configuration Properties](https://docs.mulesoft.com/mule-runtime/4.6/configuring-properties) to set any of these dynamic requests. ### Configure Dynamic Requests in XML The following example code in XML, shows the configuration of dynamic requests: ```xml <...> ``` ## HTTP Content-Type and Encoding When you send a POST request, Mule runtime engine adheres to the following rules regarding Content-Type and encoding of the body.

Content

Rules

For a String, char[]`, Reader, or similar*

* If the endpoint has explicitly set encoding, Mule runtime engine uses that encoding. * If the endpoint does not have explicitly set encoding, Mule runtime engine determines the encoding from the message property Content-Type. * If the Content-Type message property is not set, Mule runtime engine uses the Mule Context default configuration. * For Content-Type, Mule runtime engine sends the message property Content-Type, but with the actual encoding set.

For binary content

Encoding is not relevant. Mule runtime engine sets Content-Type as follows:

  • If the Content-Type property is set on the message, Mule runtime engine uses the defined content type.

  • If the Content-Type property is not set on the message, Mule runtime engine sets "application/octet-stream" as Content-Type.

## Custom Headers Some APIs require that you pass custom headers, such as your developer key, along with your requests. As with the query parameters, you can also add headers to your request on the HTTP Connector. For example, if the API you are consuming requires a developer key, then specify that key as a header on your requests by using the header name `accessKey`. You can add a property to set custom headers by using Anypoint Studio. ### Custom Headers in Anypoint Studio To set custom headers in Studio, review the following steps: - In the HTTP Request operation’s properties editor, select the **Headers** tab. - Click **Add**. - Define **Name** and **Value**. Both can be defined using expressions or properties placeholders. ![Configure Customer Headers in Studio](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-consume-rest-api-configuration-4.png) Figure 5. Configure Custom Headers in the HTTP Request operation’s properties editor. ## Security Requirements If the API that you are calling requires complex authentication protocols, you can build your own connector to consume it. Otherwise, you can meet API security requirements by setting basic authentication credentials or configuring a global HTTPS connector. ### Basic Authentication If the REST API that you are consuming requires you to supply basic authentication credentials, you can provide them within the outbound HTTP endpoint configuration: 1. In Studio, go to the HTTP Request configuration window. 2. In Authentication, select **Basic Authentication**. 3. Type your username and password. These can also be set as properties placeholders. 4. Click **OK**. ![mruntime consume rest api configuration 7](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-consume-rest-api-configuration-7.png) ### HTTPS Configuration If you are consuming a REST API that requires that incoming requests arrive via HTTPS, you can configure a global HTTPS Request connector in your Mule application, then reference the connector in your request operation. In the following example, you configure the HTTPS Request connector, create a Java keystore file (JKS) and [configure TLS](https://docs.mulesoft.com/mule-runtime/4.6/tls-configuration). #### Configure the HTTP Request Connector for HTTPS 1. In the HTTP Request Configuration window, navigate to General tab > Connection Configuration section. 2. Select **HTTPS** for the **Protocol**. 3. Click **OK**. ![Configure HTTPS Request connector](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-consume-rest-api-configuration-5.png) Figure 6. Configure HTTPS Request Connector. #### Create a Keystore File Using the Java keytool in the bin directory of the Java installation, create a keystore file to certify the communication: 1. Using the command line, navigate to the Java installation directory on your machine. 2. Execute the following command: keytool -genkey -alias mule -keyalg RSA -keystore keystore.jks 3. When prompted, create two passwords and remember them for later use. This action creates a `jks` file in the local directory called `keystore.jks`. 4. Place your `keystore.jks` file: - If you use Studio, place the `keystore.jks` file into the `appname/src/main/resources` directory in Studio Package Explorer. - If you use XML in Mule runtime engine and want to use the file across multiple applications, place the file in the `MULE_HOME/conf` directory. - If you use XML in Mule runtime engine and want to use the file within this application, place the file in the `yourappname/src/main/resources` directory. 5. Reference the keystore in a global HTTPS Request connector. This connector is then referenced by the HTTP outbound endpoint within your flow. #### Configure TLS Follow these steps to configure TLS: 1. In Studio, go to the Global Elements view. 2. Select **Create** and search for "TLS Context". 3. In the Key Store Configuration section, select a type of keystore configuration from the drop-down menu: for example, **JKS** (Java Key Store) which is the default type. 4. For **Path**, specify the name of the keystore if you placed your keystore in the `appname/src/main/resources` directory; otherwise, specify `"/keystore.jks"`. 5. For **Key Password**, and **Password**, enter the passwords that you created when creating your keystore file. 6. Click **OK**. ![Configure TLS](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-consume-rest-api-configuration-6.png) Figure 7. Configure TLS. 7. Go to the HTTP Request configuration window. 8. In TLS Configuration, select **Global Reference** and the **TLS context** value that you created earlier. You can also create the TLS context inline. ![Configure TLS in HTTP Request Configuration](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-consume-rest-api-configuration-8.png) Figure 8. Configure TLS in HTTP Request Configuration. --- product: Mule Runtime version: 4.9 --- # Consume Data from an API > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you build your application, you can start consuming data from an API. Review the following processes to consume data from a SOAP or REST API. ## Consume Data from a SOAP API To consume data from a SOAP API that does not have its own Anypoint Connector, configure Anypoint Connector for Web Service Consumer (Web Service Consumer Connector). Using the host, port, and address metadata retrieved from the API’s WSDL file, the connector provides the connection configuration you need for consuming a service from within your Mule application: See [Web Service Consumer Connector](https://docs.mulesoft.com/web-service-consumer-connector/latest/) for details. ## Consume Data from a REST API The following process focuses on configuring the HTTP Request Connector to call the REST API. It helps you to understand the basic anatomy of how a Mule application consumes a REST API, the minimum configuration required, how to consume examples, how to configure dynamic requests, how to manage HTTP Content-Type and encoding, and how to work with custom headers and security requirements. To consume data from a REST API from within a Mule application, you can configure Anypoint Connector for HTTP Request (HTTP Request Connector). If you connect to the same REST API many times or work with an API that has complex authentication protocols, consider [developing your own connector using the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). Check whether a connector already exists in [Anypoint Exchange](https://anypoint.mulesoft.com/exchange/) for the API you want to connect to. You can search in Exchange through Anypoint Studio’s Mule Palette. ## Basic Anatomy A Mule application consuming a REST API consists of the following: - One or more message processors configured to build your request - An HTTP request operation configured to call the REST API - One or more message processors configured to accept and process the response ![Consuming REST API Flow](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-consume-rest-api-flow.png) Figure 1. Consuming REST API Flow. You configure the portions of the application that build the request and process the response. ## Minimum Configuration The REST API you are consuming must have a [RAML](https://raml.org/) file that describes the API, so that the HTTP connector proactively presents you with smart suggestions. In the RAML file, you define the following: - Authentication - A base URI for configuring the outbound HTTP endpoint - Scope Based on authentication credentials, the application can limit calls to only GET requests on certain resources, for example, or otherwise limit access to a resource. - Resources You must configure the path of the resources for the outbound HTTP endpoint. - Methods You can accept POST as the default method for the HTTP outbound endpoint, or you can change this default to the method supported by your resource. - Input validation For POST and PUT calls, the API almost always requires that the input format, such as JSON or XML, match its schema. In Mule runtime engine, you can define or configure the following: - Output format After the HTTP request operation, your flow must include message processors to accept the response from the API and translate the response into a useable format. - Redirects If the API uses redirects, enable redirects in your HTTP request operation. - Timeout - Headers for methods POST, PUT, and DELETE requests almost always require headers. - URI and Query Parameters - Error handling See [HTTP Connector documentation](https://docs.mulesoft.com/http-connector/latest/#input-sources) for more information about how to configure the request operation. ### Consume REST API Example The following example consumes the [JSONPlaceholder API](https://jsonplaceholder.typicode.com/todos/1). The example shows only the configuration of the HTTP Request Connector, and to make it work, you must configure at least one Mule event source to trigger a message in the flow and at least one message processor to accept the response. See [REST API Examples documentation](https://docs.mulesoft.com/mule-runtime/4.9/rest-api-examples) for more information. In this API example: - The API doesn’t require authentication. - The base URL is `jsonplaceholder.typicode.com`. - The API is a mock API for development purposes. - The sample API requests show that to get information about user with `id=1` the request must be: https://jsonplaceholder.typicode.com/users/1 The parts of the URL are as follows: - Protocol: `http` - API Base URL: `jsonplaceholder.typicode.com` - Resource path: `/users/1` - Query Parameters: None, in this case. To implement this call in your Mule application, configure your HTTP request operation. ### Configure HTTP Request Operation in Anypoint Studio 1. From the Mule Palette in Studio, add an HTTP Request Connector to your application. 2. In the HTTP Request Configuration window, provide `jsonplaceholder.typicode.com` as the value for **Host**. 3. Set the **Port** value to 80. 4. Click **OK**: ![An HTTP Request configuration with Host and Port](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-consume-rest-api-configuration-1.png) Figure 2. HTTP Request configuration with Host and Port. 5. Navigate to the Request section from the HTTP Request operation’s properties editor > General tab and add `/users/1` in the **Path** field. Specifying this path completes the URL that you began to identify by specifying the host in the first step. 6. Select a method from the **Method** drop-down list (in this example, `GET`). 7. Save your application. ![An HTTP Request GET Method and Path](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-consume-rest-api-configuration-2.png) Figure 3. HTTP Request GET Method and Path. ### Configure HTTP Request Operation in XML The following XML code shows the configuration of the HTTP Request operation for the example: ```xml <...> ``` ### Example JSON Response For the JSONPlaceholder API example, the JSON response has the following structure: ```json { "userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": false } ``` You can transform the data in the **Advanced** tab of the HTTP Request operation. You can also define the target variable, which by default is the Payload. If this API has an associated RAML file, you can reference it in the configuration element of the connector. With that in place, after you select the verb and asset to call, Studio exposes the metadata corresponding to the output. Integration with other elements in a flow is simplified. ## Configure Dynamic Requests with DataWeave Expressions Most use cases require that you change the call to the API change dynamically based on data in the message. You can configure these dynamic requests by using DataWeave expressions. In the configuration examples documented in "Consume REST API Example", the request was hardcoded in the URL: https://jsonplaceholder.typicode.com/users/1 In the following GET request example, the call instructs Mule runtime engine to extract the user ID from the payload of the message, using the DataWeave expression `#[payload.user_id]`. https://jsonplaceholder.typicode.com/users/#\[payload.user\_id\] ### Configure Dynamic Requests in Anypoint Studio To perform the same operation by using Anypoint Studio, modify the path configuration with the desired DataWeave expression: in this case `#['/users/' ++ payload.user_id]`. ![A configure Dynamic Requests with DataWeave expressions in Path field](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-consume-rest-api-configuration-3.png) Figure 4. Configure Dynamic Requests with DataWeave expressions in Path field. You can also configure dynamic requests for the query or URI parameters, or for the HTTP method. Additionally, you can use [Configuration Properties](https://docs.mulesoft.com/mule-runtime/4.9/configuring-properties) to set any of these dynamic requests. ### Configure Dynamic Requests in XML The following example code in XML, shows the configuration of dynamic requests: ```xml <...> ``` ## HTTP Content-Type and Encoding When you send a POST request, Mule runtime engine adheres to the following rules regarding Content-Type and encoding of the body.

Content

Rules

For a String, char[]`, Reader, or similar*

* If the endpoint has explicitly set encoding, Mule runtime engine uses that encoding. * If the endpoint does not have explicitly set encoding, Mule runtime engine determines the encoding from the message property Content-Type. * If the Content-Type message property is not set, Mule runtime engine uses the Mule Context default configuration. * For Content-Type, Mule runtime engine sends the message property Content-Type, but with the actual encoding set.

For binary content

Encoding is not relevant. Mule runtime engine sets Content-Type as follows:

  • If the Content-Type property is set on the message, Mule runtime engine uses the defined content type.

  • If the Content-Type property is not set on the message, Mule runtime engine sets "application/octet-stream" as Content-Type.

## Custom Headers Some APIs require that you pass custom headers, such as your developer key, along with your requests. As with the query parameters, you can also add headers to your request on the HTTP Connector. For example, if the API you are consuming requires a developer key, then specify that key as a header on your requests by using the header name `accessKey`. You can add a property to set custom headers by using Anypoint Studio. ### Custom Headers in Anypoint Studio To set custom headers in Studio, review the following steps: - In the HTTP Request operation’s properties editor, select the **Headers** tab. - Click **Add**. - Define **Name** and **Value**. Both can be defined using expressions or properties placeholders. ![A custom header configuration in Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-consume-rest-api-configuration-4.png) Figure 5. Configure Custom Headers in the HTTP Request operation’s properties editor. ## Security Requirements If the API that you are calling requires complex authentication protocols, you can build your own connector to consume it. Otherwise, you can meet API security requirements by setting basic authentication credentials or configuring a global HTTPS connector. ### Basic Authentication If the REST API that you are consuming requires you to supply basic authentication credentials, you can provide them within the outbound HTTP endpoint configuration: 1. In Studio, go to the HTTP Request configuration window. 2. In Authentication, select **Basic Authentication**. 3. Type your username and password. These can also be set as properties placeholders. 4. Click **OK**. ![An HTTP Request showing settings for connection timeout, response buffer size, and TLS configuration](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-consume-rest-api-configuration-7.png) ### HTTPS Configuration If you are consuming a REST API that requires that incoming requests arrive via HTTPS, you can configure a global HTTPS Request connector in your Mule application, then reference the connector in your request operation. In the following example, you configure the HTTPS Request connector, create a Java keystore file (JKS) and [configure TLS](https://docs.mulesoft.com/mule-runtime/4.9/tls-configuration). #### Configure the HTTP Request Connector for HTTPS 1. In the HTTP Request Configuration window, navigate to General tab > Connection Configuration section. 2. Select **HTTPS** for the **Protocol**. 3. Click **OK**. ![An HTTP Request showing settings for protocol, host, port, and persistent connections configuration](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-consume-rest-api-configuration-5.png) Figure 6. Configure HTTPS Request Connector. #### Create a Keystore File Using the Java keytool in the bin directory of the Java installation, create a keystore file to certify the communication: 1. Using the command line, navigate to the Java installation directory on your machine. 2. Execute the following command: keytool -genkey -alias mule -keyalg RSA -keystore keystore.jks 3. When prompted, create two passwords and remember them for later use. This action creates a `jks` file in the local directory called `keystore.jks`. 4. Place your `keystore.jks` file: - If you use Studio, place the `keystore.jks` file into the `appname/src/main/resources` directory in Studio Package Explorer. - If you use XML in Mule runtime engine and want to use the file across multiple applications, place the file in the `MULE_HOME/conf` directory. - If you use XML in Mule runtime engine and want to use the file within this application, place the file in the `yourappname/src/main/resources` directory. 5. Reference the keystore in a global HTTPS Request connector. This connector is then referenced by the HTTP outbound endpoint within your flow. #### Configure TLS Follow these steps to configure TLS: 1. In Studio, go to the Global Elements view. 2. Select **Create** and search for "TLS Context". 3. In the Key Store Configuration section, select a type of keystore configuration from the drop-down menu: for example, **JKS** (Java Key Store) which is the default type. 4. For **Path**, specify the name of the keystore if you placed your keystore in the `appname/src/main/resources` directory; otherwise, specify `"/keystore.jks"`. 5. For **Key Password**, and **Password**, enter the passwords that you created when creating your keystore file. 6. Click **OK**. ![A TLS configuration showing settings for trust store and key store configurations](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-consume-rest-api-configuration-6.png) Figure 7. Configure TLS. 7. Go to the HTTP Request configuration window. 8. In TLS Configuration, select **Global Reference** and the **TLS context** value that you created earlier. You can also create the TLS context inline. ![An HTTP Request configuration including TLS and proxy details](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-consume-rest-api-configuration-8.png) Figure 8. Configure TLS in HTTP Request Configuration. --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Consume Data from an API > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After you build your application, you can start consuming data from an API. Review the following processes to consume data from a SOAP or REST API. ## Consume Data from a SOAP API To consume data from a SOAP API that does not have its own Anypoint Connector, configure Anypoint Connector for Web Service Consumer (Web Service Consumer Connector). Using the host, port, and address metadata retrieved from the API’s WSDL file, the connector provides the connection configuration you need for consuming a service from within your Mule application: See [Web Service Consumer Connector](https://docs.mulesoft.com/web-service-consumer-connector/latest/) for details. ## Consume Data from a REST API The following process focuses on configuring the HTTP Request Connector to call the REST API. It helps you to understand the basic anatomy of how a Mule application consumes a REST API, the minimum configuration required, how to consume examples, how to configure dynamic requests, how to manage HTTP Content-Type and encoding, and how to work with custom headers and security requirements. To consume data from a REST API from within a Mule application, you can configure Anypoint Connector for HTTP Request (HTTP Request Connector). If you connect to the same REST API many times or work with an API that has complex authentication protocols, consider [developing your own connector using the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). Check whether a connector already exists in [Anypoint Exchange](https://anypoint.mulesoft.com/exchange/) for the API you want to connect to. You can search in Exchange through Anypoint Studio’s Mule Palette. ## Basic Anatomy A Mule application consuming a REST API consists of the following: - One or more message processors configured to build your request - An HTTP request operation configured to call the REST API - One or more message processors configured to accept and process the response ![Consuming REST API Flow](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-consume-rest-api-flow.png) Figure 1. Consuming REST API Flow. You configure the portions of the application that build the request and process the response. ## Minimum Configuration The REST API you are consuming must have a [RAML](https://raml.org/) file that describes the API, so that the HTTP connector proactively presents you with smart suggestions. In the RAML file, you define the following: - Authentication - A base URI for configuring the outbound HTTP endpoint - Scope Based on authentication credentials, the application can limit calls to only GET requests on certain resources, for example, or otherwise limit access to a resource. - Resources You must configure the path of the resources for the outbound HTTP endpoint. - Methods You can accept POST as the default method for the HTTP outbound endpoint, or you can change this default to the method supported by your resource. - Input validation For POST and PUT calls, the API almost always requires that the input format, such as JSON or XML, match its schema. In Mule runtime engine, you can define or configure the following: - Output format After the HTTP request operation, your flow must include message processors to accept the response from the API and translate the response into a useable format. - Redirects If the API uses redirects, enable redirects in your HTTP request operation. - Timeout - Headers for methods POST, PUT, and DELETE requests almost always require headers. - URI and Query Parameters - Error handling See [HTTP Connector documentation](https://docs.mulesoft.com/http-connector/latest/#input-sources) for more information about how to configure the request operation. ### Consume REST API Example The following example consumes the [JSONPlaceholder API](https://jsonplaceholder.typicode.com/todos/1). The example shows only the configuration of the HTTP Request Connector, and to make it work, you must configure at least one Mule event source to trigger a message in the flow and at least one message processor to accept the response. See [REST API Examples documentation](https://docs.mulesoft.com/mule-runtime/latest/rest-api-examples) for more information. In this API example: - The API doesn’t require authentication. - The base URL is `jsonplaceholder.typicode.com`. - The API is a mock API for development purposes. - The sample API requests show that to get information about user with `id=1` the request must be: https://jsonplaceholder.typicode.com/users/1 The parts of the URL are as follows: - Protocol: `http` - API Base URL: `jsonplaceholder.typicode.com` - Resource path: `/users/1` - Query Parameters: None, in this case. To implement this call in your Mule application, configure your HTTP request operation. ### Configure HTTP Request Operation in Anypoint Studio 1. From the Mule Palette in Studio, add an HTTP Request Connector to your application. 2. In the HTTP Request Configuration window, provide `jsonplaceholder.typicode.com` as the value for **Host**. 3. Set the **Port** value to 80. 4. Click **OK**: ![An HTTP Request configuration with Host and Port](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-consume-rest-api-configuration-1.png) Figure 2. HTTP Request configuration with Host and Port. 5. Navigate to the Request section from the HTTP Request operation’s properties editor > General tab and add `/users/1` in the **Path** field. Specifying this path completes the URL that you began to identify by specifying the host in the first step. 6. Select a method from the **Method** drop-down list (in this example, `GET`). 7. Save your application. ![An HTTP Request GET Method and Path](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-consume-rest-api-configuration-2.png) Figure 3. HTTP Request GET Method and Path. ### Configure HTTP Request Operation in XML The following XML code shows the configuration of the HTTP Request operation for the example: ```xml <...> ``` ### Example JSON Response For the JSONPlaceholder API example, the JSON response has the following structure: ```json { "userId": 1, "id": 3, "title": "fugiat veniam minus", "completed": false } ``` You can transform the data in the **Advanced** tab of the HTTP Request operation. You can also define the target variable, which by default is the Payload. If this API has an associated RAML file, you can reference it in the configuration element of the connector. With that in place, after you select the verb and asset to call, Studio exposes the metadata corresponding to the output. Integration with other elements in a flow is simplified. ## Configure Dynamic Requests with DataWeave Expressions Most use cases require that you change the call to the API change dynamically based on data in the message. You can configure these dynamic requests by using DataWeave expressions. In the configuration examples documented in "Consume REST API Example", the request was hardcoded in the URL: https://jsonplaceholder.typicode.com/users/1 In the following GET request example, the call instructs Mule runtime engine to extract the user ID from the payload of the message, using the DataWeave expression `#[payload.user_id]`. https://jsonplaceholder.typicode.com/users/#\[payload.user\_id\] ### Configure Dynamic Requests in Anypoint Studio To perform the same operation by using Anypoint Studio, modify the path configuration with the desired DataWeave expression: in this case `#['/users/' ++ payload.user_id]`. ![A configure Dynamic Requests with DataWeave expressions in Path field](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-consume-rest-api-configuration-3.png) Figure 4. Configure Dynamic Requests with DataWeave expressions in Path field. You can also configure dynamic requests for the query or URI parameters, or for the HTTP method. Additionally, you can use [Configuration Properties](https://docs.mulesoft.com/mule-runtime/latest/configuring-properties) to set any of these dynamic requests. ### Configure Dynamic Requests in XML The following example code in XML, shows the configuration of dynamic requests: ```xml <...> ``` ## HTTP Content-Type and Encoding When you send a POST request, Mule runtime engine adheres to the following rules regarding Content-Type and encoding of the body.

Content

Rules

For a String, char[]`, Reader, or similar*

* If the endpoint has explicitly set encoding, Mule runtime engine uses that encoding. * If the endpoint does not have explicitly set encoding, Mule runtime engine determines the encoding from the message property Content-Type. * If the Content-Type message property is not set, Mule runtime engine uses the Mule Context default configuration. * For Content-Type, Mule runtime engine sends the message property Content-Type, but with the actual encoding set.

For binary content

Encoding is not relevant. Mule runtime engine sets Content-Type as follows:

  • If the Content-Type property is set on the message, Mule runtime engine uses the defined content type.

  • If the Content-Type property is not set on the message, Mule runtime engine sets "application/octet-stream" as Content-Type.

## Custom Headers Some APIs require that you pass custom headers, such as your developer key, along with your requests. As with the query parameters, you can also add headers to your request on the HTTP Connector. For example, if the API you are consuming requires a developer key, then specify that key as a header on your requests by using the header name `accessKey`. You can add a property to set custom headers by using Anypoint Studio. ### Custom Headers in Anypoint Studio To set custom headers in Studio, review the following steps: - In the HTTP Request operation’s properties editor, select the **Headers** tab. - Click **Add**. - Define **Name** and **Value**. Both can be defined using expressions or properties placeholders. ![A custom header configuration in Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-consume-rest-api-configuration-4.png) Figure 5. Configure Custom Headers in the HTTP Request operation’s properties editor. ## Security Requirements If the API that you are calling requires complex authentication protocols, you can build your own connector to consume it. Otherwise, you can meet API security requirements by setting basic authentication credentials or configuring a global HTTPS connector. ### Basic Authentication If the REST API that you are consuming requires you to supply basic authentication credentials, you can provide them within the outbound HTTP endpoint configuration: 1. In Studio, go to the HTTP Request configuration window. 2. In Authentication, select **Basic Authentication**. 3. Type your username and password. These can also be set as properties placeholders. 4. Click **OK**. ![An HTTP Request showing settings for connection timeout, response buffer size, and TLS configuration](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-consume-rest-api-configuration-7.png) ### HTTPS Configuration If you are consuming a REST API that requires that incoming requests arrive via HTTPS, you can configure a global HTTPS Request connector in your Mule application, then reference the connector in your request operation. In the following example, you configure the HTTPS Request connector, create a Java keystore file (JKS) and [configure TLS](https://docs.mulesoft.com/mule-runtime/latest/tls-configuration). #### Configure the HTTP Request Connector for HTTPS 1. In the HTTP Request Configuration window, navigate to General tab > Connection Configuration section. 2. Select **HTTPS** for the **Protocol**. 3. Click **OK**. ![An HTTP Request showing settings for protocol, host, port, and persistent connections configuration](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-consume-rest-api-configuration-5.png) Figure 6. Configure HTTPS Request Connector. #### Create a Keystore File Using the Java keytool in the bin directory of the Java installation, create a keystore file to certify the communication: 1. Using the command line, navigate to the Java installation directory on your machine. 2. Execute the following command: keytool -genkey -alias mule -keyalg RSA -keystore keystore.jks 3. When prompted, create two passwords and remember them for later use. This action creates a `jks` file in the local directory called `keystore.jks`. 4. Place your `keystore.jks` file: - If you use Studio, place the `keystore.jks` file into the `appname/src/main/resources` directory in Studio Package Explorer. - If you use XML in Mule runtime engine and want to use the file across multiple applications, place the file in the `MULE_HOME/conf` directory. - If you use XML in Mule runtime engine and want to use the file within this application, place the file in the `yourappname/src/main/resources` directory. 5. Reference the keystore in a global HTTPS Request connector. This connector is then referenced by the HTTP outbound endpoint within your flow. #### Configure TLS Follow these steps to configure TLS: 1. In Studio, go to the Global Elements view. 2. Select **Create** and search for "TLS Context". 3. In the Key Store Configuration section, select a type of keystore configuration from the drop-down menu: for example, **JKS** (Java Key Store) which is the default type. 4. For **Path**, specify the name of the keystore if you placed your keystore in the `appname/src/main/resources` directory; otherwise, specify `"/keystore.jks"`. 5. For **Key Password**, and **Password**, enter the passwords that you created when creating your keystore file. 6. Click **OK**. ![A TLS configuration showing settings for trust store and key store configurations](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-consume-rest-api-configuration-6.png) Figure 7. Configure TLS. 7. Go to the HTTP Request configuration window. 8. In TLS Configuration, select **Global Reference** and the **TLS context** value that you created earlier. You can also create the TLS context inline. ![An HTTP Request configuration including TLS and proxy details](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-consume-rest-api-configuration-8.png) Figure 8. Configure TLS in HTTP Request Configuration. --- product: Mule Runtime version: 4.11 keywords: build, deploy, test, maven, ci, continuous integration, continuous, integration --- # Continuous Integration > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The need for continuous integration (CI) for a project is very important. By using Maven as your build tool, you can create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. The advantages of CI are: - Provides early notification of issues in the software development lifecycle. - Ensures code gets fully tested before release. - Successfully tested branches ensure better success when merging to the main branch. ## Continuous Integration Objectives A CI system does all of the following: 1. Listens for new commits to a project’s source code management system. The CI system watches many branches for new commits. You can either use polling to find new commits, or the management system can trigger events that inform your program of commits. 2. Pulls the newest branch into a centralized server. 3. Creates build jobs on a centralized server. 4. Runs configurable unit and integration tests on the code base that compile, test, package, and deploy the project in a sandbox to ensure the project works correctly. 5. Stores artifacts in a repository. 6. Displays the results of each build. 7. Deploys passing builds to production. For information about these tools, see their websites. ## MuleSoft CI Tools You can deploy Mule applications using: - [The API Manager](https://docs.mulesoft.com/api-manager/latest/getting-started-proxy) - [The Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) You can create functional tests with [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/). The mule-maven-plugin supports deployments to: - CloudHub - Runtime Fabric - On-premises Mule instances - Standalone deployment - Using Anypoint Runtime Manager REST API - Using Runtime Manager agent For a complete CI example that uses Jenkins and Maven, see the Anypoint Platform Development: Advanced class on the [MuleSoft training site](https://trailheadacademy.salesforce.com/products/mulesoft). The training site also includes related classes and certification exams. ## External CI Tools Popular CI tools are: - Jenkins - Hudson - TeamCity - Bamboo For information about these tools, see their websites. ## Integration Notes If you’ve chosen to use connectors in your functional test cases, watch out for potential port conflicts that can occur in a continuous build server. If your target deployable is a web application and not a Mule application, consider using Junit Integration Test Runner for running your functional tests and avoiding port conflicts. ## See Also - [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.11/using-maven-with-mule) - [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/) --- product: Mule Runtime version: 4.12 keywords: build, deploy, test, maven, ci, continuous integration, continuous, integration --- # Continuous Integration > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The need for continuous integration (CI) for a project is very important. By using Maven as your build tool, you can create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. The advantages of CI are: - Provides early notification of issues in the software development lifecycle. - Ensures code gets fully tested before release. - Successfully tested branches ensure better success when merging to the main branch. ## Continuous Integration Objectives A CI system does all of the following: 1. Listens for new commits to a project’s source code management system. The CI system watches many branches for new commits. You can either use polling to find new commits, or the management system can trigger events that inform your program of commits. 2. Pulls the newest branch into a centralized server. 3. Creates build jobs on a centralized server. 4. Runs configurable unit and integration tests on the code base that compile, test, package, and deploy the project in a sandbox to ensure the project works correctly. 5. Stores artifacts in a repository. 6. Displays the results of each build. 7. Deploys passing builds to production. For information about these tools, see their websites. ## MuleSoft CI Tools You can deploy Mule applications using: - [The API Manager](https://docs.mulesoft.com/api-manager/latest/getting-started-proxy) - [The Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) You can create functional tests with [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/). The mule-maven-plugin supports deployments to: - CloudHub - Runtime Fabric - On-premises Mule instances - Standalone deployment - Using Anypoint Runtime Manager REST API - Using Runtime Manager agent For a complete CI example that uses Jenkins and Maven, see the Anypoint Platform Development: Advanced class on the [MuleSoft training site](https://trailheadacademy.salesforce.com/products/mulesoft). The training site also includes related classes and certification exams. ## External CI Tools Popular CI tools are: - Jenkins - Hudson - TeamCity - Bamboo For information about these tools, see their websites. ## Integration Notes If you’ve chosen to use connectors in your functional test cases, watch out for potential port conflicts that can occur in a continuous build server. If your target deployable is a web application and not a Mule application, consider using Junit Integration Test Runner for running your functional tests and avoiding port conflicts. ## See Also - [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.12/using-maven-with-mule) - [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/) --- product: Mule Runtime version: 4.3 keywords: build, deploy, test, maven, ci, continuous integration, continuous, integration --- # Continuous Integration > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The need for continuous integration (CI) for a project is very important. By using Maven as your build tool, you can create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. The advantages of CI are: - Provides early notification of issues in the software development lifecycle. - Ensures code gets fully tested before release. - Successfully tested branches ensure better success when merging to the main branch. ## Continuous Integration Objectives A CI system does all of the following: 1. Listens for new commits to a project’s source code management system. The CI system watches many branches for new commits. You can either use polling to find new commits, or the management system can trigger events that inform your program of commits. 2. Pulls the newest branch into a centralized server. 3. Creates build jobs on a centralized server. 4. Runs configurable unit and integration tests on the code base that compile, test, package, and deploy the project in a sandbox to ensure the project works correctly. 5. Stores artifacts in a repository. 6. Displays the results of each build. 7. Deploys passing builds to production. For information about these tools, see their websites. ## MuleSoft CI Tools You can deploy Mule applications using: - [The API Manager](https://docs.mulesoft.com/api-manager/latest/getting-started-proxy) - [The Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) You can create functional tests with [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/). The mule-maven-plugin supports deployments to: - CloudHub - Runtime Fabric - On-premises Mule instances - Standalone deployment - Using Anypoint Runtime Manager REST API - Using Runtime Manager agent For a complete CI example that uses Jenkins and Maven, see the Anypoint Platform Development: Advanced class on the [MuleSoft training site](https://trailheadacademy.salesforce.com/products/mulesoft). The training site also includes related classes and certification exams. ## External CI Tools Popular CI tools are: - Jenkins - Hudson - TeamCity - Bamboo For information about these tools, see their websites. ## Integration Notes If you’ve chosen to use connectors in your functional test cases, watch out for potential port conflicts that can occur in a continuous build server. If your target deployable is a web application and not a Mule application, consider using Junit Integration Test Runner for running your functional tests and avoiding port conflicts. ## See Also - [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.3/using-maven-with-mule) - [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/) --- product: Mule Runtime version: 4.4 keywords: build, deploy, test, maven, ci, continuous integration, continuous, integration --- # Continuous Integration > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The need for continuous integration (CI) for a project is very important. By using Maven as your build tool, you can create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. The advantages of CI are: - Provides early notification of issues in the software development lifecycle. - Ensures code gets fully tested before release. - Successfully tested branches ensure better success when merging to the main branch. ## Continuous Integration Objectives A CI system does all of the following: 1. Listens for new commits to a project’s source code management system. The CI system watches many branches for new commits. You can either use polling to find new commits, or the management system can trigger events that inform your program of commits. 2. Pulls the newest branch into a centralized server. 3. Creates build jobs on a centralized server. 4. Runs configurable unit and integration tests on the code base that compile, test, package, and deploy the project in a sandbox to ensure the project works correctly. 5. Stores artifacts in a repository. 6. Displays the results of each build. 7. Deploys passing builds to production. For information about these tools, see their websites. ## MuleSoft CI Tools You can deploy Mule applications using: - [The API Manager](https://docs.mulesoft.com/api-manager/latest/getting-started-proxy) - [The Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) You can create functional tests with [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/). The mule-maven-plugin supports deployments to: - CloudHub - Runtime Fabric - On-premises Mule instances - Standalone deployment - Using Anypoint Runtime Manager REST API - Using Runtime Manager agent For a complete CI example that uses Jenkins and Maven, see the Anypoint Platform Development: Advanced class on the [MuleSoft training site](https://trailheadacademy.salesforce.com/products/mulesoft). The training site also includes related classes and certification exams. ## External CI Tools Popular CI tools are: - Jenkins - Hudson - TeamCity - Bamboo For information about these tools, see their websites. ## Integration Notes If you’ve chosen to use connectors in your functional test cases, watch out for potential port conflicts that can occur in a continuous build server. If your target deployable is a web application and not a Mule application, consider using Junit Integration Test Runner for running your functional tests and avoiding port conflicts. ## See Also - [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.4/using-maven-with-mule) - [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/) --- product: Mule Runtime version: 4.6 keywords: build, deploy, test, maven, ci, continuous integration, continuous, integration --- # Continuous Integration > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The need for continuous integration (CI) for a project is very important. By using Maven as your build tool, you can create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. The advantages of CI are: - Provides early notification of issues in the software development lifecycle. - Ensures code gets fully tested before release. - Successfully tested branches ensure better success when merging to the main branch. ## Continuous Integration Objectives A CI system does all of the following: 1. Listens for new commits to a project’s source code management system. The CI system watches many branches for new commits. You can either use polling to find new commits, or the management system can trigger events that inform your program of commits. 2. Pulls the newest branch into a centralized server. 3. Creates build jobs on a centralized server. 4. Runs configurable unit and integration tests on the code base that compile, test, package, and deploy the project in a sandbox to ensure the project works correctly. 5. Stores artifacts in a repository. 6. Displays the results of each build. 7. Deploys passing builds to production. For information about these tools, see their websites. ## MuleSoft CI Tools You can deploy Mule applications using: - [The API Manager](https://docs.mulesoft.com/api-manager/latest/getting-started-proxy) - [The Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) You can create functional tests with [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/). The mule-maven-plugin supports deployments to: - CloudHub - Runtime Fabric - On-premises Mule instances - Standalone deployment - Using Anypoint Runtime Manager REST API - Using Runtime Manager agent For a complete CI example that uses Jenkins and Maven, see the Anypoint Platform Development: Advanced class on the [MuleSoft training site](https://trailheadacademy.salesforce.com/products/mulesoft). The training site also includes related classes and certification exams. ## External CI Tools Popular CI tools are: - Jenkins - Hudson - TeamCity - Bamboo For information about these tools, see their websites. ## Integration Notes If you’ve chosen to use connectors in your functional test cases, watch out for potential port conflicts that can occur in a continuous build server. If your target deployable is a web application and not a Mule application, consider using Junit Integration Test Runner for running your functional tests and avoiding port conflicts. ## See Also - [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.6/using-maven-with-mule) - [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/) --- product: Mule Runtime version: 4.9 keywords: build, deploy, test, maven, ci, continuous integration, continuous, integration --- # Continuous Integration > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The need for continuous integration (CI) for a project is very important. By using Maven as your build tool, you can create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. The advantages of CI are: - Provides early notification of issues in the software development lifecycle. - Ensures code gets fully tested before release. - Successfully tested branches ensure better success when merging to the main branch. ## Continuous Integration Objectives A CI system does all of the following: 1. Listens for new commits to a project’s source code management system. The CI system watches many branches for new commits. You can either use polling to find new commits, or the management system can trigger events that inform your program of commits. 2. Pulls the newest branch into a centralized server. 3. Creates build jobs on a centralized server. 4. Runs configurable unit and integration tests on the code base that compile, test, package, and deploy the project in a sandbox to ensure the project works correctly. 5. Stores artifacts in a repository. 6. Displays the results of each build. 7. Deploys passing builds to production. For information about these tools, see their websites. ## MuleSoft CI Tools You can deploy Mule applications using: - [The API Manager](https://docs.mulesoft.com/api-manager/latest/getting-started-proxy) - [The Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) You can create functional tests with [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/). The mule-maven-plugin supports deployments to: - CloudHub - Runtime Fabric - On-premises Mule instances - Standalone deployment - Using Anypoint Runtime Manager REST API - Using Runtime Manager agent For a complete CI example that uses Jenkins and Maven, see the Anypoint Platform Development: Advanced class on the [MuleSoft training site](https://trailheadacademy.salesforce.com/products/mulesoft). The training site also includes related classes and certification exams. ## External CI Tools Popular CI tools are: - Jenkins - Hudson - TeamCity - Bamboo For information about these tools, see their websites. ## Integration Notes If you’ve chosen to use connectors in your functional test cases, watch out for potential port conflicts that can occur in a continuous build server. If your target deployable is a web application and not a Mule application, consider using Junit Integration Test Runner for running your functional tests and avoiding port conflicts. ## See Also - [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.9/using-maven-with-mule) - [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: build, deploy, test, maven, ci, continuous integration, continuous, integration --- # Continuous Integration > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The need for continuous integration (CI) for a project is very important. By using Maven as your build tool, you can create a build that gets triggered on every project change, and run all of its unit and functional tests automatically. The advantages of CI are: - Provides early notification of issues in the software development lifecycle. - Ensures code gets fully tested before release. - Successfully tested branches ensure better success when merging to the main branch. ## Continuous Integration Objectives A CI system does all of the following: 1. Listens for new commits to a project’s source code management system. The CI system watches many branches for new commits. You can either use polling to find new commits, or the management system can trigger events that inform your program of commits. 2. Pulls the newest branch into a centralized server. 3. Creates build jobs on a centralized server. 4. Runs configurable unit and integration tests on the code base that compile, test, package, and deploy the project in a sandbox to ensure the project works correctly. 5. Stores artifacts in a repository. 6. Displays the results of each build. 7. Deploys passing builds to production. For information about these tools, see their websites. ## MuleSoft CI Tools You can deploy Mule applications using: - [The API Manager](https://docs.mulesoft.com/api-manager/latest/getting-started-proxy) - [The Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) You can create functional tests with [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/). The mule-maven-plugin supports deployments to: - CloudHub - Runtime Fabric - On-premises Mule instances - Standalone deployment - Using Anypoint Runtime Manager REST API - Using Runtime Manager agent For a complete CI example that uses Jenkins and Maven, see the Anypoint Platform Development: Advanced class on the [MuleSoft training site](https://trailheadacademy.salesforce.com/products/mulesoft). The training site also includes related classes and certification exams. ## External CI Tools Popular CI tools are: - Jenkins - Hudson - TeamCity - Bamboo For information about these tools, see their websites. ## Integration Notes If you’ve chosen to use connectors in your functional test cases, watch out for potential port conflicts that can occur in a continuous build server. If your target deployable is a web application and not a Mule application, consider using Junit Integration Test Runner for running your functional tests and avoiding port conflicts. ## See Also - [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/latest/using-maven-with-mule) - [MUnit Unit Testing](https://docs.mulesoft.com/munit/latest/) --- product: Mule Runtime version: 4.11 --- # Core Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Like the operations in connectors and modules, Core components are important building blocks of flows in a Mule app. Core components provide the logic for processing a Mule event as it travels in a series of linked steps through the app. Examples include the Scheduler, For Each, and Logger components. In Studio, Mule components are accessible by clicking **Core** from the Mule palette. ![Core components in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/components-core-studio.png) Notice that the components are subdivided into types, including Batch, Error Handling, and Flow Control. ## Batch To process Mule messages in batches, instead of processing them all together, you can use Batch components, which include: - Batch Aggregator - Batch Job - Batch Step See [Batch Processors](https://docs.mulesoft.com/mule-runtime/4.11/batch-processing-concept). ## Components These Core components perform a variety of tasks: - [Custom Business Events](https://docs.mulesoft.com/mule-runtime/4.11/business-events-custom): For collecting information about flows and message processors that handle your business transactions. See also [Business Events](https://docs.mulesoft.com/mule-runtime/4.11/business-events). - [Dynamic Evaluate](https://docs.mulesoft.com/mule-runtime/4.11/dynamic-evaluate-component-reference): For dynamically selecting a script, instead of forcing you to hardcode it through the Transform Message Component. - [Flow Reference](https://docs.mulesoft.com/mule-runtime/4.11/flowref-about): For routing the Mule event to another flow or subflow (and back) within a Mule app. - [Logger](https://docs.mulesoft.com/mule-runtime/4.11/logger-component-reference): For logging important information about your Mule app, such as error messages and status notifications. - [Parse Template](https://docs.mulesoft.com/mule-runtime/4.11/parse-template-reference): For processing a template and obtaining a result. - [Transform Message](https://docs.mulesoft.com/mule-runtime/4.11/transform-component-about): For converting input data to a new output structure or format. ## Endpoints Endpoints (sometimes called Sources in Studio) include components that initiate (or trigger) processing in a Mule flow. The [Scheduler](https://docs.mulesoft.com/mule-runtime/4.11/scheduler-concept) is an endpoint. It triggers a flow to start at a configurable interval. Note that some connectors provide listeners that serve as endpoints. Listeners can trigger a flow when they receive an external request. For example, an HTTP Listener that is configured for a given URL can trigger a flow when someone or some process goes to that URL. ## Error Handling Error handling components route and process Mule errors that occur in a Mule app: - Error Handler - On Error Continue - On Error Propagate See [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.11/error-handling) ## Flow Control (Routers) A Flow Control component (or Router) takes the input Mule event and routes it to one or more separate sequences of components. Flow Control components include: - Choice - First Successful - Round Robin - Scatter-Gather For example, a [Choice router](https://docs.mulesoft.com/mule-runtime/4.11/choice-router-concept) applies DataWeave logic to pick one of two or more routes, where each route is a separate sequence of event processors. A [Scatter-Gather router](https://docs.mulesoft.com/mule-runtime/4.11/scatter-gather-concept) router sends the input event to every route, and each route independently processes the event. After every route has processed the event, the results from all the routes are combined together into one output event. ## Scopes A Scope is a type of component that groups together a sequence of event processors (such as other Core components and operations from both modules and connectors) to apply some programming behavior to that isolated sequence of event processors. Scopes include these components: - Async - Cache - Flow - For Each - Try - Until Successful For example, a Try scope lets you isolate and handle any errors that occur in a particular sequence of flows. So, you might wrap an outbound HTTP Request connector (and perhaps some other surrounding components before and after the HTTP Request connector, such as a Transform Message component or a Logging component) in a Try scope, so if an error results, you can apply logging or compensation logic specific to that grouping of components. See [Try Scope](https://docs.mulesoft.com/mule-runtime/4.11/try-scope-concept). Another example is the For Each (or Foreach) scope, which takes a collection of data, usually extracted from the current input event, and applies the same sequence of event processors to every item in the collection. For example, a For Each scope might be used to process each individual row returned from a database query or each individual line from a CSV file. See [For Each Scope](https://docs.mulesoft.com/mule-runtime/4.11/for-each-scope-concept). ## Transformers Transformers are components you can use to set or remove a part of the Mule event. Transformers include: - [Remove Variable](https://docs.mulesoft.com/mule-runtime/4.11/remove-variable) - [Set Payload](https://docs.mulesoft.com/mule-runtime/4.11/set-payload-transformer-reference) - [Set Variable](https://docs.mulesoft.com/mule-runtime/4.11/variable-transformer-reference) ## See Also - [Connectors and Modules](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.12 --- # Core Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Like the operations in connectors and modules, Core components are important building blocks of flows in a Mule app. Core components provide the logic for processing a Mule event as it travels in a series of linked steps through the app. Examples include the Scheduler, For Each, and Logger components. In Studio, Mule components are accessible by clicking **Core** from the Mule palette. ![Core components in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/components-core-studio.png) Notice that the components are subdivided into types, including Batch, Error Handling, and Flow Control. ## Batch To process Mule messages in batches, instead of processing them all together, you can use Batch components, which include: - Batch Aggregator - Batch Job - Batch Step See [Batch Processors](https://docs.mulesoft.com/mule-runtime/4.12/batch-processing-concept). ## Components These Core components perform a variety of tasks: - [Custom Business Events](https://docs.mulesoft.com/mule-runtime/4.12/business-events-custom): For collecting information about flows and message processors that handle your business transactions. See also [Business Events](https://docs.mulesoft.com/mule-runtime/4.12/business-events). - [Dynamic Evaluate](https://docs.mulesoft.com/mule-runtime/4.12/dynamic-evaluate-component-reference): For dynamically selecting a script, instead of forcing you to hardcode it through the Transform Message Component. - [Flow Reference](https://docs.mulesoft.com/mule-runtime/4.12/flowref-about): For routing the Mule event to another flow or subflow (and back) within a Mule app. - [Logger](https://docs.mulesoft.com/mule-runtime/4.12/logger-component-reference): For logging important information about your Mule app, such as error messages and status notifications. - [Parse Template](https://docs.mulesoft.com/mule-runtime/4.12/parse-template-reference): For processing a template and obtaining a result. - [Transform Message](https://docs.mulesoft.com/mule-runtime/4.12/transform-component-about): For converting input data to a new output structure or format. ## Endpoints Endpoints (sometimes called Sources in Studio) include components that initiate (or trigger) processing in a Mule flow. The [Scheduler](https://docs.mulesoft.com/mule-runtime/4.12/scheduler-concept) is an endpoint. It triggers a flow to start at a configurable interval. Note that some connectors provide listeners that serve as endpoints. Listeners can trigger a flow when they receive an external request. For example, an HTTP Listener that is configured for a given URL can trigger a flow when someone or some process goes to that URL. ## Error Handling Error handling components route and process Mule errors that occur in a Mule app: - Error Handler - On Error Continue - On Error Propagate See [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.12/error-handling) ## Flow Control (Routers) A Flow Control component (or Router) takes the input Mule event and routes it to one or more separate sequences of components. Flow Control components include: - Choice - First Successful - Round Robin - Scatter-Gather For example, a [Choice router](https://docs.mulesoft.com/mule-runtime/4.12/choice-router-concept) applies DataWeave logic to pick one of two or more routes, where each route is a separate sequence of event processors. A [Scatter-Gather router](https://docs.mulesoft.com/mule-runtime/4.12/scatter-gather-concept) router sends the input event to every route, and each route independently processes the event. After every route has processed the event, the results from all the routes are combined together into one output event. ## Scopes A Scope is a type of component that groups together a sequence of event processors (such as other Core components and operations from both modules and connectors) to apply some programming behavior to that isolated sequence of event processors. Scopes include these components: - Async - Cache - Flow - For Each - Try - Until Successful For example, a Try scope lets you isolate and handle any errors that occur in a particular sequence of flows. So, you might wrap an outbound HTTP Request connector (and perhaps some other surrounding components before and after the HTTP Request connector, such as a Transform Message component or a Logging component) in a Try scope, so if an error results, you can apply logging or compensation logic specific to that grouping of components. See [Try Scope](https://docs.mulesoft.com/mule-runtime/4.12/try-scope-concept). Another example is the For Each (or Foreach) scope, which takes a collection of data, usually extracted from the current input event, and applies the same sequence of event processors to every item in the collection. For example, a For Each scope might be used to process each individual row returned from a database query or each individual line from a CSV file. See [For Each Scope](https://docs.mulesoft.com/mule-runtime/4.12/for-each-scope-concept). ## Transformers Transformers are components you can use to set or remove a part of the Mule event. Transformers include: - [Remove Variable](https://docs.mulesoft.com/mule-runtime/4.12/remove-variable) - [Set Payload](https://docs.mulesoft.com/mule-runtime/4.12/set-payload-transformer-reference) - [Set Variable](https://docs.mulesoft.com/mule-runtime/4.12/variable-transformer-reference) ## See Also - [Connectors and Modules](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.3 --- # Core Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Like the operations in connectors and modules, Core components are important building blocks of flows in a Mule app. Core components provide the logic for processing a Mule event as it travels in a series of linked steps through the app. Examples include the Scheduler, For Each, and Logger components. In Studio, Mule components are accessible by clicking **Core** from the Mule palette. \+ image::components-core-studio.png\[Core Components in Studio\] \+ Notice that the components are subdivided into types, including Batch, Error Handling, and Flow Control. ## Batch To process Mule messages in batches, instead of processing them all together, you can use Batch components, which include: - Batch Aggregator - Batch Job - Batch Step See [Batch Processors](https://docs.mulesoft.com/mule-runtime/4.3/batch-processing-concept). ## Components These Core components perform a variety of tasks: - [Custom Business Events](https://docs.mulesoft.com/mule-runtime/4.3/business-events-custom): For collecting information about flows and message processors that handle your business transactions. See also [Business Events](https://docs.mulesoft.com/mule-runtime/4.3/business-events). - [Dynamic Evaluate](https://docs.mulesoft.com/mule-runtime/4.3/dynamic-evaluate-component-reference): For dynamically selecting a script, instead of forcing you to hardcode it through the Transform Message Component. - [Flow Reference](https://docs.mulesoft.com/mule-runtime/4.3/flowref-about): For routing the Mule event to another flow or subflow (and back) within a Mule app. - [Logger](https://docs.mulesoft.com/mule-runtime/4.3/logger-component-reference): For logging important information about your Mule app, such as error messages and status notifications. - [Parse Template](https://docs.mulesoft.com/mule-runtime/4.3/parse-template-reference): For processing a template and obtaining a result. - [Transform Message](https://docs.mulesoft.com/mule-runtime/4.3/transform-component-about): For converting input data to a new output structure or format. ## Endpoints Endpoints (sometimes called Sources in Studio) include components that initiate (or trigger) processing in a Mule flow. The [Scheduler](https://docs.mulesoft.com/mule-runtime/4.3/scheduler-concept) is an endpoint. It triggers a flow to start at a configurable interval. Note that some connectors provide listeners that serve as endpoints. Listeners can trigger a flow when they receive an external request. For example, an HTTP Listener that is configured for a given URL can trigger a flow when someone or some process goes to that URL. ## Error Handling Error handling components route and process Mule errors that occur in a Mule app: - Error Handler - On Error Continue - On Error Propagate See [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.3/error-handling) ## Flow Control (Routers) A Flow Control component (or Router) takes the input Mule event and routes it to one or more separate sequences of components. Flow Control components include: - Choice - First Successful - Round Robin - Scatter-Gather For example, a [Choice router](https://docs.mulesoft.com/mule-runtime/4.3/choice-router-concept) applies DataWeave logic to pick one of two or more routes, where each route is a separate sequence of event processors. A [Scatter-Gather router](https://docs.mulesoft.com/mule-runtime/4.3/scatter-gather-concept) router sends the input event to every route, and each route independently processes the event. After every route has processed the event, the results from all the routes are combined together into one output event. ## Scopes A Scope is a type of component that groups together a sequence of event processors (such as other Core components and operations from both modules and connectors) to apply some programming behavior to that isolated sequence of event processors. Scopes include these components: - Async - Cache - Flow - For Each - Try - Until Successful For example, a Try scope lets you isolate and handle any errors that occur in a particular sequence of flows. So, you might wrap an outbound HTTP Request connector (and perhaps some other surrounding components before and after the HTTP Request connector, such as a Transform Message component or a Logging component) in a Try scope, so if an error results, you can apply logging or compensation logic specific to that grouping of components. See [Try Scope](https://docs.mulesoft.com/mule-runtime/4.3/try-scope-concept). Another example is the For Each (or Foreach) scope, which takes a collection of data, usually extracted from the current input event, and applies the same sequence of event processors to every item in the collection. For example, a For Each scope might be used to process each individual row returned from a database query or each individual line from a CSV file. See [For Each Scope](https://docs.mulesoft.com/mule-runtime/4.3/for-each-scope-concept). ## Transformers Transformers are components you can use to set or remove a part of the Mule event. Transformers include: - [Remove Variable](https://docs.mulesoft.com/mule-runtime/4.3/remove-variable) - [Set Payload](https://docs.mulesoft.com/mule-runtime/4.3/set-payload-transformer-reference) - [Set Variable](https://docs.mulesoft.com/mule-runtime/4.3/variable-transformer-reference) ## See Also - [Connectors and Modules](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.4 --- # Core Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Like the operations in connectors and modules, Core components are important building blocks of flows in a Mule app. Core components provide the logic for processing a Mule event as it travels in a series of linked steps through the app. Examples include the Scheduler, For Each, and Logger components. In Studio, Mule components are accessible by clicking **Core** from the Mule palette. \+ image::components-core-studio.png\[Core Components in Studio\] \+ Notice that the components are subdivided into types, including Batch, Error Handling, and Flow Control. ## Batch To process Mule messages in batches, instead of processing them all together, you can use Batch components, which include: - Batch Aggregator - Batch Job - Batch Step See [Batch Processors](https://docs.mulesoft.com/mule-runtime/4.4/batch-processing-concept). ## Components These Core components perform a variety of tasks: - [Custom Business Events](https://docs.mulesoft.com/mule-runtime/4.4/business-events-custom): For collecting information about flows and message processors that handle your business transactions. See also [Business Events](https://docs.mulesoft.com/mule-runtime/4.4/business-events). - [Dynamic Evaluate](https://docs.mulesoft.com/mule-runtime/4.4/dynamic-evaluate-component-reference): For dynamically selecting a script, instead of forcing you to hardcode it through the Transform Message Component. - [Flow Reference](https://docs.mulesoft.com/mule-runtime/4.4/flowref-about): For routing the Mule event to another flow or subflow (and back) within a Mule app. - [Logger](https://docs.mulesoft.com/mule-runtime/4.4/logger-component-reference): For logging important information about your Mule app, such as error messages and status notifications. - [Parse Template](https://docs.mulesoft.com/mule-runtime/4.4/parse-template-reference): For processing a template and obtaining a result. - [Transform Message](https://docs.mulesoft.com/mule-runtime/4.4/transform-component-about): For converting input data to a new output structure or format. ## Endpoints Endpoints (sometimes called Sources in Studio) include components that initiate (or trigger) processing in a Mule flow. The [Scheduler](https://docs.mulesoft.com/mule-runtime/4.4/scheduler-concept) is an endpoint. It triggers a flow to start at a configurable interval. Note that some connectors provide listeners that serve as endpoints. Listeners can trigger a flow when they receive an external request. For example, an HTTP Listener that is configured for a given URL can trigger a flow when someone or some process goes to that URL. ## Error Handling Error handling components route and process Mule errors that occur in a Mule app: - Error Handler - On Error Continue - On Error Propagate See [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.4/error-handling) ## Flow Control (Routers) A Flow Control component (or Router) takes the input Mule event and routes it to one or more separate sequences of components. Flow Control components include: - Choice - First Successful - Round Robin - Scatter-Gather For example, a [Choice router](https://docs.mulesoft.com/mule-runtime/4.4/choice-router-concept) applies DataWeave logic to pick one of two or more routes, where each route is a separate sequence of event processors. A [Scatter-Gather router](https://docs.mulesoft.com/mule-runtime/4.4/scatter-gather-concept) router sends the input event to every route, and each route independently processes the event. After every route has processed the event, the results from all the routes are combined together into one output event. ## Scopes A Scope is a type of component that groups together a sequence of event processors (such as other Core components and operations from both modules and connectors) to apply some programming behavior to that isolated sequence of event processors. Scopes include these components: - Async - Cache - Flow - For Each - Try - Until Successful For example, a Try scope lets you isolate and handle any errors that occur in a particular sequence of flows. So, you might wrap an outbound HTTP Request connector (and perhaps some other surrounding components before and after the HTTP Request connector, such as a Transform Message component or a Logging component) in a Try scope, so if an error results, you can apply logging or compensation logic specific to that grouping of components. See [Try Scope](https://docs.mulesoft.com/mule-runtime/4.4/try-scope-concept). Another example is the For Each (or Foreach) scope, which takes a collection of data, usually extracted from the current input event, and applies the same sequence of event processors to every item in the collection. For example, a For Each scope might be used to process each individual row returned from a database query or each individual line from a CSV file. See [For Each Scope](https://docs.mulesoft.com/mule-runtime/4.4/for-each-scope-concept). ## Transformers Transformers are components you can use to set or remove a part of the Mule event. Transformers include: - [Remove Variable](https://docs.mulesoft.com/mule-runtime/4.4/remove-variable) - [Set Payload](https://docs.mulesoft.com/mule-runtime/4.4/set-payload-transformer-reference) - [Set Variable](https://docs.mulesoft.com/mule-runtime/4.4/variable-transformer-reference) ## See Also - [Connectors and Modules](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.6 --- # Core Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Like the operations in connectors and modules, Core components are important building blocks of flows in a Mule app. Core components provide the logic for processing a Mule event as it travels in a series of linked steps through the app. Examples include the Scheduler, For Each, and Logger components. In Studio, Mule components are accessible by clicking **Core** from the Mule palette. \+ image::components-core-studio.png\[Core Components in Studio\] \+ Notice that the components are subdivided into types, including Batch, Error Handling, and Flow Control. ## Batch To process Mule messages in batches, instead of processing them all together, you can use Batch components, which include: - Batch Aggregator - Batch Job - Batch Step See [Batch Processors](https://docs.mulesoft.com/mule-runtime/4.6/batch-processing-concept). ## Components These Core components perform a variety of tasks: - [Custom Business Events](https://docs.mulesoft.com/mule-runtime/4.6/business-events-custom): For collecting information about flows and message processors that handle your business transactions. See also [Business Events](https://docs.mulesoft.com/mule-runtime/4.6/business-events). - [Dynamic Evaluate](https://docs.mulesoft.com/mule-runtime/4.6/dynamic-evaluate-component-reference): For dynamically selecting a script, instead of forcing you to hardcode it through the Transform Message Component. - [Flow Reference](https://docs.mulesoft.com/mule-runtime/4.6/flowref-about): For routing the Mule event to another flow or subflow (and back) within a Mule app. - [Logger](https://docs.mulesoft.com/mule-runtime/4.6/logger-component-reference): For logging important information about your Mule app, such as error messages and status notifications. - [Parse Template](https://docs.mulesoft.com/mule-runtime/4.6/parse-template-reference): For processing a template and obtaining a result. - [Transform Message](https://docs.mulesoft.com/mule-runtime/4.6/transform-component-about): For converting input data to a new output structure or format. ## Endpoints Endpoints (sometimes called Sources in Studio) include components that initiate (or trigger) processing in a Mule flow. The [Scheduler](https://docs.mulesoft.com/mule-runtime/4.6/scheduler-concept) is an endpoint. It triggers a flow to start at a configurable interval. Note that some connectors provide listeners that serve as endpoints. Listeners can trigger a flow when they receive an external request. For example, an HTTP Listener that is configured for a given URL can trigger a flow when someone or some process goes to that URL. ## Error Handling Error handling components route and process Mule errors that occur in a Mule app: - Error Handler - On Error Continue - On Error Propagate See [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.6/error-handling) ## Flow Control (Routers) A Flow Control component (or Router) takes the input Mule event and routes it to one or more separate sequences of components. Flow Control components include: - Choice - First Successful - Round Robin - Scatter-Gather For example, a [Choice router](https://docs.mulesoft.com/mule-runtime/4.6/choice-router-concept) applies DataWeave logic to pick one of two or more routes, where each route is a separate sequence of event processors. A [Scatter-Gather router](https://docs.mulesoft.com/mule-runtime/4.6/scatter-gather-concept) router sends the input event to every route, and each route independently processes the event. After every route has processed the event, the results from all the routes are combined together into one output event. ## Scopes A Scope is a type of component that groups together a sequence of event processors (such as other Core components and operations from both modules and connectors) to apply some programming behavior to that isolated sequence of event processors. Scopes include these components: - Async - Cache - Flow - For Each - Try - Until Successful For example, a Try scope lets you isolate and handle any errors that occur in a particular sequence of flows. So, you might wrap an outbound HTTP Request connector (and perhaps some other surrounding components before and after the HTTP Request connector, such as a Transform Message component or a Logging component) in a Try scope, so if an error results, you can apply logging or compensation logic specific to that grouping of components. See [Try Scope](https://docs.mulesoft.com/mule-runtime/4.6/try-scope-concept). Another example is the For Each (or Foreach) scope, which takes a collection of data, usually extracted from the current input event, and applies the same sequence of event processors to every item in the collection. For example, a For Each scope might be used to process each individual row returned from a database query or each individual line from a CSV file. See [For Each Scope](https://docs.mulesoft.com/mule-runtime/4.6/for-each-scope-concept). ## Transformers Transformers are components you can use to set or remove a part of the Mule event. Transformers include: - [Remove Variable](https://docs.mulesoft.com/mule-runtime/4.6/remove-variable) - [Set Payload](https://docs.mulesoft.com/mule-runtime/4.6/set-payload-transformer-reference) - [Set Variable](https://docs.mulesoft.com/mule-runtime/4.6/variable-transformer-reference) ## See Also - [Connectors and Modules](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.9 --- # Core Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Like the operations in connectors and modules, Core components are important building blocks of flows in a Mule app. Core components provide the logic for processing a Mule event as it travels in a series of linked steps through the app. Examples include the Scheduler, For Each, and Logger components. In Studio, Mule components are accessible by clicking **Core** from the Mule palette. ![Core components in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/components-core-studio.png) Notice that the components are subdivided into types, including Batch, Error Handling, and Flow Control. ## Batch To process Mule messages in batches, instead of processing them all together, you can use Batch components, which include: - Batch Aggregator - Batch Job - Batch Step See [Batch Processors](https://docs.mulesoft.com/mule-runtime/4.9/batch-processing-concept). ## Components These Core components perform a variety of tasks: - [Custom Business Events](https://docs.mulesoft.com/mule-runtime/4.9/business-events-custom): For collecting information about flows and message processors that handle your business transactions. See also [Business Events](https://docs.mulesoft.com/mule-runtime/4.9/business-events). - [Dynamic Evaluate](https://docs.mulesoft.com/mule-runtime/4.9/dynamic-evaluate-component-reference): For dynamically selecting a script, instead of forcing you to hardcode it through the Transform Message Component. - [Flow Reference](https://docs.mulesoft.com/mule-runtime/4.9/flowref-about): For routing the Mule event to another flow or subflow (and back) within a Mule app. - [Logger](https://docs.mulesoft.com/mule-runtime/4.9/logger-component-reference): For logging important information about your Mule app, such as error messages and status notifications. - [Parse Template](https://docs.mulesoft.com/mule-runtime/4.9/parse-template-reference): For processing a template and obtaining a result. - [Transform Message](https://docs.mulesoft.com/mule-runtime/4.9/transform-component-about): For converting input data to a new output structure or format. ## Endpoints Endpoints (sometimes called Sources in Studio) include components that initiate (or trigger) processing in a Mule flow. The [Scheduler](https://docs.mulesoft.com/mule-runtime/4.9/scheduler-concept) is an endpoint. It triggers a flow to start at a configurable interval. Note that some connectors provide listeners that serve as endpoints. Listeners can trigger a flow when they receive an external request. For example, an HTTP Listener that is configured for a given URL can trigger a flow when someone or some process goes to that URL. ## Error Handling Error handling components route and process Mule errors that occur in a Mule app: - Error Handler - On Error Continue - On Error Propagate See [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.9/error-handling) ## Flow Control (Routers) A Flow Control component (or Router) takes the input Mule event and routes it to one or more separate sequences of components. Flow Control components include: - Choice - First Successful - Round Robin - Scatter-Gather For example, a [Choice router](https://docs.mulesoft.com/mule-runtime/4.9/choice-router-concept) applies DataWeave logic to pick one of two or more routes, where each route is a separate sequence of event processors. A [Scatter-Gather router](https://docs.mulesoft.com/mule-runtime/4.9/scatter-gather-concept) router sends the input event to every route, and each route independently processes the event. After every route has processed the event, the results from all the routes are combined together into one output event. ## Scopes A Scope is a type of component that groups together a sequence of event processors (such as other Core components and operations from both modules and connectors) to apply some programming behavior to that isolated sequence of event processors. Scopes include these components: - Async - Cache - Flow - For Each - Try - Until Successful For example, a Try scope lets you isolate and handle any errors that occur in a particular sequence of flows. So, you might wrap an outbound HTTP Request connector (and perhaps some other surrounding components before and after the HTTP Request connector, such as a Transform Message component or a Logging component) in a Try scope, so if an error results, you can apply logging or compensation logic specific to that grouping of components. See [Try Scope](https://docs.mulesoft.com/mule-runtime/4.9/try-scope-concept). Another example is the For Each (or Foreach) scope, which takes a collection of data, usually extracted from the current input event, and applies the same sequence of event processors to every item in the collection. For example, a For Each scope might be used to process each individual row returned from a database query or each individual line from a CSV file. See [For Each Scope](https://docs.mulesoft.com/mule-runtime/4.9/for-each-scope-concept). ## Transformers Transformers are components you can use to set or remove a part of the Mule event. Transformers include: - [Remove Variable](https://docs.mulesoft.com/mule-runtime/4.9/remove-variable) - [Set Payload](https://docs.mulesoft.com/mule-runtime/4.9/set-payload-transformer-reference) - [Set Variable](https://docs.mulesoft.com/mule-runtime/4.9/variable-transformer-reference) ## See Also - [Connectors and Modules](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Core Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Like the operations in connectors and modules, Core components are important building blocks of flows in a Mule app. Core components provide the logic for processing a Mule event as it travels in a series of linked steps through the app. Examples include the Scheduler, For Each, and Logger components. In Studio, Mule components are accessible by clicking **Core** from the Mule palette. ![Core components in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/components-core-studio.png) Notice that the components are subdivided into types, including Batch, Error Handling, and Flow Control. ## Batch To process Mule messages in batches, instead of processing them all together, you can use Batch components, which include: - Batch Aggregator - Batch Job - Batch Step See [Batch Processors](https://docs.mulesoft.com/mule-runtime/latest/batch-processing-concept). ## Components These Core components perform a variety of tasks: - [Custom Business Events](https://docs.mulesoft.com/mule-runtime/latest/business-events-custom): For collecting information about flows and message processors that handle your business transactions. See also [Business Events](https://docs.mulesoft.com/mule-runtime/latest/business-events). - [Dynamic Evaluate](https://docs.mulesoft.com/mule-runtime/latest/dynamic-evaluate-component-reference): For dynamically selecting a script, instead of forcing you to hardcode it through the Transform Message Component. - [Flow Reference](https://docs.mulesoft.com/mule-runtime/latest/flowref-about): For routing the Mule event to another flow or subflow (and back) within a Mule app. - [Logger](https://docs.mulesoft.com/mule-runtime/latest/logger-component-reference): For logging important information about your Mule app, such as error messages and status notifications. - [Parse Template](https://docs.mulesoft.com/mule-runtime/latest/parse-template-reference): For processing a template and obtaining a result. - [Transform Message](https://docs.mulesoft.com/mule-runtime/latest/transform-component-about): For converting input data to a new output structure or format. ## Endpoints Endpoints (sometimes called Sources in Studio) include components that initiate (or trigger) processing in a Mule flow. The [Scheduler](https://docs.mulesoft.com/mule-runtime/latest/scheduler-concept) is an endpoint. It triggers a flow to start at a configurable interval. Note that some connectors provide listeners that serve as endpoints. Listeners can trigger a flow when they receive an external request. For example, an HTTP Listener that is configured for a given URL can trigger a flow when someone or some process goes to that URL. ## Error Handling Error handling components route and process Mule errors that occur in a Mule app: - Error Handler - On Error Continue - On Error Propagate See [Error Handlers](https://docs.mulesoft.com/mule-runtime/latest/error-handling) ## Flow Control (Routers) A Flow Control component (or Router) takes the input Mule event and routes it to one or more separate sequences of components. Flow Control components include: - Choice - First Successful - Round Robin - Scatter-Gather For example, a [Choice router](https://docs.mulesoft.com/mule-runtime/latest/choice-router-concept) applies DataWeave logic to pick one of two or more routes, where each route is a separate sequence of event processors. A [Scatter-Gather router](https://docs.mulesoft.com/mule-runtime/latest/scatter-gather-concept) router sends the input event to every route, and each route independently processes the event. After every route has processed the event, the results from all the routes are combined together into one output event. ## Scopes A Scope is a type of component that groups together a sequence of event processors (such as other Core components and operations from both modules and connectors) to apply some programming behavior to that isolated sequence of event processors. Scopes include these components: - Async - Cache - Flow - For Each - Try - Until Successful For example, a Try scope lets you isolate and handle any errors that occur in a particular sequence of flows. So, you might wrap an outbound HTTP Request connector (and perhaps some other surrounding components before and after the HTTP Request connector, such as a Transform Message component or a Logging component) in a Try scope, so if an error results, you can apply logging or compensation logic specific to that grouping of components. See [Try Scope](https://docs.mulesoft.com/mule-runtime/latest/try-scope-concept). Another example is the For Each (or Foreach) scope, which takes a collection of data, usually extracted from the current input event, and applies the same sequence of event processors to every item in the collection. For example, a For Each scope might be used to process each individual row returned from a database query or each individual line from a CSV file. See [For Each Scope](https://docs.mulesoft.com/mule-runtime/latest/for-each-scope-concept). ## Transformers Transformers are components you can use to set or remove a part of the Mule event. Transformers include: - [Remove Variable](https://docs.mulesoft.com/mule-runtime/latest/remove-variable) - [Set Payload](https://docs.mulesoft.com/mule-runtime/latest/set-payload-transformer-reference) - [Set Variable](https://docs.mulesoft.com/mule-runtime/latest/variable-transformer-reference) ## See Also - [Connectors and Modules](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.11 keywords: tracing, correlation, id, anypoint, studio --- # Correlation ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When Mule creates a new event, it generates a unique identifier string called a **correlation ID** before sending the event to the next processor in the flow. This ID enables you to correlate different log entries with a particular execution. Use the correlation ID to understand the entire history of an event that resulted in an issue or an unhandled error (all errors include the correlation ID of the event that triggered it). Also, knowing the correlation ID helps you perform a memory analysis of heap dumps. To obtain a correlation ID, Mule first checks for one in the source message (for example, a JMS message or an HTTP listener with the X-CORRELATION-ID header). If the source does not set a correlation ID, Mule generates one using the correlation ID generator. ## Modify the Correlation ID Generator Although it is best to avoid making changes to the correlation ID generator, you might need to format the correlation ID for the events if: - Your company has its own standard or format for correlation IDs. - Your external system correlation IDs are a different length than those in Mule, causing an incompatibility that makes them untraceable. > [!NOTE] In CloudHub 2.0, even if you enable the correlation ID generator, the correlation-id > configured in a private space overrides the correlation ID generator. To change how Mule generates the correlation ID: 1. Add the `` component to your application XML. 2. Set the `correlationIdGeneratorExpression` attribute to specify the expression that generates the correlation ID: ```xml ``` > [!IMPORTANT] Ensure that the algorithm you use cannot generate the same correlation ID for two > different events. ### Correlation ID Generator Configuration Example In the following example, Mule generates the correlation ID by calling the Java `uuid()` method, and then replaces the dashes (`-`) with dots (`.`): ```xml ``` After executing the flow, the logger shows the following: WARN 2021-03-30 16:46:11,269 \[\[MuleRuntime\].uber.06: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: b5a95a63.f190.4c91.880a.5b54512fa6b1\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some In this case, the value `b5a95a63.f190.4c91.880a.5b54512fa6b1` is the correlation ID. ## Change the Correlation ID During the Flow Execution You might want to change the correlation ID of the event for a given scope or a set of operations if: - You are processing the results of a database query inside a `foreach` scope and you want to correlate the event with the register you are processing. - You are consuming a JMS message queue and you want to proceed using the JMS correlation ID for traceability purposes. For these scenarios, installing the Mule Tracing module enables you to use the `with-correlation-id` scope to modify the correlation ID during the execution of said scope. ### Install the Mule Tracing Module To install the Mule Tracing module in your application: 1. Open your Mule project in Anypoint Studio. 2. Go to the Mule Palette. 3. Select **Search in Exchange**, and search for the Mule Tracing module. 4. Select the module and click **Add**. 5. Click **Finish**. ### Configuration Example Consider the following Mule application: ![A flow showing a correlation ID scope configuration](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-with-correlation-id-scope.png) Application XML configuration: ```xml ``` In this case, after the application executes the flow, the output logs are: WARN 2021-03-30 16:46:11,269 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some WARN 2021-03-30 16:46:11,271 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/2/processors/0; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee-EXAMPLE\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some WARN 2021-03-30 16:46:11,274 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/3; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ## Use the DEBUG Log Level to View Additional Correlation ID Logs If you want to see additional logs related to the correlation ID, set the log level to `DEBUG` by adding the following code to your application XML: The updated logs display as follows: WARN 2021-03-30 16:58:29,545 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some DEBUG 2021-03-30 16:58:29,548 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] org.mule.runtime.module.extension.internal.runtime.operation.ImmutableProcessorChildContextChainExecutor: Changing event correlationId from '4c355b30-9192-11eb-b79f-36548d51aeee' to '4c355b30-9192-11eb-b79f-36548d51aeee-EXAMPLE' in location example/processors/2 WARN 2021-03-30 16:58:29,555 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/2/processors/0; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee-EXAMPLE\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some DEBUG 2021-03-30 16:58:29,566 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] org.mule.runtime.module.extension.internal.runtime.operation.ImmutableProcessorChildContextChainExecutor: Event with correlationId '4c355b30-9192-11eb-b79f-36548d51aeee-EXAMPLE' going back to '4c355b30-9192-11eb-b79f-36548d51aeee' (successful execution) in location example/processors/2 WARN 2021-03-30 16:58:29,568 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/3; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ## Error Handling If an error occurs, the error handler logs the correlation ID that corresponds to the flow or Try scope that contains the error handler, for example: ```xml ``` In this scenario, Mule logs the correlation ID set at the beginning of the execution, because the error stops the execution of the correlation ID scope, preventing it from setting the new correlation ID (`#[correlationId ++ '-EXAMPLE']`). However, consider the following example: ```xml ``` In this scenario, because the error handler executes within the correlation ID scope, the correlation ID logged after the flow execution is the one configured in the correlation ID scope (`#[correlationId ++ '-EXAMPLE']`). ## Example of Identifying the Correlation ID in Logs Consider the following flow: ```xml ``` After receiving a request, the flow produces the following log: WARN 2021-03-30 14:19:52,862 \[\[MuleRuntime\].uber.04: \[test-project-app\].example.CPU\_LITE @7a3620f2\] \[processor: example/processors/1; event: 23d22940-917c-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some In this case, the value `23d22940-917c-11eb-9209-3c22fb13cde7` is the correlation ID. This ID is unique for the corresponding event, so any other log that includes this correlation ID is referring to the same event. ## Example of Logging the Same Correlation ID from Different Operations Consider the following flow, which is the same as in the previous example but including a `raise-error` component: ```xml ``` After its execution, the flow generates the following log: WARN 2021-03-30 14:27:36,045 \[\[MuleRuntime\].uber.08: \[test-project-app\].example.CPU\_LITE @19afa17\] \[processor: example/processors/1; event: 37f0f591-917d-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ERROR 2021-03-30 14:27:36,052 \[\[MuleRuntime\].uber.08: \[test-project-app\].example.CPU\_LITE @19afa17\] \[processor: example/processors/2; event: 37f0f591-917d-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* Message : An error occurred. Element : example/processors/2 @ test-project-app:test-project-app.xml:16 Element DSL : Error type : APP:SOME FlowStack : at example(example/processors/2 @ test-project-app:test-project-app.xml:16) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* When the Logger and the Raise Error components execute, both components log the correlation ID `37f0f591-917d-11eb-9209-3c22fb13cde7`. Note that this correlation ID is different from the one logged in the previous example. ## Example of Setting the Correlation ID for a Database Query The following example shows a scenario in which you can modify the correlation ID while processing the results of a database query: ![A flow showing a correlation ID database query with components like Select, For Each, and Logger](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-correlation-id-db-example.png) Application XML configuration: ```xml ``` In this case, each record obtained from the database is processed within the `foreach` scope, and the correlation ID for each iteration corresponds to the `orderId` of said record. In this scenario, if there is a problem during the HTTP request operation, the correlation ID enables you to track which record caused the error. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-event) --- product: Mule Runtime version: 4.12 keywords: tracing, correlation, id, anypoint, studio --- # Correlation ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When Mule creates a new event, it generates a unique identifier string called a **correlation ID** before sending the event to the next processor in the flow. This ID enables you to correlate different log entries with a particular execution. Use the correlation ID to understand the entire history of an event that resulted in an issue or an unhandled error (all errors include the correlation ID of the event that triggered it). Also, knowing the correlation ID helps you perform a memory analysis of heap dumps. To obtain a correlation ID, Mule first checks for one in the source message (for example, a JMS message or an HTTP listener with the X-CORRELATION-ID header). If the source does not set a correlation ID, Mule generates one using the correlation ID generator. ## Modify the Correlation ID Generator Although it is best to avoid making changes to the correlation ID generator, you might need to format the correlation ID for the events if: - Your company has its own standard or format for correlation IDs. - Your external system correlation IDs are a different length than those in Mule, causing an incompatibility that makes them untraceable. > [!NOTE] In CloudHub 2.0, even if you enable the correlation ID generator, the correlation-id > configured in a private space overrides the correlation ID generator. To change how Mule generates the correlation ID: 1. Add the `` component to your application XML. 2. Set the `correlationIdGeneratorExpression` attribute to specify the expression that generates the correlation ID: ```xml ``` > [!IMPORTANT] Ensure that the algorithm you use cannot generate the same correlation ID for two > different events. ### Correlation ID Generator Configuration Example In the following example, Mule generates the correlation ID by calling the Java `uuid()` method, and then replaces the dashes (`-`) with dots (`.`): ```xml ``` After executing the flow, the logger shows the following: WARN 2021-03-30 16:46:11,269 \[\[MuleRuntime\].uber.06: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: b5a95a63.f190.4c91.880a.5b54512fa6b1\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some In this case, the value `b5a95a63.f190.4c91.880a.5b54512fa6b1` is the correlation ID. ## Change the Correlation ID During the Flow Execution You might want to change the correlation ID of the event for a given scope or a set of operations if: - You are processing the results of a database query inside a `foreach` scope and you want to correlate the event with the register you are processing. - You are consuming a JMS message queue and you want to proceed using the JMS correlation ID for traceability purposes. For these scenarios, installing the Mule Tracing module enables you to use the `with-correlation-id` scope to modify the correlation ID during the execution of said scope. ### Install the Mule Tracing Module To install the Mule Tracing module in your application: 1. Open your Mule project in Anypoint Studio. 2. Go to the Mule Palette. 3. Select **Search in Exchange**, and search for the Mule Tracing module. 4. Select the module and click **Add**. 5. Click **Finish**. ### Configuration Example Consider the following Mule application: ![A flow showing a correlation ID scope configuration](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-with-correlation-id-scope.png) Application XML configuration: ```xml ``` In this case, after the application executes the flow, the output logs are: WARN 2021-03-30 16:46:11,269 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some WARN 2021-03-30 16:46:11,271 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/2/processors/0; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee-EXAMPLE\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some WARN 2021-03-30 16:46:11,274 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/3; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ## Use the DEBUG Log Level to View Additional Correlation ID Logs If you want to see additional logs related to the correlation ID, set the log level to `DEBUG` by adding the following code to your application XML: The updated logs display as follows: WARN 2021-03-30 16:58:29,545 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some DEBUG 2021-03-30 16:58:29,548 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] org.mule.runtime.module.extension.internal.runtime.operation.ImmutableProcessorChildContextChainExecutor: Changing event correlationId from '4c355b30-9192-11eb-b79f-36548d51aeee' to '4c355b30-9192-11eb-b79f-36548d51aeee-EXAMPLE' in location example/processors/2 WARN 2021-03-30 16:58:29,555 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/2/processors/0; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee-EXAMPLE\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some DEBUG 2021-03-30 16:58:29,566 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] org.mule.runtime.module.extension.internal.runtime.operation.ImmutableProcessorChildContextChainExecutor: Event with correlationId '4c355b30-9192-11eb-b79f-36548d51aeee-EXAMPLE' going back to '4c355b30-9192-11eb-b79f-36548d51aeee' (successful execution) in location example/processors/2 WARN 2021-03-30 16:58:29,568 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/3; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ## Error Handling If an error occurs, the error handler logs the correlation ID that corresponds to the flow or Try scope that contains the error handler, for example: ```xml ``` In this scenario, Mule logs the correlation ID set at the beginning of the execution, because the error stops the execution of the correlation ID scope, preventing it from setting the new correlation ID (`#[correlationId ++ '-EXAMPLE']`). However, consider the following example: ```xml ``` In this scenario, because the error handler executes within the correlation ID scope, the correlation ID logged after the flow execution is the one configured in the correlation ID scope (`#[correlationId ++ '-EXAMPLE']`). ## Example of Identifying the Correlation ID in Logs Consider the following flow: ```xml ``` After receiving a request, the flow produces the following log: WARN 2021-03-30 14:19:52,862 \[\[MuleRuntime\].uber.04: \[test-project-app\].example.CPU\_LITE @7a3620f2\] \[processor: example/processors/1; event: 23d22940-917c-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some In this case, the value `23d22940-917c-11eb-9209-3c22fb13cde7` is the correlation ID. This ID is unique for the corresponding event, so any other log that includes this correlation ID is referring to the same event. ## Example of Logging the Same Correlation ID from Different Operations Consider the following flow, which is the same as in the previous example but including a `raise-error` component: ```xml ``` After its execution, the flow generates the following log: WARN 2021-03-30 14:27:36,045 \[\[MuleRuntime\].uber.08: \[test-project-app\].example.CPU\_LITE @19afa17\] \[processor: example/processors/1; event: 37f0f591-917d-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ERROR 2021-03-30 14:27:36,052 \[\[MuleRuntime\].uber.08: \[test-project-app\].example.CPU\_LITE @19afa17\] \[processor: example/processors/2; event: 37f0f591-917d-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* Message : An error occurred. Element : example/processors/2 @ test-project-app:test-project-app.xml:16 Element DSL : Error type : APP:SOME FlowStack : at example(example/processors/2 @ test-project-app:test-project-app.xml:16) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* When the Logger and the Raise Error components execute, both components log the correlation ID `37f0f591-917d-11eb-9209-3c22fb13cde7`. Note that this correlation ID is different from the one logged in the previous example. ## Example of Setting the Correlation ID for a Database Query The following example shows a scenario in which you can modify the correlation ID while processing the results of a database query: ![A flow showing a correlation ID database query with components like Select, For Each, and Logger](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-correlation-id-db-example.png) Application XML configuration: ```xml ``` In this case, each record obtained from the database is processed within the `foreach` scope, and the correlation ID for each iteration corresponds to the `orderId` of said record. In this scenario, if there is a problem during the HTTP request operation, the correlation ID enables you to track which record caused the error. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-event) --- product: Mule Runtime version: 4.4 keywords: tracing, correlation, id, anypoint, studio --- # Correlation ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When Mule creates a new event, it generates a unique identifier string called a **correlation ID** before sending the event to the next processor in the flow. This ID enables you to correlate different log entries with a particular execution. Use the correlation ID to understand the entire history of an event that resulted in an issue or an unhandled error (all errors include the correlation ID of the event that triggered it). Also, knowing the correlation ID helps you perform a memory analysis of heap dumps. To obtain a correlation ID, Mule first checks for one in the source message (for example, a JMS message or an HTTP listener with the X-CORRELATION-ID header). If the source does not set a correlation ID, Mule generates one using the correlation ID generator. ## Modify the Correlation ID Generator Although it is best to avoid making changes to the correlation ID generator, you might need to format the correlation ID for the events if: - Your company has its own standard or format for correlation IDs. - Your external system correlation IDs are a different length than those in Mule, causing an incompatibility that makes them untraceable. To change how Mule generates the correlation ID: 1. Add the `` component to your application XML. 2. Set the `correlationIdGeneratorExpression` attribute to specify the expression that generates the correlation ID: ```xml ``` > [!IMPORTANT] Ensure that the algorithm you use cannot generate the same correlation ID for two > different events. ### Correlation ID Generator Configuration Example In the following example, Mule generates the correlation ID by calling the Java `uuid()` method, and then replaces the dashes (`-`) with dots (`.`): ```xml ``` After executing the flow, the logger shows the following: WARN 2021-03-30 16:46:11,269 \[\[MuleRuntime\].uber.06: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: b5a95a63.f190.4c91.880a.5b54512fa6b1\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some In this case, the value `b5a95a63.f190.4c91.880a.5b54512fa6b1` is the correlation ID. ## Change the Correlation ID During the Flow Execution You might want to change the correlation ID of the event for a given scope or a set of operations if: - You are processing the results of a database query inside a `foreach` scope and you want to correlate the event with the register you are processing. - You are consuming a JMS message queue and you want to proceed using the JMS correlation ID for traceability purposes. For these scenarios, installing the Mule Tracing module enables you to use the `with-correlation-id` scope to modify the correlation ID during the execution of said scope. ### Install the Mule Tracing Module To install the Mule Tracing module in your application: 1. Open your Mule project in Anypoint Studio. 2. Go to the Mule Palette. 3. Select **Search in Exchange**, and search for the Mule Tracing module. 4. Select the module and click **Add**. 5. Click **Finish**. ### Configuration Example Consider the following Mule application: ![Correlation id scope configuration](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-with-correlation-id-scope.png) Application XML configuration: ```xml ``` In this case, after the application executes the flow, the output logs are: WARN 2021-03-30 16:46:11,269 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some WARN 2021-03-30 16:46:11,271 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/2/processors/0; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee-EXAMPLE\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some WARN 2021-03-30 16:46:11,274 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/3; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ## Use the DEBUG Log Level to View Additional Correlation ID Logs If you want to see additional logs related to the correlation ID, set the log level to `DEBUG` by adding the following code to your application XML: The updated logs display as follows: WARN 2021-03-30 16:58:29,545 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some DEBUG 2021-03-30 16:58:29,548 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] org.mule.runtime.module.extension.internal.runtime.operation.ImmutableProcessorChildContextChainExecutor: Changing event correlationId from '4c355b30-9192-11eb-b79f-36548d51aeee' to '4c355b30-9192-11eb-b79f-36548d51aeee-EXAMPLE' in location example/processors/2 WARN 2021-03-30 16:58:29,555 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/2/processors/0; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee-EXAMPLE\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some DEBUG 2021-03-30 16:58:29,566 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] org.mule.runtime.module.extension.internal.runtime.operation.ImmutableProcessorChildContextChainExecutor: Event with correlationId '4c355b30-9192-11eb-b79f-36548d51aeee-EXAMPLE' going back to '4c355b30-9192-11eb-b79f-36548d51aeee' (successful execution) in location example/processors/2 WARN 2021-03-30 16:58:29,568 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/3; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ## Error Handling If an error occurs, the error handler logs the correlation ID that corresponds to the flow or Try scope that contains the error handler, for example: ```xml ``` In this scenario, Mule logs the correlation ID set at the beginning of the execution, because the error stops the execution of the correlation ID scope, preventing it from setting the new correlation ID (`#[correlationId ++ '-EXAMPLE']`). However, consider the following example: ```xml ``` In this scenario, because the error handler executes within the correlation ID scope, the correlation ID logged after the flow execution is the one configured in the correlation ID scope (`#[correlationId ++ '-EXAMPLE']`). ## Example of Identifying the Correlation ID in Logs Consider the following flow: ```xml ``` After receiving a request, the flow produces the following log: WARN 2021-03-30 14:19:52,862 \[\[MuleRuntime\].uber.04: \[test-project-app\].example.CPU\_LITE @7a3620f2\] \[processor: example/processors/1; event: 23d22940-917c-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some In this case, the value `23d22940-917c-11eb-9209-3c22fb13cde7` is the correlation ID. This ID is unique for the corresponding event, so any other log that includes this correlation ID is referring to the same event. ## Example of Logging the Same Correlation ID from Different Operations Consider the following flow, which is the same as in the previous example but including a `raise-error` component: ```xml ``` After its execution, the flow generates the following log: WARN 2021-03-30 14:27:36,045 \[\[MuleRuntime\].uber.08: \[test-project-app\].example.CPU\_LITE @19afa17\] \[processor: example/processors/1; event: 37f0f591-917d-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ERROR 2021-03-30 14:27:36,052 \[\[MuleRuntime\].uber.08: \[test-project-app\].example.CPU\_LITE @19afa17\] \[processor: example/processors/2; event: 37f0f591-917d-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* Message : An error occurred. Element : example/processors/2 @ test-project-app:test-project-app.xml:16 Element DSL : Error type : APP:SOME FlowStack : at example(example/processors/2 @ test-project-app:test-project-app.xml:16) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* When the Logger and the Raise Error components execute, both components log the correlation ID `37f0f591-917d-11eb-9209-3c22fb13cde7`. Note that this correlation ID is different from the one logged in the previous example. ## Example of Setting the Correlation ID for a Database Query The following example shows a scenario in which you can modify the correlation ID while processing the results of a database query: ![Correlation ID Database query example](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-correlation-id-db-example.png) Application XML configuration: ```xml ``` In this case, each record obtained from the database is processed within the `foreach` scope, and the correlation ID for each iteration corresponds to the `orderId` of said record. In this scenario, if there is a problem during the HTTP request operation, the correlation ID enables you to track which record caused the error. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-event) --- product: Mule Runtime version: 4.6 keywords: tracing, correlation, id, anypoint, studio --- # Correlation ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When Mule creates a new event, it generates a unique identifier string called a **correlation ID** before sending the event to the next processor in the flow. This ID enables you to correlate different log entries with a particular execution. Use the correlation ID to understand the entire history of an event that resulted in an issue or an unhandled error (all errors include the correlation ID of the event that triggered it). Also, knowing the correlation ID helps you perform a memory analysis of heap dumps. To obtain a correlation ID, Mule first checks for one in the source message (for example, a JMS message or an HTTP listener with the X-CORRELATION-ID header). If the source does not set a correlation ID, Mule generates one using the correlation ID generator. ## Modify the Correlation ID Generator Although it is best to avoid making changes to the correlation ID generator, you might need to format the correlation ID for the events if: - Your company has its own standard or format for correlation IDs. - Your external system correlation IDs are a different length than those in Mule, causing an incompatibility that makes them untraceable. > [!NOTE] In CloudHub 2.0, even if you enable the correlation ID generator, the correlation-id > configured in a private space overrides the correlation ID generator. To change how Mule generates the correlation ID: 1. Add the `` component to your application XML. 2. Set the `correlationIdGeneratorExpression` attribute to specify the expression that generates the correlation ID: ```xml ``` > [!IMPORTANT] Ensure that the algorithm you use cannot generate the same correlation ID for two > different events. ### Correlation ID Generator Configuration Example In the following example, Mule generates the correlation ID by calling the Java `uuid()` method, and then replaces the dashes (`-`) with dots (`.`): ```xml ``` After executing the flow, the logger shows the following: WARN 2021-03-30 16:46:11,269 \[\[MuleRuntime\].uber.06: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: b5a95a63.f190.4c91.880a.5b54512fa6b1\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some In this case, the value `b5a95a63.f190.4c91.880a.5b54512fa6b1` is the correlation ID. ## Change the Correlation ID During the Flow Execution You might want to change the correlation ID of the event for a given scope or a set of operations if: - You are processing the results of a database query inside a `foreach` scope and you want to correlate the event with the register you are processing. - You are consuming a JMS message queue and you want to proceed using the JMS correlation ID for traceability purposes. For these scenarios, installing the Mule Tracing module enables you to use the `with-correlation-id` scope to modify the correlation ID during the execution of said scope. ### Install the Mule Tracing Module To install the Mule Tracing module in your application: 1. Open your Mule project in Anypoint Studio. 2. Go to the Mule Palette. 3. Select **Search in Exchange**, and search for the Mule Tracing module. 4. Select the module and click **Add**. 5. Click **Finish**. ### Configuration Example Consider the following Mule application: ![Correlation id scope configuration](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-with-correlation-id-scope.png) Application XML configuration: ```xml ``` In this case, after the application executes the flow, the output logs are: WARN 2021-03-30 16:46:11,269 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some WARN 2021-03-30 16:46:11,271 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/2/processors/0; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee-EXAMPLE\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some WARN 2021-03-30 16:46:11,274 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/3; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ## Use the DEBUG Log Level to View Additional Correlation ID Logs If you want to see additional logs related to the correlation ID, set the log level to `DEBUG` by adding the following code to your application XML: The updated logs display as follows: WARN 2021-03-30 16:58:29,545 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some DEBUG 2021-03-30 16:58:29,548 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] org.mule.runtime.module.extension.internal.runtime.operation.ImmutableProcessorChildContextChainExecutor: Changing event correlationId from '4c355b30-9192-11eb-b79f-36548d51aeee' to '4c355b30-9192-11eb-b79f-36548d51aeee-EXAMPLE' in location example/processors/2 WARN 2021-03-30 16:58:29,555 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/2/processors/0; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee-EXAMPLE\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some DEBUG 2021-03-30 16:58:29,566 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] org.mule.runtime.module.extension.internal.runtime.operation.ImmutableProcessorChildContextChainExecutor: Event with correlationId '4c355b30-9192-11eb-b79f-36548d51aeee-EXAMPLE' going back to '4c355b30-9192-11eb-b79f-36548d51aeee' (successful execution) in location example/processors/2 WARN 2021-03-30 16:58:29,568 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/3; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ## Error Handling If an error occurs, the error handler logs the correlation ID that corresponds to the flow or Try scope that contains the error handler, for example: ```xml ``` In this scenario, Mule logs the correlation ID set at the beginning of the execution, because the error stops the execution of the correlation ID scope, preventing it from setting the new correlation ID (`#[correlationId ++ '-EXAMPLE']`). However, consider the following example: ```xml ``` In this scenario, because the error handler executes within the correlation ID scope, the correlation ID logged after the flow execution is the one configured in the correlation ID scope (`#[correlationId ++ '-EXAMPLE']`). ## Example of Identifying the Correlation ID in Logs Consider the following flow: ```xml ``` After receiving a request, the flow produces the following log: WARN 2021-03-30 14:19:52,862 \[\[MuleRuntime\].uber.04: \[test-project-app\].example.CPU\_LITE @7a3620f2\] \[processor: example/processors/1; event: 23d22940-917c-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some In this case, the value `23d22940-917c-11eb-9209-3c22fb13cde7` is the correlation ID. This ID is unique for the corresponding event, so any other log that includes this correlation ID is referring to the same event. ## Example of Logging the Same Correlation ID from Different Operations Consider the following flow, which is the same as in the previous example but including a `raise-error` component: ```xml ``` After its execution, the flow generates the following log: WARN 2021-03-30 14:27:36,045 \[\[MuleRuntime\].uber.08: \[test-project-app\].example.CPU\_LITE @19afa17\] \[processor: example/processors/1; event: 37f0f591-917d-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ERROR 2021-03-30 14:27:36,052 \[\[MuleRuntime\].uber.08: \[test-project-app\].example.CPU\_LITE @19afa17\] \[processor: example/processors/2; event: 37f0f591-917d-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* Message : An error occurred. Element : example/processors/2 @ test-project-app:test-project-app.xml:16 Element DSL : Error type : APP:SOME FlowStack : at example(example/processors/2 @ test-project-app:test-project-app.xml:16) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* When the Logger and the Raise Error components execute, both components log the correlation ID `37f0f591-917d-11eb-9209-3c22fb13cde7`. Note that this correlation ID is different from the one logged in the previous example. ## Example of Setting the Correlation ID for a Database Query The following example shows a scenario in which you can modify the correlation ID while processing the results of a database query: ![Correlation ID Database query example](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-correlation-id-db-example.png) Application XML configuration: ```xml ``` In this case, each record obtained from the database is processed within the `foreach` scope, and the correlation ID for each iteration corresponds to the `orderId` of said record. In this scenario, if there is a problem during the HTTP request operation, the correlation ID enables you to track which record caused the error. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-event) --- product: Mule Runtime version: 4.9 keywords: tracing, correlation, id, anypoint, studio --- # Correlation ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When Mule creates a new event, it generates a unique identifier string called a **correlation ID** before sending the event to the next processor in the flow. This ID enables you to correlate different log entries with a particular execution. Use the correlation ID to understand the entire history of an event that resulted in an issue or an unhandled error (all errors include the correlation ID of the event that triggered it). Also, knowing the correlation ID helps you perform a memory analysis of heap dumps. To obtain a correlation ID, Mule first checks for one in the source message (for example, a JMS message or an HTTP listener with the X-CORRELATION-ID header). If the source does not set a correlation ID, Mule generates one using the correlation ID generator. ## Modify the Correlation ID Generator Although it is best to avoid making changes to the correlation ID generator, you might need to format the correlation ID for the events if: - Your company has its own standard or format for correlation IDs. - Your external system correlation IDs are a different length than those in Mule, causing an incompatibility that makes them untraceable. > [!NOTE] In CloudHub 2.0, even if you enable the correlation ID generator, the correlation-id > configured in a private space overrides the correlation ID generator. To change how Mule generates the correlation ID: 1. Add the `` component to your application XML. 2. Set the `correlationIdGeneratorExpression` attribute to specify the expression that generates the correlation ID: ```xml ``` > [!IMPORTANT] Ensure that the algorithm you use cannot generate the same correlation ID for two > different events. ### Correlation ID Generator Configuration Example In the following example, Mule generates the correlation ID by calling the Java `uuid()` method, and then replaces the dashes (`-`) with dots (`.`): ```xml ``` After executing the flow, the logger shows the following: WARN 2021-03-30 16:46:11,269 \[\[MuleRuntime\].uber.06: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: b5a95a63.f190.4c91.880a.5b54512fa6b1\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some In this case, the value `b5a95a63.f190.4c91.880a.5b54512fa6b1` is the correlation ID. ## Change the Correlation ID During the Flow Execution You might want to change the correlation ID of the event for a given scope or a set of operations if: - You are processing the results of a database query inside a `foreach` scope and you want to correlate the event with the register you are processing. - You are consuming a JMS message queue and you want to proceed using the JMS correlation ID for traceability purposes. For these scenarios, installing the Mule Tracing module enables you to use the `with-correlation-id` scope to modify the correlation ID during the execution of said scope. ### Install the Mule Tracing Module To install the Mule Tracing module in your application: 1. Open your Mule project in Anypoint Studio. 2. Go to the Mule Palette. 3. Select **Search in Exchange**, and search for the Mule Tracing module. 4. Select the module and click **Add**. 5. Click **Finish**. ### Configuration Example Consider the following Mule application: ![A flow showing a correlation ID scope configuration](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-with-correlation-id-scope.png) Application XML configuration: ```xml ``` In this case, after the application executes the flow, the output logs are: WARN 2021-03-30 16:46:11,269 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some WARN 2021-03-30 16:46:11,271 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/2/processors/0; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee-EXAMPLE\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some WARN 2021-03-30 16:46:11,274 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/3; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ## Use the DEBUG Log Level to View Additional Correlation ID Logs If you want to see additional logs related to the correlation ID, set the log level to `DEBUG` by adding the following code to your application XML: The updated logs display as follows: WARN 2021-03-30 16:58:29,545 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some DEBUG 2021-03-30 16:58:29,548 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] org.mule.runtime.module.extension.internal.runtime.operation.ImmutableProcessorChildContextChainExecutor: Changing event correlationId from '4c355b30-9192-11eb-b79f-36548d51aeee' to '4c355b30-9192-11eb-b79f-36548d51aeee-EXAMPLE' in location example/processors/2 WARN 2021-03-30 16:58:29,555 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/2/processors/0; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee-EXAMPLE\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some DEBUG 2021-03-30 16:58:29,566 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] org.mule.runtime.module.extension.internal.runtime.operation.ImmutableProcessorChildContextChainExecutor: Event with correlationId '4c355b30-9192-11eb-b79f-36548d51aeee-EXAMPLE' going back to '4c355b30-9192-11eb-b79f-36548d51aeee' (successful execution) in location example/processors/2 WARN 2021-03-30 16:58:29,568 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/3; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ## Error Handling If an error occurs, the error handler logs the correlation ID that corresponds to the flow or Try scope that contains the error handler, for example: ```xml ``` In this scenario, Mule logs the correlation ID set at the beginning of the execution, because the error stops the execution of the correlation ID scope, preventing it from setting the new correlation ID (`#[correlationId ++ '-EXAMPLE']`). However, consider the following example: ```xml ``` In this scenario, because the error handler executes within the correlation ID scope, the correlation ID logged after the flow execution is the one configured in the correlation ID scope (`#[correlationId ++ '-EXAMPLE']`). ## Example of Identifying the Correlation ID in Logs Consider the following flow: ```xml ``` After receiving a request, the flow produces the following log: WARN 2021-03-30 14:19:52,862 \[\[MuleRuntime\].uber.04: \[test-project-app\].example.CPU\_LITE @7a3620f2\] \[processor: example/processors/1; event: 23d22940-917c-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some In this case, the value `23d22940-917c-11eb-9209-3c22fb13cde7` is the correlation ID. This ID is unique for the corresponding event, so any other log that includes this correlation ID is referring to the same event. ## Example of Logging the Same Correlation ID from Different Operations Consider the following flow, which is the same as in the previous example but including a `raise-error` component: ```xml ``` After its execution, the flow generates the following log: WARN 2021-03-30 14:27:36,045 \[\[MuleRuntime\].uber.08: \[test-project-app\].example.CPU\_LITE @19afa17\] \[processor: example/processors/1; event: 37f0f591-917d-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ERROR 2021-03-30 14:27:36,052 \[\[MuleRuntime\].uber.08: \[test-project-app\].example.CPU\_LITE @19afa17\] \[processor: example/processors/2; event: 37f0f591-917d-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* Message : An error occurred. Element : example/processors/2 @ test-project-app:test-project-app.xml:16 Element DSL : Error type : APP:SOME FlowStack : at example(example/processors/2 @ test-project-app:test-project-app.xml:16) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* When the Logger and the Raise Error components execute, both components log the correlation ID `37f0f591-917d-11eb-9209-3c22fb13cde7`. Note that this correlation ID is different from the one logged in the previous example. ## Example of Setting the Correlation ID for a Database Query The following example shows a scenario in which you can modify the correlation ID while processing the results of a database query: ![A flow showing a correlation ID database query with components like Select, For Each, and Logger](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-correlation-id-db-example.png) Application XML configuration: ```xml ``` In this case, each record obtained from the database is processed within the `foreach` scope, and the correlation ID for each iteration corresponds to the `orderId` of said record. In this scenario, if there is a problem during the HTTP request operation, the correlation ID enables you to track which record caused the error. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-event) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: tracing, correlation, id, anypoint, studio --- # Correlation ID > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When Mule creates a new event, it generates a unique identifier string called a **correlation ID** before sending the event to the next processor in the flow. This ID enables you to correlate different log entries with a particular execution. Use the correlation ID to understand the entire history of an event that resulted in an issue or an unhandled error (all errors include the correlation ID of the event that triggered it). Also, knowing the correlation ID helps you perform a memory analysis of heap dumps. To obtain a correlation ID, Mule first checks for one in the source message (for example, a JMS message or an HTTP listener with the X-CORRELATION-ID header). If the source does not set a correlation ID, Mule generates one using the correlation ID generator. ## Modify the Correlation ID Generator Although it is best to avoid making changes to the correlation ID generator, you might need to format the correlation ID for the events if: - Your company has its own standard or format for correlation IDs. - Your external system correlation IDs are a different length than those in Mule, causing an incompatibility that makes them untraceable. > [!NOTE] In CloudHub 2.0, even if you enable the correlation ID generator, the correlation-id > configured in a private space overrides the correlation ID generator. To change how Mule generates the correlation ID: 1. Add the `` component to your application XML. 2. Set the `correlationIdGeneratorExpression` attribute to specify the expression that generates the correlation ID: ```xml ``` > [!IMPORTANT] Ensure that the algorithm you use cannot generate the same correlation ID for two > different events. ### Correlation ID Generator Configuration Example In the following example, Mule generates the correlation ID by calling the Java `uuid()` method, and then replaces the dashes (`-`) with dots (`.`): ```xml ``` After executing the flow, the logger shows the following: WARN 2021-03-30 16:46:11,269 \[\[MuleRuntime\].uber.06: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: b5a95a63.f190.4c91.880a.5b54512fa6b1\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some In this case, the value `b5a95a63.f190.4c91.880a.5b54512fa6b1` is the correlation ID. ## Change the Correlation ID During the Flow Execution You might want to change the correlation ID of the event for a given scope or a set of operations if: - You are processing the results of a database query inside a `foreach` scope and you want to correlate the event with the register you are processing. - You are consuming a JMS message queue and you want to proceed using the JMS correlation ID for traceability purposes. For these scenarios, installing the Mule Tracing module enables you to use the `with-correlation-id` scope to modify the correlation ID during the execution of said scope. ### Install the Mule Tracing Module To install the Mule Tracing module in your application: 1. Open your Mule project in Anypoint Studio. 2. Go to the Mule Palette. 3. Select **Search in Exchange**, and search for the Mule Tracing module. 4. Select the module and click **Add**. 5. Click **Finish**. ### Configuration Example Consider the following Mule application: ![A flow showing a correlation ID scope configuration](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-with-correlation-id-scope.png) Application XML configuration: ```xml ``` In this case, after the application executes the flow, the output logs are: WARN 2021-03-30 16:46:11,269 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some WARN 2021-03-30 16:46:11,271 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/2/processors/0; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee-EXAMPLE\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some WARN 2021-03-30 16:46:11,274 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/3; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ## Use the DEBUG Log Level to View Additional Correlation ID Logs If you want to see additional logs related to the correlation ID, set the log level to `DEBUG` by adding the following code to your application XML: The updated logs display as follows: WARN 2021-03-30 16:58:29,545 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/1; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some DEBUG 2021-03-30 16:58:29,548 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] org.mule.runtime.module.extension.internal.runtime.operation.ImmutableProcessorChildContextChainExecutor: Changing event correlationId from '4c355b30-9192-11eb-b79f-36548d51aeee' to '4c355b30-9192-11eb-b79f-36548d51aeee-EXAMPLE' in location example/processors/2 WARN 2021-03-30 16:58:29,555 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/2/processors/0; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee-EXAMPLE\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some DEBUG 2021-03-30 16:58:29,566 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] org.mule.runtime.module.extension.internal.runtime.operation.ImmutableProcessorChildContextChainExecutor: Event with correlationId '4c355b30-9192-11eb-b79f-36548d51aeee-EXAMPLE' going back to '4c355b30-9192-11eb-b79f-36548d51aeee' (successful execution) in location example/processors/2 WARN 2021-03-30 16:58:29,568 \[\[MuleRuntime\].uber.05: \[test-project-app\].example.CPU\_LITE @6d3b5ad\] \[processor: example/processors/3; event: bad0e5b0-9191-11eb-a0b3-36548d51aeee\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ## Error Handling If an error occurs, the error handler logs the correlation ID that corresponds to the flow or Try scope that contains the error handler, for example: ```xml ``` In this scenario, Mule logs the correlation ID set at the beginning of the execution, because the error stops the execution of the correlation ID scope, preventing it from setting the new correlation ID (`#[correlationId ++ '-EXAMPLE']`). However, consider the following example: ```xml ``` In this scenario, because the error handler executes within the correlation ID scope, the correlation ID logged after the flow execution is the one configured in the correlation ID scope (`#[correlationId ++ '-EXAMPLE']`). ## Example of Identifying the Correlation ID in Logs Consider the following flow: ```xml ``` After receiving a request, the flow produces the following log: WARN 2021-03-30 14:19:52,862 \[\[MuleRuntime\].uber.04: \[test-project-app\].example.CPU\_LITE @7a3620f2\] \[processor: example/processors/1; event: 23d22940-917c-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some In this case, the value `23d22940-917c-11eb-9209-3c22fb13cde7` is the correlation ID. This ID is unique for the corresponding event, so any other log that includes this correlation ID is referring to the same event. ## Example of Logging the Same Correlation ID from Different Operations Consider the following flow, which is the same as in the previous example but including a `raise-error` component: ```xml ``` After its execution, the flow generates the following log: WARN 2021-03-30 14:27:36,045 \[\[MuleRuntime\].uber.08: \[test-project-app\].example.CPU\_LITE @19afa17\] \[processor: example/processors/1; event: 37f0f591-917d-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: some ERROR 2021-03-30 14:27:36,052 \[\[MuleRuntime\].uber.08: \[test-project-app\].example.CPU\_LITE @19afa17\] \[processor: example/processors/2; event: 37f0f591-917d-11eb-9209-3c22fb13cde7\] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* Message : An error occurred. Element : example/processors/2 @ test-project-app:test-project-app.xml:16 Element DSL : Error type : APP:SOME FlowStack : at example(example/processors/2 @ test-project-app:test-project-app.xml:16) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* When the Logger and the Raise Error components execute, both components log the correlation ID `37f0f591-917d-11eb-9209-3c22fb13cde7`. Note that this correlation ID is different from the one logged in the previous example. ## Example of Setting the Correlation ID for a Database Query The following example shows a scenario in which you can modify the correlation ID while processing the results of a database query: ![A flow showing a correlation ID database query with components like Select, For Each, and Logger](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-correlation-id-db-example.png) Application XML configuration: ```xml ``` In this case, each record obtained from the database is processed within the `foreach` scope, and the correlation ID for each iteration corresponds to the `orderId` of said record. In this scenario, if there is a problem during the HTTP request operation, the correlation ID enables you to track which record caused the error. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/latest/about-mule-event) --- product: Mule Runtime version: 4.11 --- # Create Placeholders for Spring Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Spring module in a Mule app can use any sort of Spring configurations. You can define the Spring property placeholders in a `.properties` file (for example, `spring-properties.properties`) that are fully interoperable with the Spring module. The properties in the file takes this form: springPropertyA=springPropertyAValue springPropertyB=springPropertyBValue In Anypoint Studio, you must store the file in the project directory for your Mule app: - `/src/main/resources` You can add the `.properties` file to your Mule app through the Global Element called Configuration Properties. The XML for this element looks like this: `` Note that you cannot use a YAML file to create Spring property placeholders, as you can for non-Spring modules. ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.11/configuring-properties) - [Create Property Placeholders for Mule Apps](https://docs.mulesoft.com/mule-runtime/4.11/mule-app-properties-to-configure) --- product: Mule Runtime version: 4.12 --- # Create Placeholders for Spring Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Spring module in a Mule app can use any sort of Spring configurations. You can define the Spring property placeholders in a `.properties` file (for example, `spring-properties.properties`) that are fully interoperable with the Spring module. The properties in the file takes this form: springPropertyA=springPropertyAValue springPropertyB=springPropertyBValue In Anypoint Studio, you must store the file in the project directory for your Mule app: - `/src/main/resources` You can add the `.properties` file to your Mule app through the Global Element called Configuration Properties. The XML for this element looks like this: `` Note that you cannot use a YAML file to create Spring property placeholders, as you can for non-Spring modules. ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.12/configuring-properties) - [Create Property Placeholders for Mule Apps](https://docs.mulesoft.com/mule-runtime/4.12/mule-app-properties-to-configure) --- product: Mule Runtime version: 4.3 --- # Create Placeholders for Spring Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Spring module in a Mule app can use any sort of Spring configurations. You can define the Spring property placeholders in a `.properties` file (for example, `spring-properties.properties`) that are fully interoperable with the Spring module. The properties in the file takes this form: springPropertyA=springPropertyAValue springPropertyB=springPropertyBValue In Anypoint Studio, you must store the file in the project directory for your Mule app: - `/src/main/resources` You can add the `.properties` file to your Mule app through the Global Element called Configuration Properties. The XML for this element looks like this: `` Note that you cannot use a YAML file to create Spring property placeholders, as you can for non-Spring modules. ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.3/configuring-properties) - [Create Property Placeholders for Mule Apps](https://docs.mulesoft.com/mule-runtime/4.3/mule-app-properties-to-configure) --- product: Mule Runtime version: 4.4 --- # Create Placeholders for Spring Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Spring module in a Mule app can use any sort of Spring configurations. You can define the Spring property placeholders in a `.properties` file (for example, `spring-properties.properties`) that are fully interoperable with the Spring module. The properties in the file takes this form: springPropertyA=springPropertyAValue springPropertyB=springPropertyBValue In Anypoint Studio, you must store the file in the project directory for your Mule app: - `/src/main/resources` You can add the `.properties` file to your Mule app through the Global Element called Configuration Properties. The XML for this element looks like this: `` Note that you cannot use a YAML file to create Spring property placeholders, as you can for non-Spring modules. ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.4/configuring-properties) - [Create Property Placeholders for Mule Apps](https://docs.mulesoft.com/mule-runtime/4.4/mule-app-properties-to-configure) --- product: Mule Runtime version: 4.6 --- # Create Placeholders for Spring Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Spring module in a Mule app can use any sort of Spring configurations. You can define the Spring property placeholders in a `.properties` file (for example, `spring-properties.properties`) that are fully interoperable with the Spring module. The properties in the file takes this form: springPropertyA=springPropertyAValue springPropertyB=springPropertyBValue In Anypoint Studio, you must store the file in the project directory for your Mule app: - `/src/main/resources` You can add the `.properties` file to your Mule app through the Global Element called Configuration Properties. The XML for this element looks like this: `` Note that you cannot use a YAML file to create Spring property placeholders, as you can for non-Spring modules. ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.6/configuring-properties) - [Create Property Placeholders for Mule Apps](https://docs.mulesoft.com/mule-runtime/4.6/mule-app-properties-to-configure) --- product: Mule Runtime version: 4.9 --- # Create Placeholders for Spring Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Spring module in a Mule app can use any sort of Spring configurations. You can define the Spring property placeholders in a `.properties` file (for example, `spring-properties.properties`) that are fully interoperable with the Spring module. The properties in the file takes this form: springPropertyA=springPropertyAValue springPropertyB=springPropertyBValue In Anypoint Studio, you must store the file in the project directory for your Mule app: - `/src/main/resources` You can add the `.properties` file to your Mule app through the Global Element called Configuration Properties. The XML for this element looks like this: `` Note that you cannot use a YAML file to create Spring property placeholders, as you can for non-Spring modules. ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.9/configuring-properties) - [Create Property Placeholders for Mule Apps](https://docs.mulesoft.com/mule-runtime/4.9/mule-app-properties-to-configure) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Create Placeholders for Spring Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Spring module in a Mule app can use any sort of Spring configurations. You can define the Spring property placeholders in a `.properties` file (for example, `spring-properties.properties`) that are fully interoperable with the Spring module. The properties in the file takes this form: springPropertyA=springPropertyAValue springPropertyB=springPropertyBValue In Anypoint Studio, you must store the file in the project directory for your Mule app: - `/src/main/resources` You can add the `.properties` file to your Mule app through the Global Element called Configuration Properties. The XML for this element looks like this: `` Note that you cannot use a YAML file to create Spring property placeholders, as you can for non-Spring modules. ## See Also - [Configure Properties](https://docs.mulesoft.com/mule-runtime/latest/configuring-properties) - [Create Property Placeholders for Mule Apps](https://docs.mulesoft.com/mule-runtime/latest/mule-app-properties-to-configure) --- product: Mule Runtime version: 4.11 --- # Custom Business Event Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Use the Custom Business Event component (`tracking:custom-event` element in the XML view) to add metadata and Key Performance Indicators (KPIs) to your flow. Configure the component as follows: 1. Click the **Mule Palette** tab in Anypoint Studio. 2. Drag **Custom Business Event** to any point of your flow. 3. Open the component properties view and specify values for **Display Name** and **Event Name**: ![Setup for a custom business event](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-custom-business-event.png) You can also configure Key Performance Indicators (KPIs) to capture information from the message payload: - In the UI: 1. Click the plus button (![Add icon](/mulesoft/current/en-us/mule-runtime/4.11/_images/green-plus-icon.png)\]) inside **Key Performance Indicators**. 2. Configure **Name** and **Expression / Value**: ![A configuration panel showing settings for a key performance indicator](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-business-events-kpi.png) - In the XML: 1. Add a child `tracking:meta-data` element to the `tracking:custom-event`. 2. Configure the `key` and `value` attributes inside `tracking:meta-data`: For example: ```xml ``` For your KPIs, use names that are easy to search for in the Anypoint Runtime Manager interface, and use a representative value, which can be any Mule expression:
NameExpression / Value

employee-id

#[payload['ID']]

employee-email

#[payload['Email']]

employee-git-id

#[payload['GITHUB_ID']]

price

700

price-after-discount

#[vars.price]

order-id

#[payload.order.header.orderID]

## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/4.11/business-events) --- product: Mule Runtime version: 4.12 --- # Custom Business Event Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Use the Custom Business Event component (`tracking:custom-event` element in the XML view) to add metadata and Key Performance Indicators (KPIs) to your flow. Configure the component as follows: 1. Click the **Mule Palette** tab in Anypoint Studio. 2. Drag **Custom Business Event** to any point of your flow. 3. Open the component properties view and specify values for **Display Name** and **Event Name**: ![Setup for a custom business event](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-custom-business-event.png) You can also configure Key Performance Indicators (KPIs) to capture information from the message payload: - In the UI: 1. Click the plus button (![Add icon](/mulesoft/current/en-us/mule-runtime/4.12/_images/green-plus-icon.png)\]) inside **Key Performance Indicators**. 2. Configure **Name** and **Expression / Value**: ![A configuration panel showing settings for a key performance indicator](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-business-events-kpi.png) - In the XML: 1. Add a child `tracking:meta-data` element to the `tracking:custom-event`. 2. Configure the `key` and `value` attributes inside `tracking:meta-data`: For example: ```xml ``` For your KPIs, use names that are easy to search for in the Anypoint Runtime Manager interface, and use a representative value, which can be any Mule expression:
NameExpression / Value

employee-id

#[payload['ID']]

employee-email

#[payload['Email']]

employee-git-id

#[payload['GITHUB_ID']]

price

700

price-after-discount

#[vars.price]

order-id

#[payload.order.header.orderID]

## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/4.12/business-events) --- product: Mule Runtime version: 4.3 --- # Custom Business Event Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Use the Custom Business Event component (`tracking:custom-event` element in the XML view) to add metadata and Key Performance Indicators (KPIs) to your flow. Configure the component as follows: 1. Click the **Mule Palette** tab in Anypoint Studio. 2. Drag **Custom Business Event** to any point of your flow. 3. Open the component properties view and specify values for **Display Name** and **Event Name**: ![custom-business-event](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-custom-business-event.png) You can also configure Key Performance Indicators (KPIs) to capture information from the message payload: - In the UI: 1. Click the plus button (![2%](/mulesoft/current/en-us/mule-runtime/4.3/_images/green-plus-icon.png)) inside **Key Performance Indicators**. 2. Configure **Name** and **Expression / Value**: ![business-events-kpi](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-business-events-kpi.png) - In the XML: 1. Add a child `tracking:meta-data` element to the `tracking:custom-event`. 2. Configure the `key` and `value` attributes inside `tracking:meta-data`: For example: ```xml ``` For your KPIs, use names that are easy to search for in the Anypoint Runtime Manager interface, and use a representative value, which can be any Mule expression:
NameExpression / Value

employee-id

#[payload['ID']]

employee-email

#[payload['Email']]

employee-git-id

#[payload['GITHUB_ID']]

price

700

price-after-discount

#[vars.price]

order-id

#[payload.order.header.orderID]

## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/4.3/business-events) --- product: Mule Runtime version: 4.4 --- # Custom Business Event Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Use the Custom Business Event component (`tracking:custom-event` element in the XML view) to add metadata and Key Performance Indicators (KPIs) to your flow. Configure the component as follows: 1. Click the **Mule Palette** tab in Anypoint Studio. 2. Drag **Custom Business Event** to any point of your flow. 3. Open the component properties view and specify values for **Display Name** and **Event Name**: ![custom-business-event](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-custom-business-event.png) You can also configure Key Performance Indicators (KPIs) to capture information from the message payload: - In the UI: 1. Click the plus button (![2%](/mulesoft/current/en-us/mule-runtime/4.4/_images/green-plus-icon.png)) inside **Key Performance Indicators**. 2. Configure **Name** and **Expression / Value**: ![business-events-kpi](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-business-events-kpi.png) - In the XML: 1. Add a child `tracking:meta-data` element to the `tracking:custom-event`. 2. Configure the `key` and `value` attributes inside `tracking:meta-data`: For example: ```xml ``` For your KPIs, use names that are easy to search for in the Anypoint Runtime Manager interface, and use a representative value, which can be any Mule expression:
NameExpression / Value

employee-id

#[payload['ID']]

employee-email

#[payload['Email']]

employee-git-id

#[payload['GITHUB_ID']]

price

700

price-after-discount

#[vars.price]

order-id

#[payload.order.header.orderID]

## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/4.4/business-events) --- product: Mule Runtime version: 4.6 --- # Custom Business Event Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Use the Custom Business Event component (`tracking:custom-event` element in the XML view) to add metadata and Key Performance Indicators (KPIs) to your flow. Configure the component as follows: 1. Click the **Mule Palette** tab in Anypoint Studio. 2. Drag **Custom Business Event** to any point of your flow. 3. Open the component properties view and specify values for **Display Name** and **Event Name**: ![custom-business-event](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-custom-business-event.png) You can also configure Key Performance Indicators (KPIs) to capture information from the message payload: - In the UI: 1. Click the plus button (![2%](/mulesoft/current/en-us/mule-runtime/4.6/_images/green-plus-icon.png)) inside **Key Performance Indicators**. 2. Configure **Name** and **Expression / Value**: ![business-events-kpi](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-business-events-kpi.png) - In the XML: 1. Add a child `tracking:meta-data` element to the `tracking:custom-event`. 2. Configure the `key` and `value` attributes inside `tracking:meta-data`: For example: ```xml ``` For your KPIs, use names that are easy to search for in the Anypoint Runtime Manager interface, and use a representative value, which can be any Mule expression:
NameExpression / Value

employee-id

#[payload['ID']]

employee-email

#[payload['Email']]

employee-git-id

#[payload['GITHUB_ID']]

price

700

price-after-discount

#[vars.price]

order-id

#[payload.order.header.orderID]

## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/4.6/business-events) --- product: Mule Runtime version: 4.9 --- # Custom Business Event Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Use the Custom Business Event component (`tracking:custom-event` element in the XML view) to add metadata and Key Performance Indicators (KPIs) to your flow. Configure the component as follows: 1. Click the **Mule Palette** tab in Anypoint Studio. 2. Drag **Custom Business Event** to any point of your flow. 3. Open the component properties view and specify values for **Display Name** and **Event Name**: ![Setup for a custom business event](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-custom-business-event.png) You can also configure Key Performance Indicators (KPIs) to capture information from the message payload: - In the UI: 1. Click the plus button (![Add icon](/mulesoft/current/en-us/mule-runtime/4.9/_images/green-plus-icon.png)\]) inside **Key Performance Indicators**. 2. Configure **Name** and **Expression / Value**: ![A configuration panel showing settings for a key performance indicator](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-business-events-kpi.png) - In the XML: 1. Add a child `tracking:meta-data` element to the `tracking:custom-event`. 2. Configure the `key` and `value` attributes inside `tracking:meta-data`: For example: ```xml ``` For your KPIs, use names that are easy to search for in the Anypoint Runtime Manager interface, and use a representative value, which can be any Mule expression:
NameExpression / Value

employee-id

#[payload['ID']]

employee-email

#[payload['Email']]

employee-git-id

#[payload['GITHUB_ID']]

price

700

price-after-discount

#[vars.price]

order-id

#[payload.order.header.orderID]

## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/4.9/business-events) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Custom Business Event Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Use the Custom Business Event component (`tracking:custom-event` element in the XML view) to add metadata and Key Performance Indicators (KPIs) to your flow. Configure the component as follows: 1. Click the **Mule Palette** tab in Anypoint Studio. 2. Drag **Custom Business Event** to any point of your flow. 3. Open the component properties view and specify values for **Display Name** and **Event Name**: ![Setup for a custom business event](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-custom-business-event.png) You can also configure Key Performance Indicators (KPIs) to capture information from the message payload: - In the UI: 1. Click the plus button (![Add icon](/mulesoft/current/en-us/mule-runtime/latest/_images/green-plus-icon.png)\]) inside **Key Performance Indicators**. 2. Configure **Name** and **Expression / Value**: ![A configuration panel showing settings for a key performance indicator](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-business-events-kpi.png) - In the XML: 1. Add a child `tracking:meta-data` element to the `tracking:custom-event`. 2. Configure the `key` and `value` attributes inside `tracking:meta-data`: For example: ```xml ``` For your KPIs, use names that are easy to search for in the Anypoint Runtime Manager interface, and use a representative value, which can be any Mule expression:
NameExpression / Value

employee-id

#[payload['ID']]

employee-email

#[payload['Email']]

employee-git-id

#[payload['GITHUB_ID']]

price

700

price-after-discount

#[vars.price]

order-id

#[payload.order.header.orderID]

## See Also [Business Events](https://docs.mulesoft.com/mule-runtime/latest/business-events) --- product: Mule Runtime version: 4.11 keywords: anypoint, studio, on premises, on premise, properties, custom configuration properties, configuration properties provider --- # Custom Configuration Properties Provider > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can use the Mule SDK and Mule API to create a custom configuration properties provider that enables an app to discover configuration properties values. ## Mule API The main interfaces of the API are: - `ConfigurationPropertiesProviderFactory` This interface is used to discover custom implementations of configuration properties providers. When Mule runtime engine (Mule) finds a configuration element that matches the namespace and name provided by the `getSupportedComponentIdentifier()` method, Mule requests the factory to create a `ConfigurationPropertiesProvider` using the configuration you define with the `createProvider(..)` method. Mule discovers instances of `ConfigurationPropertiesProviderFactory` by using SPI. - `ConfigurationPropertiesProvider` When Mule finds a configuration property, Mule invokes this interface to resolve the property’s value. ## Example: Secure Configuration Properties Provider The Security module uses the API to implement `ConfigurationPropertiesProviderFactory`: ```java import static org.mule.runtime.api.component.ComponentIdentifier.builder; import org.mule.runtime.properties.api.ConfigurationPropertiesProviderFactory; public class SecureConfigurationPropertiesProviderFactory implements ConfigurationPropertiesProviderFactory { public static final String EXTENSION_NAMESPACE = "secure-properties"; public static final String SECURE_CONFIGURATION_PROPERTIES_ELEMENT = "config"; public static final ComponentIdentifier SECURE_CONFIGURATION_PROPERTIES = builder().namespace(EXTENSION_NAMESPACE).name(SECURE_CONFIGURATION_PROPERTIES_ELEMENT).build(); ... @Override public ComponentIdentifier getSupportedComponentIdentifier() { return SECURE_CONFIGURATION_PROPERTIES; } @Override public SecureConfigurationPropertiesProvider createProvider(ConfigurationParameters parameters, ResourceProvider externalResourceProvider) { String file = parameters.getStringParameter("file"); .. String key = parameters.getStringParameter("key"); ... return new SecureConfigurationPropertiesProvider(..); } } ``` The `ComponentIdentifier` returned by `getSupportedComponentIdentifier()` matches against the following configuration component: ```xml ``` When processing the configuration, Mule finds the `secure-properties:config` component, and then invokes the `SecureConfigurationPropertiesProvider.createProvider(..)` method to create an instance of `SecureConfigurationPropertiesProvider` to resolve configuration properties. ```java public class SecureConfigurationPropertiesProvider extends DefaultConfigurationPropertiesProvider { private final static String SECURE_PREFIX = "secure::"; private final static Pattern SECURE_PATTERN = Pattern.compile("\\$\\{" + SECURE_PREFIX + "[^}]*}"); private final EncryptionAlgorithm algorithm; private final EncryptionMode mode; private final boolean fileLevelEncryption; private final SecurePropertyPlaceholderModule securePropertyPlaceholderModule = new SecurePropertyPlaceholderModule(); public SecureConfigurationPropertiesProvider(ResourceProvider resourceProvider, String file, EncryptionAlgorithm algorithm, String key, EncryptionMode mode, String encoding, boolean fileLevelEncryption) { ... } @Override public Optional getConfigurationProperty(String configurationAttributeKey) { if (configurationAttributeKey.startsWith(SECURE_PREFIX)) { String effectiveKey = configurationAttributeKey.substring(SECURE_PREFIX.length()); ConfigurationProperty originalConfigurationProperty = configurationAttributes.get(effectiveKey); if (originalConfigurationProperty == null) { return empty(); } String originalString = ((String) originalConfigurationProperty.getRawValue()); String encryptedValue = originalString.substring(originalConfigurationProperty.getKey().length() + 1, originalString.length() - algorithm.name().length() - mode.name().length() - 2); final String decryptedValue = resolveInnerProperties(securePropertyPlaceholderModule.convertPropertyValue(encryptedValue)); return of(new ConfigurationProperty() { @Override public Object getSource() { return originalConfigurationProperty.getSource(); } @Override public Object getRawValue() { return decryptedValue; } @Override public String getKey() { return originalConfigurationProperty.getKey(); } }); } else { return empty(); } } @Override public String getDescription() { ComponentLocation location = (ComponentLocation) getAnnotation(LOCATION_KEY); return format(" - file: %s, line number: %s", fileLocation, location.getFileName().orElse(UNKNOWN), location.getLineInFile().map(String::valueOf).orElse("unknown")); } ... } ``` Define a prefix (with the format `PREFIX::`) that is unique to this resolver. The prefix enables the user to target a specific resolver. This is implemented in `SecureConfigurationPropertiesProvider` by using the prefix defined by `SECURE_PREFIX`. In the configuration, the prefix must be used in the following way: ```xml ``` Notice how the `value` attribute of `set-payload` is using the resolver for secure properties by using the `secure::` prefix. ## Example: Mule SDK Module To create a configuration element that enables the custom configuration properties provider within Studio, you must create a Mule SDK module. You can download or checkout the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example), which contains all the infrastructure code to get started implementing your custom configuration properties resolver extension. The sample project is a Mule SDK module. See [Getting started with the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started) for additional information. ### Customizing the Module to Access Your Custom Properties Source Follow these steps to customize the Mule SDK Module: 1. Import the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example) into your favorite IDE. 2. Open the `pom.xml` file: 1. Define the GAV (`groupId`, `artifactId`, and `version`) of your module. 2. Define the `name` of your module. 3. Review the minimum Mule version you want your properties provider to require. This example is compatible with Mule 4.1.1 and later to cover all possible scenarios. See [Choosing the SDK Version](https://docs.mulesoft.com/mule-sdk/latest/choosing-version). 3. Change the package name (`com.my.company.custom.provider.api`) of your code. 4. Open `resources/META-INF/services/org.mule.runtime.config.api.dsl.model.properties.ConfigurationPropertiesProviderFactory`, and change the content to match the package name you changed previously. 5. Open the `CustomConfigurationPropertiesExtension` class: 1. Change the `EXTENSION_NAME` constant to the name of your module. 2. Change the `vendor` method parameter on the `@Extension` annotation to your company name. 3. Customize the section at the end to define the parameters that can be configured in the `config` element of your module. 6. Open the `CustomConfigurationPropertiesProviderFactory` class: 1. Change the `CUSTOM_PROPERTIES_PREFIX` value to a meaningful prefix for the configuration properties that your module must resolve. 2. Change the class implementation to look up the properties from your custom source. 7. Update the MUnit test cases in `test/munit` with more test cases to cover your new module functionality. Once your module is ready, you can install it locally using `mvn clean install` to make the module accessible from Studio. ## Using the Custom Properties Provider in a Mule Application To use the custom properties provider: 1. Create an application in Studio. 2. Add the dependency to you new module: 1. Open the `pom.xml` file. 2. Within the `` tag, add a new dependency using the GAV that you put in your module. 3. Remember to add `mule-plugin` because it is a Mule module. 4. Save your changes. Now, open the application XML file and in the **Global Elements** tab and click **Create**. Under **Connector Configuration**, you should see an option for selecting the configuration from your custom module, for example: ![Screen for selecting a type of global configuration element with a search function](/mulesoft/current/en-us/mule-runtime/4.11/_images/custom-configuration-provider.png) You can now configure your new component and start using properties with the prefix defined in your module. ## Using Custom Configuration Properties Provider versus a Connector For static properties, use the properties provider approach, because static properties don’t change during runtime. If your properties might change during runtime, create a connector that can provide the value as one of its operations. > [!NOTE] Although the [Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) is used to > implement a custom configuration properties provider, you can’t use > [ConnectionProviders](https://docs.mulesoft.com/mule-sdk/latest/connections) to connect to external sources. This is > because `ConnectionProviders` are managed by Mule runtime and are initialized at a later stage, > after the static properties are resolved. Consequently, connectivity testing isn’t supported for > custom properties providers. --- product: Mule Runtime version: 4.12 keywords: anypoint, studio, on premises, on premise, properties, custom configuration properties, configuration properties provider --- # Custom Configuration Properties Provider > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can use the Mule SDK and Mule API to create a custom configuration properties provider that enables an app to discover configuration properties values. ## Mule API The main interfaces of the API are: - `ConfigurationPropertiesProviderFactory` This interface is used to discover custom implementations of configuration properties providers. When Mule runtime engine (Mule) finds a configuration element that matches the namespace and name provided by the `getSupportedComponentIdentifier()` method, Mule requests the factory to create a `ConfigurationPropertiesProvider` using the configuration you define with the `createProvider(..)` method. Mule discovers instances of `ConfigurationPropertiesProviderFactory` by using SPI. - `ConfigurationPropertiesProvider` When Mule finds a configuration property, Mule invokes this interface to resolve the property’s value. ## Example: Secure Configuration Properties Provider The Security module uses the API to implement `ConfigurationPropertiesProviderFactory`: ```java import static org.mule.runtime.api.component.ComponentIdentifier.builder; import org.mule.runtime.properties.api.ConfigurationPropertiesProviderFactory; public class SecureConfigurationPropertiesProviderFactory implements ConfigurationPropertiesProviderFactory { public static final String EXTENSION_NAMESPACE = "secure-properties"; public static final String SECURE_CONFIGURATION_PROPERTIES_ELEMENT = "config"; public static final ComponentIdentifier SECURE_CONFIGURATION_PROPERTIES = builder().namespace(EXTENSION_NAMESPACE).name(SECURE_CONFIGURATION_PROPERTIES_ELEMENT).build(); ... @Override public ComponentIdentifier getSupportedComponentIdentifier() { return SECURE_CONFIGURATION_PROPERTIES; } @Override public SecureConfigurationPropertiesProvider createProvider(ConfigurationParameters parameters, ResourceProvider externalResourceProvider) { String file = parameters.getStringParameter("file"); .. String key = parameters.getStringParameter("key"); ... return new SecureConfigurationPropertiesProvider(..); } } ``` The `ComponentIdentifier` returned by `getSupportedComponentIdentifier()` matches against the following configuration component: ```xml ``` When processing the configuration, Mule finds the `secure-properties:config` component, and then invokes the `SecureConfigurationPropertiesProvider.createProvider(..)` method to create an instance of `SecureConfigurationPropertiesProvider` to resolve configuration properties. ```java public class SecureConfigurationPropertiesProvider extends DefaultConfigurationPropertiesProvider { private final static String SECURE_PREFIX = "secure::"; private final static Pattern SECURE_PATTERN = Pattern.compile("\\$\\{" + SECURE_PREFIX + "[^}]*}"); private final EncryptionAlgorithm algorithm; private final EncryptionMode mode; private final boolean fileLevelEncryption; private final SecurePropertyPlaceholderModule securePropertyPlaceholderModule = new SecurePropertyPlaceholderModule(); public SecureConfigurationPropertiesProvider(ResourceProvider resourceProvider, String file, EncryptionAlgorithm algorithm, String key, EncryptionMode mode, String encoding, boolean fileLevelEncryption) { ... } @Override public Optional getConfigurationProperty(String configurationAttributeKey) { if (configurationAttributeKey.startsWith(SECURE_PREFIX)) { String effectiveKey = configurationAttributeKey.substring(SECURE_PREFIX.length()); ConfigurationProperty originalConfigurationProperty = configurationAttributes.get(effectiveKey); if (originalConfigurationProperty == null) { return empty(); } String originalString = ((String) originalConfigurationProperty.getRawValue()); String encryptedValue = originalString.substring(originalConfigurationProperty.getKey().length() + 1, originalString.length() - algorithm.name().length() - mode.name().length() - 2); final String decryptedValue = resolveInnerProperties(securePropertyPlaceholderModule.convertPropertyValue(encryptedValue)); return of(new ConfigurationProperty() { @Override public Object getSource() { return originalConfigurationProperty.getSource(); } @Override public Object getRawValue() { return decryptedValue; } @Override public String getKey() { return originalConfigurationProperty.getKey(); } }); } else { return empty(); } } @Override public String getDescription() { ComponentLocation location = (ComponentLocation) getAnnotation(LOCATION_KEY); return format(" - file: %s, line number: %s", fileLocation, location.getFileName().orElse(UNKNOWN), location.getLineInFile().map(String::valueOf).orElse("unknown")); } ... } ``` Define a prefix (with the format `PREFIX::`) that is unique to this resolver. The prefix enables the user to target a specific resolver. This is implemented in `SecureConfigurationPropertiesProvider` by using the prefix defined by `SECURE_PREFIX`. In the configuration, the prefix must be used in the following way: ```xml ``` Notice how the `value` attribute of `set-payload` is using the resolver for secure properties by using the `secure::` prefix. ## Example: Mule SDK Module To create a configuration element that enables the custom configuration properties provider within Studio, you must create a Mule SDK module. You can download or checkout the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example), which contains all the infrastructure code to get started implementing your custom configuration properties resolver extension. The sample project is a Mule SDK module. See [Getting started with the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started) for additional information. ### Customizing the Module to Access Your Custom Properties Source Follow these steps to customize the Mule SDK Module: 1. Import the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example) into your favorite IDE. 2. Open the `pom.xml` file: 1. Define the GAV (`groupId`, `artifactId`, and `version`) of your module. 2. Define the `name` of your module. 3. Review the minimum Mule version you want your properties provider to require. This example is compatible with Mule 4.1.1 and later to cover all possible scenarios. See [Choosing the SDK Version](https://docs.mulesoft.com/mule-sdk/latest/choosing-version). 3. Change the package name (`com.my.company.custom.provider.api`) of your code. 4. Open `resources/META-INF/services/org.mule.runtime.config.api.dsl.model.properties.ConfigurationPropertiesProviderFactory`, and change the content to match the package name you changed previously. 5. Open the `CustomConfigurationPropertiesExtension` class: 1. Change the `EXTENSION_NAME` constant to the name of your module. 2. Change the `vendor` method parameter on the `@Extension` annotation to your company name. 3. Customize the section at the end to define the parameters that can be configured in the `config` element of your module. 6. Open the `CustomConfigurationPropertiesProviderFactory` class: 1. Change the `CUSTOM_PROPERTIES_PREFIX` value to a meaningful prefix for the configuration properties that your module must resolve. 2. Change the class implementation to look up the properties from your custom source. 7. Update the MUnit test cases in `test/munit` with more test cases to cover your new module functionality. Once your module is ready, you can install it locally using `mvn clean install` to make the module accessible from Studio. ## Using the Custom Properties Provider in a Mule Application To use the custom properties provider: 1. Create an application in Studio. 2. Add the dependency to you new module: 1. Open the `pom.xml` file. 2. Within the `` tag, add a new dependency using the GAV that you put in your module. 3. Remember to add `mule-plugin` because it is a Mule module. 4. Save your changes. Now, open the application XML file and in the **Global Elements** tab and click **Create**. Under **Connector Configuration**, you should see an option for selecting the configuration from your custom module, for example: ![Screen for selecting a type of global configuration element with a search function](/mulesoft/current/en-us/mule-runtime/4.12/_images/custom-configuration-provider.png) You can now configure your new component and start using properties with the prefix defined in your module. ## Using Custom Configuration Properties Provider versus a Connector For static properties, use the properties provider approach, because static properties don’t change during runtime. If your properties might change during runtime, create a connector that can provide the value as one of its operations. > [!NOTE] Although the [Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) is used to > implement a custom configuration properties provider, you can’t use > [ConnectionProviders](https://docs.mulesoft.com/mule-sdk/latest/connections) to connect to external sources. This is > because `ConnectionProviders` are managed by Mule runtime and are initialized at a later stage, > after the static properties are resolved. Consequently, connectivity testing isn’t supported for > custom properties providers. --- product: Mule Runtime version: 4.3 keywords: anypoint, studio, on premises, on premise, properties, custom configuration properties, configuration properties provider --- # Custom Configuration Properties Provider > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can use the Mule SDK and Mule API to create a custom configuration properties provider that enables an app to discover configuration properties values. ## Mule API The main interfaces of the API are: - `ConfigurationPropertiesProviderFactory` This interface is used to discover custom implementations of configuration properties providers. When Mule runtime engine (Mule) finds a configuration element that matches the namespace and name provided by the `getSupportedComponentIdentifier()` method, Mule requests the factory to create a `ConfigurationPropertiesProvider` using the configuration you define with the `createProvider(..)` method. Mule discovers instances of `ConfigurationPropertiesProviderFactory` by using SPI. - `ConfigurationPropertiesProvider` When Mule finds a configuration property, Mule invokes this interface to resolve the property’s value. ## Example: Secure Configuration Properties Provider The Security module uses the API to implement `ConfigurationPropertiesProviderFactory`: ```java import static org.mule.runtime.api.component.ComponentIdentifier.builder; public class SecureConfigurationPropertiesProviderFactory implements ConfigurationPropertiesProviderFactory { public static final String EXTENSION_NAMESPACE = "secure-properties"; public static final String SECURE_CONFIGURATION_PROPERTIES_ELEMENT = "config"; public static final ComponentIdentifier SECURE_CONFIGURATION_PROPERTIES = builder().namespace(EXTENSION_NAMESPACE).name(SECURE_CONFIGURATION_PROPERTIES_ELEMENT).build(); ... @Override public ComponentIdentifier getSupportedComponentIdentifier() { return SECURE_CONFIGURATION_PROPERTIES; } @Override public SecureConfigurationPropertiesProvider createProvider(ConfigurationParameters parameters, ResourceProvider externalResourceProvider) { String file = parameters.getStringParameter("file"); .. String key = parameters.getStringParameter("key"); ... return new SecureConfigurationPropertiesProvider(..); } } ``` The `ComponentIdentifier` returned by `getSupportedComponentIdentifier()` matches against the following configuration component: ```xml ``` When processing the configuration, Mule finds the `secure-properties:config` component, and then invokes the `SecureConfigurationPropertiesProvider.createProvider(..)` method to create an instance of `SecureConfigurationPropertiesProvider` to resolve configuration properties. ```java public class SecureConfigurationPropertiesProvider extends DefaultConfigurationPropertiesProvider { private final static String SECURE_PREFIX = "secure::"; private final static Pattern SECURE_PATTERN = Pattern.compile("\\$\\{" + SECURE_PREFIX + "[^}]*}"); private final EncryptionAlgorithm algorithm; private final EncryptionMode mode; private final boolean fileLevelEncryption; private final SecurePropertyPlaceholderModule securePropertyPlaceholderModule = new SecurePropertyPlaceholderModule(); public SecureConfigurationPropertiesProvider(ResourceProvider resourceProvider, String file, EncryptionAlgorithm algorithm, String key, EncryptionMode mode, String encoding, boolean fileLevelEncryption) { ... } @Override public Optional getConfigurationProperty(String configurationAttributeKey) { if (configurationAttributeKey.startsWith(SECURE_PREFIX)) { String effectiveKey = configurationAttributeKey.substring(SECURE_PREFIX.length()); ConfigurationProperty originalConfigurationProperty = configurationAttributes.get(effectiveKey); if (originalConfigurationProperty == null) { return empty(); } String originalString = ((String) originalConfigurationProperty.getRawValue()); String encryptedValue = originalString.substring(originalConfigurationProperty.getKey().length() + 1, originalString.length() - algorithm.name().length() - mode.name().length() - 2); final String decryptedValue = resolveInnerProperties(securePropertyPlaceholderModule.convertPropertyValue(encryptedValue)); return of(new ConfigurationProperty() { @Override public Object getSource() { return originalConfigurationProperty.getSource(); } @Override public Object getRawValue() { return decryptedValue; } @Override public String getKey() { return originalConfigurationProperty.getKey(); } }); } else { return empty(); } } @Override public String getDescription() { ComponentLocation location = (ComponentLocation) getAnnotation(LOCATION_KEY); return format(" - file: %s, line number: %s", fileLocation, location.getFileName().orElse(UNKNOWN), location.getLineInFile().map(String::valueOf).orElse("unknown")); } ... } ``` Define a prefix (with the format `PREFIX::`) that is unique to this resolver. The prefix enables the user to target a specific resolver. This is implemented in `SecureConfigurationPropertiesProvider` by using the prefix defined by `SECURE_PREFIX`. In the configuration, the prefix must be used in the following way: ```xml ``` Notice how the `value` attribute of `set-payload` is using the resolver for secure properties by using the `secure::` prefix. ## Example: Mule SDK Module To create a configuration element that enables the custom configuration properties provider within Studio, you must create a Mule SDK module. You can download or checkout the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example), which contains all the infrastructure code to get started implementing your custom configuration properties resolver extension. The sample project is a Mule SDK module. See [Getting started with the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started) for additional information. ### Customizing the Module to Access Your Custom Properties Source Follow these steps to customize the Mule SDK Module: 1. Import the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example) into your favorite IDE. 2. Open the `pom.xml` file: 1. Define the GAV (`groupId`, `artifactId`, and `version`) of your module. 2. Define the `name` of your module. 3. Review the minimum Mule version you want your properties provider to require. This example is compatible with Mule 4.1.1 and later to cover all possible scenarios. See [Choosing the SDK Version](https://docs.mulesoft.com/mule-sdk/latest/choosing-version). 3. Change the package name (`com.my.company.custom.provider.api`) of your code. 4. Open `resources/META-INF/services/org.mule.runtime.config.api.dsl.model.properties.ConfigurationPropertiesProviderFactory`, and change the content to match the package name you changed previously. 5. Open the `CustomConfigurationPropertiesExtension` class: 1. Change the `EXTENSION_NAME` constant to the name of your module. 2. Change the `vendor` method parameter on the `@Extension` annotation to your company name. 3. Customize the section at the end to define the parameters that can be configured in the `config` element of your module. 6. Open the `CustomConfigurationPropertiesProviderFactory` class: 1. Change the `CUSTOM_PROPERTIES_PREFIX` value to a meaningful prefix for the configuration properties that your module must resolve. 2. Change the class implementation to look up the properties from your custom source. 7. Update the MUnit test cases in `test/munit` with more test cases to cover your new module functionality. Once your module is ready, you can install it locally using `mvn clean install` to make the module accessible from Studio. ## Using the Custom Properties Provider in a Mule Application To use the custom properties provider: 1. Create an application in Studio. 2. Add the dependency to you new module: 1. Open the `pom.xml` file. 2. Within the `` tag, add a new dependency using the GAV that you put in your module. 3. Remember to add `mule-plugin` because it is a Mule module. 4. Save your changes. Now, open the application XML file and in the **Global Elements** tab and click **Create**. Under **Connector Configuration**, you should see an option for selecting the configuration from your custom module, for example: ![custom configuration provider](/mulesoft/current/en-us/mule-runtime/4.3/_images/custom-configuration-provider.png) You can now configure your new component and start using properties with the prefix defined in your module. ## Using Custom Configuration Properties Provider versus a Connector For static properties, use the properties provider approach, because static properties don’t change during runtime. If your properties might change during runtime, create a connector that can provide the value as one of its operations. > [!NOTE] Although the [Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) is used to > implement a custom configuration properties provider, you can’t use > [ConnectionProviders](https://docs.mulesoft.com/mule-sdk/latest/connections) to connect to external sources. This is > because `ConnectionProviders` are managed by Mule runtime and are initialized at a later stage, > after the static properties are resolved. Consequently, connectivity testing isn’t supported for > custom properties providers. --- product: Mule Runtime version: 4.4 keywords: anypoint, studio, on premises, on premise, properties, custom configuration properties, configuration properties provider --- # Custom Configuration Properties Provider > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can use the Mule SDK and Mule API to create a custom configuration properties provider that enables an app to discover configuration properties values. ## Mule API The main interfaces of the API are: - `ConfigurationPropertiesProviderFactory` This interface is used to discover custom implementations of configuration properties providers. When Mule runtime engine (Mule) finds a configuration element that matches the namespace and name provided by the `getSupportedComponentIdentifier()` method, Mule requests the factory to create a `ConfigurationPropertiesProvider` using the configuration you define with the `createProvider(..)` method. Mule discovers instances of `ConfigurationPropertiesProviderFactory` by using SPI. - `ConfigurationPropertiesProvider` When Mule finds a configuration property, Mule invokes this interface to resolve the property’s value. ## Example: Secure Configuration Properties Provider The Security module uses the API to implement `ConfigurationPropertiesProviderFactory`: ```java import static org.mule.runtime.api.component.ComponentIdentifier.builder; public class SecureConfigurationPropertiesProviderFactory implements ConfigurationPropertiesProviderFactory { public static final String EXTENSION_NAMESPACE = "secure-properties"; public static final String SECURE_CONFIGURATION_PROPERTIES_ELEMENT = "config"; public static final ComponentIdentifier SECURE_CONFIGURATION_PROPERTIES = builder().namespace(EXTENSION_NAMESPACE).name(SECURE_CONFIGURATION_PROPERTIES_ELEMENT).build(); ... @Override public ComponentIdentifier getSupportedComponentIdentifier() { return SECURE_CONFIGURATION_PROPERTIES; } @Override public SecureConfigurationPropertiesProvider createProvider(ConfigurationParameters parameters, ResourceProvider externalResourceProvider) { String file = parameters.getStringParameter("file"); .. String key = parameters.getStringParameter("key"); ... return new SecureConfigurationPropertiesProvider(..); } } ``` The `ComponentIdentifier` returned by `getSupportedComponentIdentifier()` matches against the following configuration component: ```xml ``` When processing the configuration, Mule finds the `secure-properties:config` component, and then invokes the `SecureConfigurationPropertiesProvider.createProvider(..)` method to create an instance of `SecureConfigurationPropertiesProvider` to resolve configuration properties. ```java public class SecureConfigurationPropertiesProvider extends DefaultConfigurationPropertiesProvider { private final static String SECURE_PREFIX = "secure::"; private final static Pattern SECURE_PATTERN = Pattern.compile("\\$\\{" + SECURE_PREFIX + "[^}]*}"); private final EncryptionAlgorithm algorithm; private final EncryptionMode mode; private final boolean fileLevelEncryption; private final SecurePropertyPlaceholderModule securePropertyPlaceholderModule = new SecurePropertyPlaceholderModule(); public SecureConfigurationPropertiesProvider(ResourceProvider resourceProvider, String file, EncryptionAlgorithm algorithm, String key, EncryptionMode mode, String encoding, boolean fileLevelEncryption) { ... } @Override public Optional getConfigurationProperty(String configurationAttributeKey) { if (configurationAttributeKey.startsWith(SECURE_PREFIX)) { String effectiveKey = configurationAttributeKey.substring(SECURE_PREFIX.length()); ConfigurationProperty originalConfigurationProperty = configurationAttributes.get(effectiveKey); if (originalConfigurationProperty == null) { return empty(); } String originalString = ((String) originalConfigurationProperty.getRawValue()); String encryptedValue = originalString.substring(originalConfigurationProperty.getKey().length() + 1, originalString.length() - algorithm.name().length() - mode.name().length() - 2); final String decryptedValue = resolveInnerProperties(securePropertyPlaceholderModule.convertPropertyValue(encryptedValue)); return of(new ConfigurationProperty() { @Override public Object getSource() { return originalConfigurationProperty.getSource(); } @Override public Object getRawValue() { return decryptedValue; } @Override public String getKey() { return originalConfigurationProperty.getKey(); } }); } else { return empty(); } } @Override public String getDescription() { ComponentLocation location = (ComponentLocation) getAnnotation(LOCATION_KEY); return format(" - file: %s, line number: %s", fileLocation, location.getFileName().orElse(UNKNOWN), location.getLineInFile().map(String::valueOf).orElse("unknown")); } ... } ``` Define a prefix (with the format `PREFIX::`) that is unique to this resolver. The prefix enables the user to target a specific resolver. This is implemented in `SecureConfigurationPropertiesProvider` by using the prefix defined by `SECURE_PREFIX`. In the configuration, the prefix must be used in the following way: ```xml ``` Notice how the `value` attribute of `set-payload` is using the resolver for secure properties by using the `secure::` prefix. ## Example: Mule SDK Module To create a configuration element that enables the custom configuration properties provider within Studio, you must create a Mule SDK module. You can download or checkout the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example), which contains all the infrastructure code to get started implementing your custom configuration properties resolver extension. The sample project is a Mule SDK module. See [Getting started with the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started) for additional information. ### Customizing the Module to Access Your Custom Properties Source Follow these steps to customize the Mule SDK Module: 1. Import the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example) into your favorite IDE. 2. Open the `pom.xml` file: 1. Define the GAV (`groupId`, `artifactId`, and `version`) of your module. 2. Define the `name` of your module. 3. Review the minimum Mule version you want your properties provider to require. This example is compatible with Mule 4.1.1 and later to cover all possible scenarios. See [Choosing the SDK Version](https://docs.mulesoft.com/mule-sdk/latest/choosing-version). 3. Change the package name (`com.my.company.custom.provider.api`) of your code. 4. Open `resources/META-INF/services/org.mule.runtime.config.api.dsl.model.properties.ConfigurationPropertiesProviderFactory`, and change the content to match the package name you changed previously. 5. Open the `CustomConfigurationPropertiesExtension` class: 1. Change the `EXTENSION_NAME` constant to the name of your module. 2. Change the `vendor` method parameter on the `@Extension` annotation to your company name. 3. Customize the section at the end to define the parameters that can be configured in the `config` element of your module. 6. Open the `CustomConfigurationPropertiesProviderFactory` class: 1. Change the `CUSTOM_PROPERTIES_PREFIX` value to a meaningful prefix for the configuration properties that your module must resolve. 2. Change the class implementation to look up the properties from your custom source. 7. Update the MUnit test cases in `test/munit` with more test cases to cover your new module functionality. Once your module is ready, you can install it locally using `mvn clean install` to make the module accessible from Studio. ## Using the Custom Properties Provider in a Mule Application To use the custom properties provider: 1. Create an application in Studio. 2. Add the dependency to you new module: 1. Open the `pom.xml` file. 2. Within the `` tag, add a new dependency using the GAV that you put in your module. 3. Remember to add `mule-plugin` because it is a Mule module. 4. Save your changes. Now, open the application XML file and in the **Global Elements** tab and click **Create**. Under **Connector Configuration**, you should see an option for selecting the configuration from your custom module, for example: ![custom configuration provider](/mulesoft/current/en-us/mule-runtime/4.4/_images/custom-configuration-provider.png) You can now configure your new component and start using properties with the prefix defined in your module. ## Using Custom Configuration Properties Provider versus a Connector For static properties, use the properties provider approach, because static properties don’t change during runtime. If your properties might change during runtime, create a connector that can provide the value as one of its operations. > [!NOTE] Although the [Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) is used to > implement a custom configuration properties provider, you can’t use > [ConnectionProviders](https://docs.mulesoft.com/mule-sdk/latest/connections) to connect to external sources. This is > because `ConnectionProviders` are managed by Mule runtime and are initialized at a later stage, > after the static properties are resolved. Consequently, connectivity testing isn’t supported for > custom properties providers. --- product: Mule Runtime version: 4.6 keywords: anypoint, studio, on premises, on premise, properties, custom configuration properties, configuration properties provider --- # Custom Configuration Properties Provider > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can use the Mule SDK and Mule API to create a custom configuration properties provider that enables an app to discover configuration properties values. ## Mule API The main interfaces of the API are: - `ConfigurationPropertiesProviderFactory` This interface is used to discover custom implementations of configuration properties providers. When Mule runtime engine (Mule) finds a configuration element that matches the namespace and name provided by the `getSupportedComponentIdentifier()` method, Mule requests the factory to create a `ConfigurationPropertiesProvider` using the configuration you define with the `createProvider(..)` method. Mule discovers instances of `ConfigurationPropertiesProviderFactory` by using SPI. - `ConfigurationPropertiesProvider` When Mule finds a configuration property, Mule invokes this interface to resolve the property’s value. ## Example: Secure Configuration Properties Provider The Security module uses the API to implement `ConfigurationPropertiesProviderFactory`: ```java import static org.mule.runtime.api.component.ComponentIdentifier.builder; public class SecureConfigurationPropertiesProviderFactory implements ConfigurationPropertiesProviderFactory { public static final String EXTENSION_NAMESPACE = "secure-properties"; public static final String SECURE_CONFIGURATION_PROPERTIES_ELEMENT = "config"; public static final ComponentIdentifier SECURE_CONFIGURATION_PROPERTIES = builder().namespace(EXTENSION_NAMESPACE).name(SECURE_CONFIGURATION_PROPERTIES_ELEMENT).build(); ... @Override public ComponentIdentifier getSupportedComponentIdentifier() { return SECURE_CONFIGURATION_PROPERTIES; } @Override public SecureConfigurationPropertiesProvider createProvider(ConfigurationParameters parameters, ResourceProvider externalResourceProvider) { String file = parameters.getStringParameter("file"); .. String key = parameters.getStringParameter("key"); ... return new SecureConfigurationPropertiesProvider(..); } } ``` The `ComponentIdentifier` returned by `getSupportedComponentIdentifier()` matches against the following configuration component: ```xml ``` When processing the configuration, Mule finds the `secure-properties:config` component, and then invokes the `SecureConfigurationPropertiesProvider.createProvider(..)` method to create an instance of `SecureConfigurationPropertiesProvider` to resolve configuration properties. ```java public class SecureConfigurationPropertiesProvider extends DefaultConfigurationPropertiesProvider { private final static String SECURE_PREFIX = "secure::"; private final static Pattern SECURE_PATTERN = Pattern.compile("\\$\\{" + SECURE_PREFIX + "[^}]*}"); private final EncryptionAlgorithm algorithm; private final EncryptionMode mode; private final boolean fileLevelEncryption; private final SecurePropertyPlaceholderModule securePropertyPlaceholderModule = new SecurePropertyPlaceholderModule(); public SecureConfigurationPropertiesProvider(ResourceProvider resourceProvider, String file, EncryptionAlgorithm algorithm, String key, EncryptionMode mode, String encoding, boolean fileLevelEncryption) { ... } @Override public Optional getConfigurationProperty(String configurationAttributeKey) { if (configurationAttributeKey.startsWith(SECURE_PREFIX)) { String effectiveKey = configurationAttributeKey.substring(SECURE_PREFIX.length()); ConfigurationProperty originalConfigurationProperty = configurationAttributes.get(effectiveKey); if (originalConfigurationProperty == null) { return empty(); } String originalString = ((String) originalConfigurationProperty.getRawValue()); String encryptedValue = originalString.substring(originalConfigurationProperty.getKey().length() + 1, originalString.length() - algorithm.name().length() - mode.name().length() - 2); final String decryptedValue = resolveInnerProperties(securePropertyPlaceholderModule.convertPropertyValue(encryptedValue)); return of(new ConfigurationProperty() { @Override public Object getSource() { return originalConfigurationProperty.getSource(); } @Override public Object getRawValue() { return decryptedValue; } @Override public String getKey() { return originalConfigurationProperty.getKey(); } }); } else { return empty(); } } @Override public String getDescription() { ComponentLocation location = (ComponentLocation) getAnnotation(LOCATION_KEY); return format(" - file: %s, line number: %s", fileLocation, location.getFileName().orElse(UNKNOWN), location.getLineInFile().map(String::valueOf).orElse("unknown")); } ... } ``` Define a prefix (with the format `PREFIX::`) that is unique to this resolver. The prefix enables the user to target a specific resolver. This is implemented in `SecureConfigurationPropertiesProvider` by using the prefix defined by `SECURE_PREFIX`. In the configuration, the prefix must be used in the following way: ```xml ``` Notice how the `value` attribute of `set-payload` is using the resolver for secure properties by using the `secure::` prefix. ## Example: Mule SDK Module To create a configuration element that enables the custom configuration properties provider within Studio, you must create a Mule SDK module. You can download or checkout the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example), which contains all the infrastructure code to get started implementing your custom configuration properties resolver extension. The sample project is a Mule SDK module. See [Getting started with the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started) for additional information. ### Customizing the Module to Access Your Custom Properties Source Follow these steps to customize the Mule SDK Module: 1. Import the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example) into your favorite IDE. 2. Open the `pom.xml` file: 1. Define the GAV (`groupId`, `artifactId`, and `version`) of your module. 2. Define the `name` of your module. 3. Review the minimum Mule version you want your properties provider to require. This example is compatible with Mule 4.1.1 and later to cover all possible scenarios. See [Choosing the SDK Version](https://docs.mulesoft.com/mule-sdk/latest/choosing-version). 3. Change the package name (`com.my.company.custom.provider.api`) of your code. 4. Open `resources/META-INF/services/org.mule.runtime.config.api.dsl.model.properties.ConfigurationPropertiesProviderFactory`, and change the content to match the package name you changed previously. 5. Open the `CustomConfigurationPropertiesExtension` class: 1. Change the `EXTENSION_NAME` constant to the name of your module. 2. Change the `vendor` method parameter on the `@Extension` annotation to your company name. 3. Customize the section at the end to define the parameters that can be configured in the `config` element of your module. 6. Open the `CustomConfigurationPropertiesProviderFactory` class: 1. Change the `CUSTOM_PROPERTIES_PREFIX` value to a meaningful prefix for the configuration properties that your module must resolve. 2. Change the class implementation to look up the properties from your custom source. 7. Update the MUnit test cases in `test/munit` with more test cases to cover your new module functionality. Once your module is ready, you can install it locally using `mvn clean install` to make the module accessible from Studio. ## Using the Custom Properties Provider in a Mule Application To use the custom properties provider: 1. Create an application in Studio. 2. Add the dependency to you new module: 1. Open the `pom.xml` file. 2. Within the `` tag, add a new dependency using the GAV that you put in your module. 3. Remember to add `mule-plugin` because it is a Mule module. 4. Save your changes. Now, open the application XML file and in the **Global Elements** tab and click **Create**. Under **Connector Configuration**, you should see an option for selecting the configuration from your custom module, for example: ![custom configuration provider](/mulesoft/current/en-us/mule-runtime/4.6/_images/custom-configuration-provider.png) You can now configure your new component and start using properties with the prefix defined in your module. ## Using Custom Configuration Properties Provider versus a Connector For static properties, use the properties provider approach, because static properties don’t change during runtime. If your properties might change during runtime, create a connector that can provide the value as one of its operations. > [!NOTE] Although the [Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) is used to > implement a custom configuration properties provider, you can’t use > [ConnectionProviders](https://docs.mulesoft.com/mule-sdk/latest/connections) to connect to external sources. This is > because `ConnectionProviders` are managed by Mule runtime and are initialized at a later stage, > after the static properties are resolved. Consequently, connectivity testing isn’t supported for > custom properties providers. --- product: Mule Runtime version: 4.9 keywords: anypoint, studio, on premises, on premise, properties, custom configuration properties, configuration properties provider --- # Custom Configuration Properties Provider > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can use the Mule SDK and Mule API to create a custom configuration properties provider that enables an app to discover configuration properties values. ## Mule API The main interfaces of the API are: - `ConfigurationPropertiesProviderFactory` This interface is used to discover custom implementations of configuration properties providers. When Mule runtime engine (Mule) finds a configuration element that matches the namespace and name provided by the `getSupportedComponentIdentifier()` method, Mule requests the factory to create a `ConfigurationPropertiesProvider` using the configuration you define with the `createProvider(..)` method. Mule discovers instances of `ConfigurationPropertiesProviderFactory` by using SPI. - `ConfigurationPropertiesProvider` When Mule finds a configuration property, Mule invokes this interface to resolve the property’s value. ## Example: Secure Configuration Properties Provider The Security module uses the API to implement `ConfigurationPropertiesProviderFactory`: ```java import static org.mule.runtime.api.component.ComponentIdentifier.builder; import org.mule.runtime.properties.api.ConfigurationPropertiesProviderFactory; public class SecureConfigurationPropertiesProviderFactory implements ConfigurationPropertiesProviderFactory { public static final String EXTENSION_NAMESPACE = "secure-properties"; public static final String SECURE_CONFIGURATION_PROPERTIES_ELEMENT = "config"; public static final ComponentIdentifier SECURE_CONFIGURATION_PROPERTIES = builder().namespace(EXTENSION_NAMESPACE).name(SECURE_CONFIGURATION_PROPERTIES_ELEMENT).build(); ... @Override public ComponentIdentifier getSupportedComponentIdentifier() { return SECURE_CONFIGURATION_PROPERTIES; } @Override public SecureConfigurationPropertiesProvider createProvider(ConfigurationParameters parameters, ResourceProvider externalResourceProvider) { String file = parameters.getStringParameter("file"); .. String key = parameters.getStringParameter("key"); ... return new SecureConfigurationPropertiesProvider(..); } } ``` The `ComponentIdentifier` returned by `getSupportedComponentIdentifier()` matches against the following configuration component: ```xml ``` When processing the configuration, Mule finds the `secure-properties:config` component, and then invokes the `SecureConfigurationPropertiesProvider.createProvider(..)` method to create an instance of `SecureConfigurationPropertiesProvider` to resolve configuration properties. ```java public class SecureConfigurationPropertiesProvider extends DefaultConfigurationPropertiesProvider { private final static String SECURE_PREFIX = "secure::"; private final static Pattern SECURE_PATTERN = Pattern.compile("\\$\\{" + SECURE_PREFIX + "[^}]*}"); private final EncryptionAlgorithm algorithm; private final EncryptionMode mode; private final boolean fileLevelEncryption; private final SecurePropertyPlaceholderModule securePropertyPlaceholderModule = new SecurePropertyPlaceholderModule(); public SecureConfigurationPropertiesProvider(ResourceProvider resourceProvider, String file, EncryptionAlgorithm algorithm, String key, EncryptionMode mode, String encoding, boolean fileLevelEncryption) { ... } @Override public Optional getConfigurationProperty(String configurationAttributeKey) { if (configurationAttributeKey.startsWith(SECURE_PREFIX)) { String effectiveKey = configurationAttributeKey.substring(SECURE_PREFIX.length()); ConfigurationProperty originalConfigurationProperty = configurationAttributes.get(effectiveKey); if (originalConfigurationProperty == null) { return empty(); } String originalString = ((String) originalConfigurationProperty.getRawValue()); String encryptedValue = originalString.substring(originalConfigurationProperty.getKey().length() + 1, originalString.length() - algorithm.name().length() - mode.name().length() - 2); final String decryptedValue = resolveInnerProperties(securePropertyPlaceholderModule.convertPropertyValue(encryptedValue)); return of(new ConfigurationProperty() { @Override public Object getSource() { return originalConfigurationProperty.getSource(); } @Override public Object getRawValue() { return decryptedValue; } @Override public String getKey() { return originalConfigurationProperty.getKey(); } }); } else { return empty(); } } @Override public String getDescription() { ComponentLocation location = (ComponentLocation) getAnnotation(LOCATION_KEY); return format(" - file: %s, line number: %s", fileLocation, location.getFileName().orElse(UNKNOWN), location.getLineInFile().map(String::valueOf).orElse("unknown")); } ... } ``` Define a prefix (with the format `PREFIX::`) that is unique to this resolver. The prefix enables the user to target a specific resolver. This is implemented in `SecureConfigurationPropertiesProvider` by using the prefix defined by `SECURE_PREFIX`. In the configuration, the prefix must be used in the following way: ```xml ``` Notice how the `value` attribute of `set-payload` is using the resolver for secure properties by using the `secure::` prefix. ## Example: Mule SDK Module To create a configuration element that enables the custom configuration properties provider within Studio, you must create a Mule SDK module. You can download or checkout the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example), which contains all the infrastructure code to get started implementing your custom configuration properties resolver extension. The sample project is a Mule SDK module. See [Getting started with the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started) for additional information. ### Customizing the Module to Access Your Custom Properties Source Follow these steps to customize the Mule SDK Module: 1. Import the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example) into your favorite IDE. 2. Open the `pom.xml` file: 1. Define the GAV (`groupId`, `artifactId`, and `version`) of your module. 2. Define the `name` of your module. 3. Review the minimum Mule version you want your properties provider to require. This example is compatible with Mule 4.1.1 and later to cover all possible scenarios. See [Choosing the SDK Version](https://docs.mulesoft.com/mule-sdk/latest/choosing-version). 3. Change the package name (`com.my.company.custom.provider.api`) of your code. 4. Open `resources/META-INF/services/org.mule.runtime.config.api.dsl.model.properties.ConfigurationPropertiesProviderFactory`, and change the content to match the package name you changed previously. 5. Open the `CustomConfigurationPropertiesExtension` class: 1. Change the `EXTENSION_NAME` constant to the name of your module. 2. Change the `vendor` method parameter on the `@Extension` annotation to your company name. 3. Customize the section at the end to define the parameters that can be configured in the `config` element of your module. 6. Open the `CustomConfigurationPropertiesProviderFactory` class: 1. Change the `CUSTOM_PROPERTIES_PREFIX` value to a meaningful prefix for the configuration properties that your module must resolve. 2. Change the class implementation to look up the properties from your custom source. 7. Update the MUnit test cases in `test/munit` with more test cases to cover your new module functionality. Once your module is ready, you can install it locally using `mvn clean install` to make the module accessible from Studio. ## Using the Custom Properties Provider in a Mule Application To use the custom properties provider: 1. Create an application in Studio. 2. Add the dependency to you new module: 1. Open the `pom.xml` file. 2. Within the `` tag, add a new dependency using the GAV that you put in your module. 3. Remember to add `mule-plugin` because it is a Mule module. 4. Save your changes. Now, open the application XML file and in the **Global Elements** tab and click **Create**. Under **Connector Configuration**, you should see an option for selecting the configuration from your custom module, for example: ![Screen for selecting a type of global configuration element with a search function](/mulesoft/current/en-us/mule-runtime/4.9/_images/custom-configuration-provider.png) You can now configure your new component and start using properties with the prefix defined in your module. ## Using Custom Configuration Properties Provider versus a Connector For static properties, use the properties provider approach, because static properties don’t change during runtime. If your properties might change during runtime, create a connector that can provide the value as one of its operations. > [!NOTE] Although the [Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) is used to > implement a custom configuration properties provider, you can’t use > [ConnectionProviders](https://docs.mulesoft.com/mule-sdk/latest/connections) to connect to external sources. This is > because `ConnectionProviders` are managed by Mule runtime and are initialized at a later stage, > after the static properties are resolved. Consequently, connectivity testing isn’t supported for > custom properties providers. --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: anypoint, studio, on premises, on premise, properties, custom configuration properties, configuration properties provider --- # Custom Configuration Properties Provider > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can use the Mule SDK and Mule API to create a custom configuration properties provider that enables an app to discover configuration properties values. ## Mule API The main interfaces of the API are: - `ConfigurationPropertiesProviderFactory` This interface is used to discover custom implementations of configuration properties providers. When Mule runtime engine (Mule) finds a configuration element that matches the namespace and name provided by the `getSupportedComponentIdentifier()` method, Mule requests the factory to create a `ConfigurationPropertiesProvider` using the configuration you define with the `createProvider(..)` method. Mule discovers instances of `ConfigurationPropertiesProviderFactory` by using SPI. - `ConfigurationPropertiesProvider` When Mule finds a configuration property, Mule invokes this interface to resolve the property’s value. ## Example: Secure Configuration Properties Provider The Security module uses the API to implement `ConfigurationPropertiesProviderFactory`: ```java import static org.mule.runtime.api.component.ComponentIdentifier.builder; import org.mule.runtime.properties.api.ConfigurationPropertiesProviderFactory; public class SecureConfigurationPropertiesProviderFactory implements ConfigurationPropertiesProviderFactory { public static final String EXTENSION_NAMESPACE = "secure-properties"; public static final String SECURE_CONFIGURATION_PROPERTIES_ELEMENT = "config"; public static final ComponentIdentifier SECURE_CONFIGURATION_PROPERTIES = builder().namespace(EXTENSION_NAMESPACE).name(SECURE_CONFIGURATION_PROPERTIES_ELEMENT).build(); ... @Override public ComponentIdentifier getSupportedComponentIdentifier() { return SECURE_CONFIGURATION_PROPERTIES; } @Override public SecureConfigurationPropertiesProvider createProvider(ConfigurationParameters parameters, ResourceProvider externalResourceProvider) { String file = parameters.getStringParameter("file"); .. String key = parameters.getStringParameter("key"); ... return new SecureConfigurationPropertiesProvider(..); } } ``` The `ComponentIdentifier` returned by `getSupportedComponentIdentifier()` matches against the following configuration component: ```xml ``` When processing the configuration, Mule finds the `secure-properties:config` component, and then invokes the `SecureConfigurationPropertiesProvider.createProvider(..)` method to create an instance of `SecureConfigurationPropertiesProvider` to resolve configuration properties. ```java public class SecureConfigurationPropertiesProvider extends DefaultConfigurationPropertiesProvider { private final static String SECURE_PREFIX = "secure::"; private final static Pattern SECURE_PATTERN = Pattern.compile("\\$\\{" + SECURE_PREFIX + "[^}]*}"); private final EncryptionAlgorithm algorithm; private final EncryptionMode mode; private final boolean fileLevelEncryption; private final SecurePropertyPlaceholderModule securePropertyPlaceholderModule = new SecurePropertyPlaceholderModule(); public SecureConfigurationPropertiesProvider(ResourceProvider resourceProvider, String file, EncryptionAlgorithm algorithm, String key, EncryptionMode mode, String encoding, boolean fileLevelEncryption) { ... } @Override public Optional getConfigurationProperty(String configurationAttributeKey) { if (configurationAttributeKey.startsWith(SECURE_PREFIX)) { String effectiveKey = configurationAttributeKey.substring(SECURE_PREFIX.length()); ConfigurationProperty originalConfigurationProperty = configurationAttributes.get(effectiveKey); if (originalConfigurationProperty == null) { return empty(); } String originalString = ((String) originalConfigurationProperty.getRawValue()); String encryptedValue = originalString.substring(originalConfigurationProperty.getKey().length() + 1, originalString.length() - algorithm.name().length() - mode.name().length() - 2); final String decryptedValue = resolveInnerProperties(securePropertyPlaceholderModule.convertPropertyValue(encryptedValue)); return of(new ConfigurationProperty() { @Override public Object getSource() { return originalConfigurationProperty.getSource(); } @Override public Object getRawValue() { return decryptedValue; } @Override public String getKey() { return originalConfigurationProperty.getKey(); } }); } else { return empty(); } } @Override public String getDescription() { ComponentLocation location = (ComponentLocation) getAnnotation(LOCATION_KEY); return format(" - file: %s, line number: %s", fileLocation, location.getFileName().orElse(UNKNOWN), location.getLineInFile().map(String::valueOf).orElse("unknown")); } ... } ``` Define a prefix (with the format `PREFIX::`) that is unique to this resolver. The prefix enables the user to target a specific resolver. This is implemented in `SecureConfigurationPropertiesProvider` by using the prefix defined by `SECURE_PREFIX`. In the configuration, the prefix must be used in the following way: ```xml ``` Notice how the `value` attribute of `set-payload` is using the resolver for secure properties by using the `secure::` prefix. ## Example: Mule SDK Module To create a configuration element that enables the custom configuration properties provider within Studio, you must create a Mule SDK module. You can download or checkout the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example), which contains all the infrastructure code to get started implementing your custom configuration properties resolver extension. The sample project is a Mule SDK module. See [Getting started with the Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started) for additional information. ### Customizing the Module to Access Your Custom Properties Source Follow these steps to customize the Mule SDK Module: 1. Import the [sample project](https://github.com/mulesoft/mule-custom-properties-providers-module-example) into your favorite IDE. 2. Open the `pom.xml` file: 1. Define the GAV (`groupId`, `artifactId`, and `version`) of your module. 2. Define the `name` of your module. 3. Review the minimum Mule version you want your properties provider to require. This example is compatible with Mule 4.1.1 and later to cover all possible scenarios. See [Choosing the SDK Version](https://docs.mulesoft.com/mule-sdk/latest/choosing-version). 3. Change the package name (`com.my.company.custom.provider.api`) of your code. 4. Open `resources/META-INF/services/org.mule.runtime.config.api.dsl.model.properties.ConfigurationPropertiesProviderFactory`, and change the content to match the package name you changed previously. 5. Open the `CustomConfigurationPropertiesExtension` class: 1. Change the `EXTENSION_NAME` constant to the name of your module. 2. Change the `vendor` method parameter on the `@Extension` annotation to your company name. 3. Customize the section at the end to define the parameters that can be configured in the `config` element of your module. 6. Open the `CustomConfigurationPropertiesProviderFactory` class: 1. Change the `CUSTOM_PROPERTIES_PREFIX` value to a meaningful prefix for the configuration properties that your module must resolve. 2. Change the class implementation to look up the properties from your custom source. 7. Update the MUnit test cases in `test/munit` with more test cases to cover your new module functionality. Once your module is ready, you can install it locally using `mvn clean install` to make the module accessible from Studio. ## Using the Custom Properties Provider in a Mule Application To use the custom properties provider: 1. Create an application in Studio. 2. Add the dependency to you new module: 1. Open the `pom.xml` file. 2. Within the `` tag, add a new dependency using the GAV that you put in your module. 3. Remember to add `mule-plugin` because it is a Mule module. 4. Save your changes. Now, open the application XML file and in the **Global Elements** tab and click **Create**. Under **Connector Configuration**, you should see an option for selecting the configuration from your custom module, for example: ![Screen for selecting a type of global configuration element with a search function](/mulesoft/current/en-us/mule-runtime/latest/_images/custom-configuration-provider.png) You can now configure your new component and start using properties with the prefix defined in your module. ## Using Custom Configuration Properties Provider versus a Connector For static properties, use the properties provider approach, because static properties don’t change during runtime. If your properties might change during runtime, create a connector that can provide the value as one of its operations. > [!NOTE] Although the [Mule SDK for Java](https://docs.mulesoft.com/mule-sdk/latest/getting-started) is used to > implement a custom configuration properties provider, you can’t use > [ConnectionProviders](https://docs.mulesoft.com/mule-sdk/latest/connections) to connect to external sources. This is > because `ConnectionProviders` are managed by Mule runtime and are initialized at a later stage, > after the static properties are resolved. Consequently, connectivity testing isn’t supported for > custom properties providers. --- product: Mule Runtime version: 4.11 keywords: studio, anypoint, transform, transformer, format, aggregate, rename, split, filter convert, xml, json, csv, pojo, java object, metadata, dataweave, data weave, datawave, datamapper, dwl, dfl, dw, output structure, input structure, map, mapping --- # DataWeave Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt DataWeave is a programming language designed by MuleSoft for accessing and transforming data that travels through a Mule application. Mule runtime engine incorporates DataWeave in several core components like Transform and Set Payload, which enable you to execute DataWeave scripts and expressions in your Mule app. DataWeave scripts act on data in the Mule event. Most commonly, you use it to access and transform data in the message payload. For example, after a component in your Mule app retrieves data from one system, you can use DataWeave to modify and output selected fields in that data to a new data format, then use another component in your app to pass on that data to another system. - To get started with DataWeave 2.4.0 for Mule runtime engine (Mule) version 4.4 and later, visit [the quickstart](https://docs.mulesoft.com/dataweave/latest/dataweave-quickstart). - To learn more about DataWeave, visit [the language guide](https://docs.mulesoft.com/dataweave/latest/dataweave-language-guide). - To look up reference information about DataWeave 2.4.0 operators and functions, visit [the reference guide](https://docs.mulesoft.com/dataweave/latest/dw-functions). ## Compatibility This table specifies which version of DataWeave is bundled with each Mule runtime engine release:
Mule VersionDataWeave Version

4.13

2.13

4.12

2.12

4.11

2.11

4.10

2.10

4.9

2.9

4.8

2.8

4.7

2.7

4.6

2.6

4.5

2.5

4.4

2.4

4.3

2.3

4.2

2.2

4.1

2.1

3.9

1.2

3.8

1.1

3.7

1.0

## See Also - [Dataweave](https://docs.mulesoft.com/dataweave/latest/) --- product: Mule Runtime version: 4.12 keywords: studio, anypoint, transform, transformer, format, aggregate, rename, split, filter convert, xml, json, csv, pojo, java object, metadata, dataweave, data weave, datawave, datamapper, dwl, dfl, dw, output structure, input structure, map, mapping --- # DataWeave Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt DataWeave is a programming language designed by MuleSoft for accessing and transforming data that travels through a Mule application. Mule runtime engine incorporates DataWeave in several core components like Transform and Set Payload, which enable you to execute DataWeave scripts and expressions in your Mule app. DataWeave scripts act on data in the Mule event. Most commonly, you use it to access and transform data in the message payload. For example, after a component in your Mule app retrieves data from one system, you can use DataWeave to modify and output selected fields in that data to a new data format, then use another component in your app to pass on that data to another system. - To get started with DataWeave 2.4.0 for Mule runtime engine (Mule) version 4.4 and later, visit [the quickstart](https://docs.mulesoft.com/dataweave/latest/dataweave-quickstart). - To learn more about DataWeave, visit [the language guide](https://docs.mulesoft.com/dataweave/latest/dataweave-language-guide). - To look up reference information about DataWeave 2.4.0 operators and functions, visit [the reference guide](https://docs.mulesoft.com/dataweave/latest/dw-functions). ## Compatibility This table specifies which version of DataWeave is bundled with each Mule runtime engine release:
Mule VersionDataWeave Version

4.13

2.13

4.12

2.12

4.11

2.11

4.10

2.10

4.9

2.9

4.8

2.8

4.7

2.7

4.6

2.6

4.5

2.5

4.4

2.4

4.3

2.3

4.2

2.2

4.1

2.1

3.9

1.2

3.8

1.1

3.7

1.0

## See Also - [Dataweave](https://docs.mulesoft.com/dataweave/latest/) --- product: Mule Runtime version: 4.3 --- # DataWeave Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt DataWeave is a programming language designed by MuleSoft for accessing and transforming data that travels through a Mule application. Mule runtime engine incorporates DataWeave in several core components like Transform and Set Payload, which enable you to execute DataWeave scripts and expressions in your Mule app. DataWeave scripts act on data in the Mule event. Most commonly, you use it to access and transform data in the message payload. For example, after a component in your Mule app retrieves data from one system, you can use DataWeave to modify and output selected fields in that data to a new data format, then use another component in your app to pass on that data to another system. - To get started with DataWeave 2.3.0 for Mule runtime engine (Mule) version 4.3 and later, visit [the quickstart](https://docs.mulesoft.com/dataweave/2.3/dataweave-quickstart). - To learn more about DataWeave, visit [the language guide](https://docs.mulesoft.com/dataweave/2.3/dataweave-language-guide). - To look up reference information about DataWeave 2.3.0 operators and functions, visit [the reference guide](https://docs.mulesoft.com/dataweave/2.3/dw-functions). ## Compatibility This table specifies which version of DataWeave is bundled with each Mule runtime engine release:
Mule VersionDataWeave Version

4.13

2.13

4.12

2.12

4.11

2.11

4.10

2.10

4.9

2.9

4.8

2.8

4.7

2.7

4.6

2.6

4.5

2.5

4.4

2.4

4.3

2.3

4.2

2.2

4.1

2.1

3.9

1.2

3.8

1.1

3.7

1.0

## See Also - [Dataweave](https://docs.mulesoft.com/dataweave/latest/) --- product: Mule Runtime version: 4.4 keywords: studio, anypoint, transform, transformer, format, aggregate, rename, split, filter convert, xml, json, csv, pojo, java object, metadata, dataweave, data weave, datawave, datamapper, dwl, dfl, dw, output structure, input structure, map, mapping --- # DataWeave Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt DataWeave is a programming language designed by MuleSoft for accessing and transforming data that travels through a Mule application. Mule runtime engine incorporates DataWeave in several core components like Transform and Set Payload, which enable you to execute DataWeave scripts and expressions in your Mule app. DataWeave scripts act on data in the Mule event. Most commonly, you use it to access and transform data in the message payload. For example, after a component in your Mule app retrieves data from one system, you can use DataWeave to modify and output selected fields in that data to a new data format, then use another component in your app to pass on that data to another system. - To get started with DataWeave 2.4.0 for Mule runtime engine (Mule) version 4.4 and later, visit [the quickstart](https://docs.mulesoft.com/dataweave/latest/dataweave-quickstart). - To learn more about DataWeave, visit [the language guide](https://docs.mulesoft.com/dataweave/latest/dataweave-language-guide). - To look up reference information about DataWeave 2.4.0 operators and functions, visit [the reference guide](https://docs.mulesoft.com/dataweave/latest/dw-functions). ## Compatibility This table specifies which version of DataWeave is bundled with each Mule runtime engine release:
Mule VersionDataWeave Version

4.13

2.13

4.12

2.12

4.11

2.11

4.10

2.10

4.9

2.9

4.8

2.8

4.7

2.7

4.6

2.6

4.5

2.5

4.4

2.4

4.3

2.3

4.2

2.2

4.1

2.1

3.9

1.2

3.8

1.1

3.7

1.0

## See Also - [Dataweave](https://docs.mulesoft.com/dataweave/latest/) --- product: Mule Runtime version: 4.6 keywords: studio, anypoint, transform, transformer, format, aggregate, rename, split, filter convert, xml, json, csv, pojo, java object, metadata, dataweave, data weave, datawave, datamapper, dwl, dfl, dw, output structure, input structure, map, mapping --- # DataWeave Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt DataWeave is a programming language designed by MuleSoft for accessing and transforming data that travels through a Mule application. Mule runtime engine incorporates DataWeave in several core components like Transform and Set Payload, which enable you to execute DataWeave scripts and expressions in your Mule app. DataWeave scripts act on data in the Mule event. Most commonly, you use it to access and transform data in the message payload. For example, after a component in your Mule app retrieves data from one system, you can use DataWeave to modify and output selected fields in that data to a new data format, then use another component in your app to pass on that data to another system. - To get started with DataWeave 2.4.0 for Mule runtime engine (Mule) version 4.4 and later, visit [the quickstart](https://docs.mulesoft.com/dataweave/latest/dataweave-quickstart). - To learn more about DataWeave, visit [the language guide](https://docs.mulesoft.com/dataweave/latest/dataweave-language-guide). - To look up reference information about DataWeave 2.4.0 operators and functions, visit [the reference guide](https://docs.mulesoft.com/dataweave/latest/dw-functions). ## Compatibility This table specifies which version of DataWeave is bundled with each Mule runtime engine release:
Mule VersionDataWeave Version

4.13

2.13

4.12

2.12

4.11

2.11

4.10

2.10

4.9

2.9

4.8

2.8

4.7

2.7

4.6

2.6

4.5

2.5

4.4

2.4

4.3

2.3

4.2

2.2

4.1

2.1

3.9

1.2

3.8

1.1

3.7

1.0

## See Also - [Dataweave](https://docs.mulesoft.com/dataweave/latest/) --- product: Mule Runtime version: 4.9 keywords: studio, anypoint, transform, transformer, format, aggregate, rename, split, filter convert, xml, json, csv, pojo, java object, metadata, dataweave, data weave, datawave, datamapper, dwl, dfl, dw, output structure, input structure, map, mapping --- # DataWeave Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt DataWeave is a programming language designed by MuleSoft for accessing and transforming data that travels through a Mule application. Mule runtime engine incorporates DataWeave in several core components like Transform and Set Payload, which enable you to execute DataWeave scripts and expressions in your Mule app. DataWeave scripts act on data in the Mule event. Most commonly, you use it to access and transform data in the message payload. For example, after a component in your Mule app retrieves data from one system, you can use DataWeave to modify and output selected fields in that data to a new data format, then use another component in your app to pass on that data to another system. - To get started with DataWeave 2.4.0 for Mule runtime engine (Mule) version 4.4 and later, visit [the quickstart](https://docs.mulesoft.com/dataweave/latest/dataweave-quickstart). - To learn more about DataWeave, visit [the language guide](https://docs.mulesoft.com/dataweave/latest/dataweave-language-guide). - To look up reference information about DataWeave 2.4.0 operators and functions, visit [the reference guide](https://docs.mulesoft.com/dataweave/latest/dw-functions). ## Compatibility This table specifies which version of DataWeave is bundled with each Mule runtime engine release:
Mule VersionDataWeave Version

4.13

2.13

4.12

2.12

4.11

2.11

4.10

2.10

4.9

2.9

4.8

2.8

4.7

2.7

4.6

2.6

4.5

2.5

4.4

2.4

4.3

2.3

4.2

2.2

4.1

2.1

3.9

1.2

3.8

1.1

3.7

1.0

## See Also - [Dataweave](https://docs.mulesoft.com/dataweave/latest/) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: studio, anypoint, transform, transformer, format, aggregate, rename, split, filter convert, xml, json, csv, pojo, java object, metadata, dataweave, data weave, datawave, datamapper, dwl, dfl, dw, output structure, input structure, map, mapping --- # DataWeave Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt DataWeave is a programming language designed by MuleSoft for accessing and transforming data that travels through a Mule application. Mule runtime engine incorporates DataWeave in several core components like Transform and Set Payload, which enable you to execute DataWeave scripts and expressions in your Mule app. DataWeave scripts act on data in the Mule event. Most commonly, you use it to access and transform data in the message payload. For example, after a component in your Mule app retrieves data from one system, you can use DataWeave to modify and output selected fields in that data to a new data format, then use another component in your app to pass on that data to another system. - To get started with DataWeave 2.4.0 for Mule runtime engine (Mule) version 4.4 and later, visit [the quickstart](https://docs.mulesoft.com/dataweave/latest/dataweave-quickstart). - To learn more about DataWeave, visit [the language guide](https://docs.mulesoft.com/dataweave/latest/dataweave-language-guide). - To look up reference information about DataWeave 2.4.0 operators and functions, visit [the reference guide](https://docs.mulesoft.com/dataweave/latest/dw-functions). ## Compatibility This table specifies which version of DataWeave is bundled with each Mule runtime engine release:
Mule VersionDataWeave Version

4.13

2.13

4.12

2.12

4.11

2.11

4.10

2.10

4.9

2.9

4.8

2.8

4.7

2.7

4.6

2.6

4.5

2.5

4.4

2.4

4.3

2.3

4.2

2.2

4.1

2.1

3.9

1.2

3.8

1.1

3.7

1.0

## See Also - [Dataweave](https://docs.mulesoft.com/dataweave/latest/) --- product: Mule Runtime version: 4.11 keywords: debugging, debug --- # Debugging Outside Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept). This lets you set breakpoints to stop execution and check events. If you’re creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. ## Use MUnit to Test an App MUnit is a Mule application testing framework that allows you to build automated tests for your integrations and APIs. It provides a full suite of integration and unit test capabilities, and is fully integrated with Maven and Surefire for integration with your continuous deployment environment. For more information, see the MUnit documentation. ## Activate Remote Debugging You can start Mule with the **\-debug** option to activate remote debugging, as shown in this Linux example: $MULE\_HOME/bin/mule -debug With this option, Mule starts normally and logs the following message in the console: Listening for transport dt\_socket at address: 5005 Mule is now remotely debuggable on port 5005. Follow these steps to debug Mule: 1. Access Eclipse, and select the **Run > Debug Configurations** menu. From there, create a **Remote Java Application** configuration that uses port 5005. 2. Add the source code of your Mule local instance as an external archive on the second tab of the configuration panel. 3. Click the **Debug** button at the lower right corner of the configuration screen. The local Mule instance resumes its start-up sequence and you can debug the app step-by-step. If you want to use a port other than 5005, change the JPDA\_OPTS property file in the Mule startup script before following the steps for debugging Mule. --- product: Mule Runtime version: 4.12 keywords: debugging, debug --- # Debugging Outside Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept). This lets you set breakpoints to stop execution and check events. If you’re creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. ## Use MUnit to Test an App MUnit is a Mule application testing framework that allows you to build automated tests for your integrations and APIs. It provides a full suite of integration and unit test capabilities, and is fully integrated with Maven and Surefire for integration with your continuous deployment environment. For more information, see the MUnit documentation. ## Activate Remote Debugging You can start Mule with the **\-debug** option to activate remote debugging, as shown in this Linux example: $MULE\_HOME/bin/mule -debug With this option, Mule starts normally and logs the following message in the console: Listening for transport dt\_socket at address: 5005 Mule is now remotely debuggable on port 5005. Follow these steps to debug Mule: 1. Access Eclipse, and select the **Run > Debug Configurations** menu. From there, create a **Remote Java Application** configuration that uses port 5005. 2. Add the source code of your Mule local instance as an external archive on the second tab of the configuration panel. 3. Click the **Debug** button at the lower right corner of the configuration screen. The local Mule instance resumes its start-up sequence and you can debug the app step-by-step. If you want to use a port other than 5005, change the JPDA\_OPTS property file in the Mule startup script before following the steps for debugging Mule. --- product: Mule Runtime version: 4.3 keywords: debugging, debug --- # Debugging Outside Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept). This lets you set breakpoints to stop execution and check events. If you’re creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. ## Use MUnit to Test an App MUnit is a Mule application testing framework that allows you to build automated tests for your integrations and APIs. It provides a full suite of integration and unit test capabilities, and is fully integrated with Maven and Surefire for integration with your continuous deployment environment. For more information, see the MUnit documentation. ## Activate Remote Debugging You can start Mule with the **\-debug** option to activate remote debugging, as shown in this Linux example: $MULE\_HOME/bin/mule -debug With this option, Mule starts normally and logs the following message in the console: Listening for transport dt\_socket at address: 5005 Mule is now remotely debuggable on port 5005. Follow these steps to debug Mule: 1. Access Eclipse, and select the the **Run > Debug Configurations** menu. From there, create a **Remote Java Application** configuration that uses port 5005. 2. Add the source code of your Mule local instance as an external archive on the second tab of the configuration panel. 3. Click the **Debug** button at the lower right corner of the configuration screen. The local Mule instance resumes its start-up sequence and you can debug the app step-by-step. If you want to use a port other than 5005, change the JPDA\_OPTS property file in the Mule startup script before following the steps for debugging Mule. --- product: Mule Runtime version: 4.4 keywords: debugging, debug --- # Debugging Outside Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept). This lets you set breakpoints to stop execution and check events. If you’re creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. ## Use MUnit to Test an App MUnit is a Mule application testing framework that allows you to build automated tests for your integrations and APIs. It provides a full suite of integration and unit test capabilities, and is fully integrated with Maven and Surefire for integration with your continuous deployment environment. For more information, see the MUnit documentation. ## Activate Remote Debugging You can start Mule with the **\-debug** option to activate remote debugging, as shown in this Linux example: $MULE\_HOME/bin/mule -debug With this option, Mule starts normally and logs the following message in the console: Listening for transport dt\_socket at address: 5005 Mule is now remotely debuggable on port 5005. Follow these steps to debug Mule: 1. Access Eclipse, and select the the **Run > Debug Configurations** menu. From there, create a **Remote Java Application** configuration that uses port 5005. 2. Add the source code of your Mule local instance as an external archive on the second tab of the configuration panel. 3. Click the **Debug** button at the lower right corner of the configuration screen. The local Mule instance resumes its start-up sequence and you can debug the app step-by-step. If you want to use a port other than 5005, change the JPDA\_OPTS property file in the Mule startup script before following the steps for debugging Mule. --- product: Mule Runtime version: 4.6 keywords: debugging, debug --- # Debugging Outside Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept). This lets you set breakpoints to stop execution and check events. If you’re creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. ## Use MUnit to Test an App MUnit is a Mule application testing framework that allows you to build automated tests for your integrations and APIs. It provides a full suite of integration and unit test capabilities, and is fully integrated with Maven and Surefire for integration with your continuous deployment environment. For more information, see the MUnit documentation. ## Activate Remote Debugging You can start Mule with the **\-debug** option to activate remote debugging, as shown in this Linux example: $MULE\_HOME/bin/mule -debug With this option, Mule starts normally and logs the following message in the console: Listening for transport dt\_socket at address: 5005 Mule is now remotely debuggable on port 5005. Follow these steps to debug Mule: 1. Access Eclipse, and select the the **Run > Debug Configurations** menu. From there, create a **Remote Java Application** configuration that uses port 5005. 2. Add the source code of your Mule local instance as an external archive on the second tab of the configuration panel. 3. Click the **Debug** button at the lower right corner of the configuration screen. The local Mule instance resumes its start-up sequence and you can debug the app step-by-step. If you want to use a port other than 5005, change the JPDA\_OPTS property file in the Mule startup script before following the steps for debugging Mule. --- product: Mule Runtime version: 4.9 keywords: debugging, debug --- # Debugging Outside Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept). This lets you set breakpoints to stop execution and check events. If you’re creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. ## Use MUnit to Test an App MUnit is a Mule application testing framework that allows you to build automated tests for your integrations and APIs. It provides a full suite of integration and unit test capabilities, and is fully integrated with Maven and Surefire for integration with your continuous deployment environment. For more information, see the MUnit documentation. ## Activate Remote Debugging You can start Mule with the **\-debug** option to activate remote debugging, as shown in this Linux example: $MULE\_HOME/bin/mule -debug With this option, Mule starts normally and logs the following message in the console: Listening for transport dt\_socket at address: 5005 Mule is now remotely debuggable on port 5005. Follow these steps to debug Mule: 1. Access Eclipse, and select the **Run > Debug Configurations** menu. From there, create a **Remote Java Application** configuration that uses port 5005. 2. Add the source code of your Mule local instance as an external archive on the second tab of the configuration panel. 3. Click the **Debug** button at the lower right corner of the configuration screen. The local Mule instance resumes its start-up sequence and you can debug the app step-by-step. If you want to use a port other than 5005, change the JPDA\_OPTS property file in the Mule startup script before following the steps for debugging Mule. --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: debugging, debug --- # Debugging Outside Studio > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept). This lets you set breakpoints to stop execution and check events. If you’re creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. ## Use MUnit to Test an App MUnit is a Mule application testing framework that allows you to build automated tests for your integrations and APIs. It provides a full suite of integration and unit test capabilities, and is fully integrated with Maven and Surefire for integration with your continuous deployment environment. For more information, see the MUnit documentation. ## Activate Remote Debugging You can start Mule with the **\-debug** option to activate remote debugging, as shown in this Linux example: $MULE\_HOME/bin/mule -debug With this option, Mule starts normally and logs the following message in the console: Listening for transport dt\_socket at address: 5005 Mule is now remotely debuggable on port 5005. Follow these steps to debug Mule: 1. Access Eclipse, and select the **Run > Debug Configurations** menu. From there, create a **Remote Java Application** configuration that uses port 5005. 2. Add the source code of your Mule local instance as an external archive on the second tab of the configuration panel. 3. Click the **Debug** button at the lower right corner of the configuration screen. The local Mule instance resumes its start-up sequence and you can debug the app step-by-step. If you want to use a port other than 5005, change the JPDA\_OPTS property file in the Mule startup script before following the steps for debugging Mule. --- product: Mule Runtime version: 4.11 --- # Define Input and Output Structure of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform Message component first needs information about what fields are available for dragging and dropping onto. If you plan to create your transformation entirely by writing DataWeave code, you can skip defining input and output and reference elements directly. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When input and output of a component can be predicted based on its configuration, these are exposed to the rest of the flow. For example, when a Salesforce connector is configured to carry out a specific operation, its output structure is known and exposed. 2. If input or output of certain components can’t be predicted, manually define the output and input of key components via their Metadata Tab. For example, an HTTP listener might receive requests containing any payload. ## Define Data Structure in Transform Message Component 1. Right click on the root of the input or the output tree, then select Set Metadata. 2. Manually define the data structure. ## Define Data Structure Via XML See [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/4.11/transform-dataweave-xml-reference). ## Reader Configuration In case your input needs to be parsed in a special way, you can set up certain properties for the reader object. Each input format has different configurable properties, or none. There are two ways to set these listed below. - Configure other components on the flow, by accessing their corresponding Metadata tab. - On the Transform Message component, right click on the root of the input pane and select **Reader Configuration** ![A Reader Configuration in the Transform Message component](/mulesoft/current/en-us/mule-runtime/4.11/_images/dw-reader-configuration-select.png) > [!NOTE] This option only exists if the selected data type format allows for configurable reader > properties. If the payload is of type `unknown`, you must change its type first. For a detailed reference of what properties can be set in the Reader Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#xml) - [Flat File](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#flat-file) > [!NOTE] You can also add this information through properties in the XML source of your Mule > project. ## Writer Configuration In case your output needs to be constructed in a special way, you can set up certain properties of the writer object. Each output format has different configurable properties, or none. These properties must be written on the `%output` directive of your DataWeave code. For a detailed reference of what properties can be set in the Writer Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#xml) - [JSON](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#json) - [Flat File](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#flat-file) ## See Also [Workflow: Create a Mapping through the Anypoint Studio UI](https://docs.mulesoft.com/mule-runtime/4.11/transform-workflow-create-mapping-ui-studio) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.11/transform-component-about) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.11/dataweave) [DataWeave Types](https://docs.mulesoft.com/dataweave/latest/dataweave-types) [Supported Data Formats](https://docs.mulesoft.com/dataweave/latest/dataweave-formats) [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/4.11/transform-dataweave-xml-reference) --- product: Mule Runtime version: 4.12 --- # Define Input and Output Structure of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform Message component first needs information about what fields are available for dragging and dropping onto. If you plan to create your transformation entirely by writing DataWeave code, you can skip defining input and output and reference elements directly. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When input and output of a component can be predicted based on its configuration, these are exposed to the rest of the flow. For example, when a Salesforce connector is configured to carry out a specific operation, its output structure is known and exposed. 2. If input or output of certain components can’t be predicted, manually define the output and input of key components via their Metadata Tab. For example, an HTTP listener might receive requests containing any payload. ## Define Data Structure in Transform Message Component 1. Right click on the root of the input or the output tree, then select Set Metadata. 2. Manually define the data structure. ## Define Data Structure Via XML See [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/4.12/transform-dataweave-xml-reference). ## Reader Configuration In case your input needs to be parsed in a special way, you can set up certain properties for the reader object. Each input format has different configurable properties, or none. There are two ways to set these listed below. - Configure other components on the flow, by accessing their corresponding Metadata tab. - On the Transform Message component, right click on the root of the input pane and select **Reader Configuration** ![A Reader Configuration in the Transform Message component](/mulesoft/current/en-us/mule-runtime/4.12/_images/dw-reader-configuration-select.png) > [!NOTE] This option only exists if the selected data type format allows for configurable reader > properties. If the payload is of type `unknown`, you must change its type first. For a detailed reference of what properties can be set in the Reader Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#xml) - [Flat File](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#flat-file) > [!NOTE] You can also add this information through properties in the XML source of your Mule > project. ## Writer Configuration In case your output needs to be constructed in a special way, you can set up certain properties of the writer object. Each output format has different configurable properties, or none. These properties must be written on the `%output` directive of your DataWeave code. For a detailed reference of what properties can be set in the Writer Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#xml) - [JSON](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#json) - [Flat File](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#flat-file) ## See Also [Workflow: Create a Mapping through the Anypoint Studio UI](https://docs.mulesoft.com/mule-runtime/4.12/transform-workflow-create-mapping-ui-studio) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.12/transform-component-about) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.12/dataweave) [DataWeave Types](https://docs.mulesoft.com/dataweave/latest/dataweave-types) [Supported Data Formats](https://docs.mulesoft.com/dataweave/latest/dataweave-formats) [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/4.12/transform-dataweave-xml-reference) --- product: Mule Runtime version: 4.3 --- # Define Input and Output Structure of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform Message component first needs information about what fields are available for dragging and dropping onto. If you plan to create your transformation entirely by writing DataWeave code, you can skip defining input and output and reference elements directly. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When input and output of a component can be predicted based on its configuration, these are exposed to the rest of the flow. For example, when a Salesforce connector is configured to carry out a specific operation, its output structure is known and exposed. 2. If input or output of certain components can’t be predicted, manually define the output and input of key components via their Metadata Tab. For example, an HTTP listener might receive requests containing any payload. ## Define Data Structure in Transform Message Component 1. Right click on the root of the input or the output tree, then select Set Metadata. 2. Manually define the data structure. ## Define Data Structure Via XML See [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/4.3/transform-dataweave-xml-reference). ## Reader Configuration In case your input needs to be parsed in a special way, you can set up certain properties for the reader object. Each input format has different configurable properties, or none. There are two ways to set these listed below. - Configure other components on the flow, by accessing their corresponding Metadata tab. - On the Transform Message component, right click on the root of the input pane and select **Reader Configuration** ![Reader Configuration](/mulesoft/current/en-us/mule-runtime/4.3/_images/dw-reader-configuration-select.png) > [!NOTE] This option only exists if the selected data type format allows for configurable reader > properties. If the payload is of type `unknown`, you must change its type first. For a detailed reference of what properties can be set in the Reader Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/2.3/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/2.3/dataweave-formats#xml) - [Flat File](https://docs.mulesoft.com/dataweave/2.3/dataweave-formats#flat-file) > [!NOTE] You can also add this information through properties in the XML source of your Mule > project. ## Writer Configuration In case your output needs to be constructed in a special way, you can set up certain properties of the writer object. Each output format has different configurable properties, or none. These properties must be written on the `%output` directive of your DataWeave code. For a detailed reference of what properties can be set in the Writer Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/2.3/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/2.3/dataweave-formats#xml) - [JSON](https://docs.mulesoft.com/dataweave/2.3/dataweave-formats#json) - [Flat File](https://docs.mulesoft.com/dataweave/2.3/dataweave-formats#flat-file) ## See Also [Workflow: Create a Mapping through the Anypoint Studio UI](https://docs.mulesoft.com/mule-runtime/4.3/transform-workflow-create-mapping-ui-studio) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.3/transform-component-about) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) [DataWeave Types](https://docs.mulesoft.com/dataweave/2.3/dataweave-types) [Supported Data Formats](https://docs.mulesoft.com/dataweave/2.3/dataweave-formats) [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/4.3/transform-dataweave-xml-reference) --- product: Mule Runtime version: 4.4 --- # Define Input and Output Structure of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform Message component first needs information about what fields are available for dragging and dropping onto. If you plan to create your transformation entirely by writing DataWeave code, you can skip defining input and output and reference elements directly. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When input and output of a component can be predicted based on its configuration, these are exposed to the rest of the flow. For example, when a Salesforce connector is configured to carry out a specific operation, its output structure is known and exposed. 2. If input or output of certain components can’t be predicted, manually define the output and input of key components via their Metadata Tab. For example, an HTTP listener might receive requests containing any payload. ## Define Data Structure in Transform Message Component 1. Right click on the root of the input or the output tree, then select Set Metadata. 2. Manually define the data structure. ## Define Data Structure Via XML See [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/4.4/transform-dataweave-xml-reference). ## Reader Configuration In case your input needs to be parsed in a special way, you can set up certain properties for the reader object. Each input format has different configurable properties, or none. There are two ways to set these listed below. - Configure other components on the flow, by accessing their corresponding Metadata tab. - On the Transform Message component, right click on the root of the input pane and select **Reader Configuration** ![Reader Configuration](/mulesoft/current/en-us/mule-runtime/4.4/_images/dw-reader-configuration-select.png) > [!NOTE] This option only exists if the selected data type format allows for configurable reader > properties. If the payload is of type `unknown`, you must change its type first. For a detailed reference of what properties can be set in the Reader Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#xml) - [Flat File](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#flat-file) > [!NOTE] You can also add this information through properties in the XML source of your Mule > project. ## Writer Configuration In case your output needs to be constructed in a special way, you can set up certain properties of the writer object. Each output format has different configurable properties, or none. These properties must be written on the `%output` directive of your DataWeave code. For a detailed reference of what properties can be set in the Writer Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#xml) - [JSON](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#json) - [Flat File](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#flat-file) ## See Also [Workflow: Create a Mapping through the Anypoint Studio UI](https://docs.mulesoft.com/mule-runtime/4.4/transform-workflow-create-mapping-ui-studio) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.4/transform-component-about) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) [DataWeave Types](https://docs.mulesoft.com/dataweave/latest/dataweave-types) [Supported Data Formats](https://docs.mulesoft.com/dataweave/latest/dataweave-formats) [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/4.4/transform-dataweave-xml-reference) --- product: Mule Runtime version: 4.6 --- # Define Input and Output Structure of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform Message component first needs information about what fields are available for dragging and dropping onto. If you plan to create your transformation entirely by writing DataWeave code, you can skip defining input and output and reference elements directly. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When input and output of a component can be predicted based on its configuration, these are exposed to the rest of the flow. For example, when a Salesforce connector is configured to carry out a specific operation, its output structure is known and exposed. 2. If input or output of certain components can’t be predicted, manually define the output and input of key components via their Metadata Tab. For example, an HTTP listener might receive requests containing any payload. ## Define Data Structure in Transform Message Component 1. Right click on the root of the input or the output tree, then select Set Metadata. 2. Manually define the data structure. ## Define Data Structure Via XML See [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/4.6/transform-dataweave-xml-reference). ## Reader Configuration In case your input needs to be parsed in a special way, you can set up certain properties for the reader object. Each input format has different configurable properties, or none. There are two ways to set these listed below. - Configure other components on the flow, by accessing their corresponding Metadata tab. - On the Transform Message component, right click on the root of the input pane and select **Reader Configuration** ![Reader Configuration](/mulesoft/current/en-us/mule-runtime/4.6/_images/dw-reader-configuration-select.png) > [!NOTE] This option only exists if the selected data type format allows for configurable reader > properties. If the payload is of type `unknown`, you must change its type first. For a detailed reference of what properties can be set in the Reader Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#xml) - [Flat File](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#flat-file) > [!NOTE] You can also add this information through properties in the XML source of your Mule > project. ## Writer Configuration In case your output needs to be constructed in a special way, you can set up certain properties of the writer object. Each output format has different configurable properties, or none. These properties must be written on the `%output` directive of your DataWeave code. For a detailed reference of what properties can be set in the Writer Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#xml) - [JSON](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#json) - [Flat File](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#flat-file) ## See Also [Workflow: Create a Mapping through the Anypoint Studio UI](https://docs.mulesoft.com/mule-runtime/4.6/transform-workflow-create-mapping-ui-studio) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.6/transform-component-about) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.6/dataweave) [DataWeave Types](https://docs.mulesoft.com/dataweave/latest/dataweave-types) [Supported Data Formats](https://docs.mulesoft.com/dataweave/latest/dataweave-formats) [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/4.6/transform-dataweave-xml-reference) --- product: Mule Runtime version: 4.9 --- # Define Input and Output Structure of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform Message component first needs information about what fields are available for dragging and dropping onto. If you plan to create your transformation entirely by writing DataWeave code, you can skip defining input and output and reference elements directly. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When input and output of a component can be predicted based on its configuration, these are exposed to the rest of the flow. For example, when a Salesforce connector is configured to carry out a specific operation, its output structure is known and exposed. 2. If input or output of certain components can’t be predicted, manually define the output and input of key components via their Metadata Tab. For example, an HTTP listener might receive requests containing any payload. ## Define Data Structure in Transform Message Component 1. Right click on the root of the input or the output tree, then select Set Metadata. 2. Manually define the data structure. ## Define Data Structure Via XML See [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/4.9/transform-dataweave-xml-reference). ## Reader Configuration In case your input needs to be parsed in a special way, you can set up certain properties for the reader object. Each input format has different configurable properties, or none. There are two ways to set these listed below. - Configure other components on the flow, by accessing their corresponding Metadata tab. - On the Transform Message component, right click on the root of the input pane and select **Reader Configuration** ![A Reader Configuration in the Transform Message component](/mulesoft/current/en-us/mule-runtime/4.9/_images/dw-reader-configuration-select.png) > [!NOTE] This option only exists if the selected data type format allows for configurable reader > properties. If the payload is of type `unknown`, you must change its type first. For a detailed reference of what properties can be set in the Reader Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#xml) - [Flat File](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#flat-file) > [!NOTE] You can also add this information through properties in the XML source of your Mule > project. ## Writer Configuration In case your output needs to be constructed in a special way, you can set up certain properties of the writer object. Each output format has different configurable properties, or none. These properties must be written on the `%output` directive of your DataWeave code. For a detailed reference of what properties can be set in the Writer Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#xml) - [JSON](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#json) - [Flat File](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#flat-file) ## See Also [Workflow: Create a Mapping through the Anypoint Studio UI](https://docs.mulesoft.com/mule-runtime/4.9/transform-workflow-create-mapping-ui-studio) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.9/transform-component-about) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.9/dataweave) [DataWeave Types](https://docs.mulesoft.com/dataweave/latest/dataweave-types) [Supported Data Formats](https://docs.mulesoft.com/dataweave/latest/dataweave-formats) [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/4.9/transform-dataweave-xml-reference) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Define Input and Output Structure of a Transformation (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform Message component first needs information about what fields are available for dragging and dropping onto. If you plan to create your transformation entirely by writing DataWeave code, you can skip defining input and output and reference elements directly. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When input and output of a component can be predicted based on its configuration, these are exposed to the rest of the flow. For example, when a Salesforce connector is configured to carry out a specific operation, its output structure is known and exposed. 2. If input or output of certain components can’t be predicted, manually define the output and input of key components via their Metadata Tab. For example, an HTTP listener might receive requests containing any payload. ## Define Data Structure in Transform Message Component 1. Right click on the root of the input or the output tree, then select Set Metadata. 2. Manually define the data structure. ## Define Data Structure Via XML See [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/latest/transform-dataweave-xml-reference). ## Reader Configuration In case your input needs to be parsed in a special way, you can set up certain properties for the reader object. Each input format has different configurable properties, or none. There are two ways to set these listed below. - Configure other components on the flow, by accessing their corresponding Metadata tab. - On the Transform Message component, right click on the root of the input pane and select **Reader Configuration** ![A Reader Configuration in the Transform Message component](/mulesoft/current/en-us/mule-runtime/latest/_images/dw-reader-configuration-select.png) > [!NOTE] This option only exists if the selected data type format allows for configurable reader > properties. If the payload is of type `unknown`, you must change its type first. For a detailed reference of what properties can be set in the Reader Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#xml) - [Flat File](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#flat-file) > [!NOTE] You can also add this information through properties in the XML source of your Mule > project. ## Writer Configuration In case your output needs to be constructed in a special way, you can set up certain properties of the writer object. Each output format has different configurable properties, or none. These properties must be written on the `%output` directive of your DataWeave code. For a detailed reference of what properties can be set in the Writer Configuration of each format, see the corresponding **reader properties** section: - [CSV](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#csv) - [XML](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#xml) - [JSON](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#json) - [Flat File](https://docs.mulesoft.com/dataweave/latest/dataweave-formats#flat-file) ## See Also [Workflow: Create a Mapping through the Anypoint Studio UI](https://docs.mulesoft.com/mule-runtime/latest/transform-workflow-create-mapping-ui-studio) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/latest/transform-component-about) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/latest/dataweave) [DataWeave Types](https://docs.mulesoft.com/dataweave/latest/dataweave-types) [Supported Data Formats](https://docs.mulesoft.com/dataweave/latest/dataweave-formats) [DataWeave XML Reference](https://docs.mulesoft.com/mule-runtime/latest/transform-dataweave-xml-reference) --- product: Mule Runtime version: 4.11 --- # Define Input and Output Structure of a Transformation (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform component first needs information about what fields are available for dragging and dropping. If you plan to create your transformation entirely by writing DataWeave source code, you can skip defining input and output and reference elements directly via code. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When all other elements are configured and you have a component that has a predicted data structure, the structure can be passed onto the Transform component. 2. Manually define input and output data structures if Design Center cannot predict the data structure. For example, an HTTP Listener might receive requests containing any type of payload. If you know what this payload will look like, you can set the data type through the Input and Output tabs in the HTTP Listener dialog box. ## Define Data Structures in the Transform Component 1. Click Set Data Type: - For the input pane, highlight the payload, attributes, or a variable and click the Set Data Type icon at the bottom of the input pane. - For the output pane, select the Set data type button. If the output pane has an existing data type, click the drop-down arrow at the top of the Output pane to set a new data type. 2. Manually define the data structure by providing a sample or a schema. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.11/dataweave) --- product: Mule Runtime version: 4.12 --- # Define Input and Output Structure of a Transformation (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform component first needs information about what fields are available for dragging and dropping. If you plan to create your transformation entirely by writing DataWeave source code, you can skip defining input and output and reference elements directly via code. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When all other elements are configured and you have a component that has a predicted data structure, the structure can be passed onto the Transform component. 2. Manually define input and output data structures if Design Center cannot predict the data structure. For example, an HTTP Listener might receive requests containing any type of payload. If you know what this payload will look like, you can set the data type through the Input and Output tabs in the HTTP Listener dialog box. ## Define Data Structures in the Transform Component 1. Click Set Data Type: - For the input pane, highlight the payload, attributes, or a variable and click the Set Data Type icon at the bottom of the input pane. - For the output pane, select the Set data type button. If the output pane has an existing data type, click the drop-down arrow at the top of the Output pane to set a new data type. 2. Manually define the data structure by providing a sample or a schema. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.12/dataweave) --- product: Mule Runtime version: 4.3 --- # Define Input and Output Structure of a Transformation (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform component first needs information about what fields are available for dragging and dropping. If you plan to create your transformation entirely by writing DataWeave source code, you can skip defining input and output and reference elements directly via code. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When all other elements are configured and you have a component that has a predicted data structure, the structure can be passed onto the Transform component. 2. Manually define input and output data structures if Design Center cannot predict the data structure. For example, an HTTP Listener might receive requests containing any type of payload. If you know what this payload will look like, you can set the data type through the Input and Output tabs in the HTTP Listener dialog box. ## Define Data Structures in the Transform Component 1. Click Set Data Type: - For the input pane, highlight the payload, attributes, or a variable and click the Set Data Type icon at the bottom of the input pane. - For the output pane, select the Set data type button. If the output pane has an existing data type, click the drop-down arrow at the top of the Output pane to set a new data type. 2. Manually define the data structure by providing a sample or a schema. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) --- product: Mule Runtime version: 4.4 --- # Define Input and Output Structure of a Transformation (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform component first needs information about what fields are available for dragging and dropping. If you plan to create your transformation entirely by writing DataWeave source code, you can skip defining input and output and reference elements directly via code. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When all other elements are configured and you have a component that has a predicted data structure, the structure can be passed onto the Transform component. 2. Manually define input and output data structures if Design Center cannot predict the data structure. For example, an HTTP Listener might receive requests containing any type of payload. If you know what this payload will look like, you can set the data type through the Input and Output tabs in the HTTP Listener dialog box. ## Define Data Structures in the Transform Component 1. Click Set Data Type: - For the input pane, highlight the payload, attributes, or a variable and click the Set Data Type icon at the bottom of the input pane. - For the output pane, select the Set data type button. If the output pane has an existing data type, click the drop-down arrow at the top of the Output pane to set a new data type. 2. Manually define the data structure by providing a sample or a schema. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) --- product: Mule Runtime version: 4.6 --- # Define Input and Output Structure of a Transformation (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform component first needs information about what fields are available for dragging and dropping. If you plan to create your transformation entirely by writing DataWeave source code, you can skip defining input and output and reference elements directly via code. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When all other elements are configured and you have a component that has a predicted data structure, the structure can be passed onto the Transform component. 2. Manually define input and output data structures if Design Center cannot predict the data structure. For example, an HTTP Listener might receive requests containing any type of payload. If you know what this payload will look like, you can set the data type through the Input and Output tabs in the HTTP Listener dialog box. ## Define Data Structures in the Transform Component 1. Click Set Data Type: - For the input pane, highlight the payload, attributes, or a variable and click the Set Data Type icon at the bottom of the input pane. - For the output pane, select the Set data type button. If the output pane has an existing data type, click the drop-down arrow at the top of the Output pane to set a new data type. 2. Manually define the data structure by providing a sample or a schema. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.6/dataweave) --- product: Mule Runtime version: 4.9 --- # Define Input and Output Structure of a Transformation (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform component first needs information about what fields are available for dragging and dropping. If you plan to create your transformation entirely by writing DataWeave source code, you can skip defining input and output and reference elements directly via code. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When all other elements are configured and you have a component that has a predicted data structure, the structure can be passed onto the Transform component. 2. Manually define input and output data structures if Design Center cannot predict the data structure. For example, an HTTP Listener might receive requests containing any type of payload. If you know what this payload will look like, you can set the data type through the Input and Output tabs in the HTTP Listener dialog box. ## Define Data Structures in the Transform Component 1. Click Set Data Type: - For the input pane, highlight the payload, attributes, or a variable and click the Set Data Type icon at the bottom of the input pane. - For the output pane, select the Set data type button. If the output pane has an existing data type, click the drop-down arrow at the top of the Output pane to set a new data type. 2. Manually define the data structure by providing a sample or a schema. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.9/dataweave) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Define Input and Output Structure of a Transformation (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To use the graphical view and construct mappings via drag and drop, the Transform component first needs information about what fields are available for dragging and dropping. If you plan to create your transformation entirely by writing DataWeave source code, you can skip defining input and output and reference elements directly via code. ## Define Data Structure on Other Components 1. Make sure that all other elements in the flow are fully configured. When all other elements are configured and you have a component that has a predicted data structure, the structure can be passed onto the Transform component. 2. Manually define input and output data structures if Design Center cannot predict the data structure. For example, an HTTP Listener might receive requests containing any type of payload. If you know what this payload will look like, you can set the data type through the Input and Output tabs in the HTTP Listener dialog box. ## Define Data Structures in the Transform Component 1. Click Set Data Type: - For the input pane, highlight the payload, attributes, or a variable and click the Set Data Type icon at the bottom of the input pane. - For the output pane, select the Set data type button. If the output pane has an existing data type, click the drop-down arrow at the top of the Output pane to set a new data type. 2. Manually define the data structure by providing a sample or a schema. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/latest/dataweave) --- product: Mule Runtime version: 4.11 --- # Deploy Applications to CloudHub 2.0 Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to CloudHub 2.0, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub 2.0 deployment strategy in your project’s `pom.xml` file. ## Before You Begin - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). - The Mule Maven Facade API (v3) is added as a repository in the distribution management section of your project’s POM file. For example: ```xml Repository Corporate Repository https://maven.anypoint.mulesoft.com/api/v3/organizations/ORGANIZATION_ID/maven default ``` See [The Mule Maven Facade API documentation](https://anypoint.mulesoft.com/exchange/portals/anypoint-platform/f1e97bc6-315a-4490-82a7-23abe036327a.anypoint-platform/exchange-maven-facade-api-http/) for more information. ## Configure the CloudHub 2.0 Deployment Strategy Inside the `plugin` element, add a configuration for your CloudHub 2.0 deployment, replacing the following placeholder values with your CloudHub 2.0 information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com MC ${environment} ${targetName} ${muleVersion} ${user} ${pass} ${appName} 1 1 ${publicUrl} true true ``` ## Deploy to CloudHub 2.0 From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` To deploy the artifact without rebuilding it, run: ```bash mvn mule:deploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into CloudHub 2.0. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to CloudHub 2.0 via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to CloudHub 2.0 To redeploy the application, run the same command as you did to deploy. CloudHub 2.0 rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub 2.0 username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub 2.0 Deployment Parameters Reference](#cloudhub2-deploy-reference). ## CloudHub 2.0 Deployment Parameters Reference
ParameterDescriptionRequired

cloudhub2Deployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub 2.0 instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to select a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.
Because Mule runtime 4.4 Standard Support ends in October 2024, new Mule apps can be deployed on either Mule 4.6 LTS or Mule 4.8 Edge. As LTS channel isn’t supported for customers using a Mule Maven plugin version 4.1.0 or earlier, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

scopeLoggingConfigurations

scopeLoggingConfiguration

scope

The package of the logging library to use.

logLevel

The log level. Accepted values: INFO, DEBUG, WARN, ERROR, FATAL.

Configuration example:

<scopeLoggingConfigurations>
  <scopeLoggingConfiguration>
    <scope>com.pkg.warning</scope>
    <logLevel>WARN</logLevel>
  </scopeLoggingConfiguration>
  <scopeLoggingConfiguration>
    <scope>com.pkg.debug</scope>
    <logLevel>DEBUG</logLevel>
  </scopeLoggingConfiguration>
</scopeLoggingConfigurations>

No

target

The CloudHub 2.0 target name to deploy the app to.
Specify either a shared space or a private space available in your Deployment Target values in CloudHub 2.0. See Features of CloudHub 2.0 for a detailed description on shared and private spaces. Use a target name value from the list of regions. For example, Cloudhub-US-East-1.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for CloudHub 2.0.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy.

Only when autoscaling is set to false.

vCores

The size of each replica specified in vCores. Accepted values: 0.1, 0.2, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4. See CloudHub 2.0 Replicas for a detailed description of available vCore sizes and their assigned hardware resources.
This parameter cannot be used if you configure instanceType.

Yes (Only when instanceType isn’t configured.)

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

If you redeploy the application and the properties element isn’t configured in the deployment POM file, the existing properties configured in your CloudHub 2.0 environment are preserved. If the properties element is present in the deployment POM file, the application is deployed using only the properties defined in that element, overriding any properties configured in Runtime Manager. Any existing properties that aren’t included in the deployment configuration are removed.

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct CloudHub 2.0 to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference.

No

integrations

services

objectStoreV2

enabled

When set to true, instructs the deployment to use Object Store v2.

Configuration example:

<integrations>
  <services>
    <objectStoreV2>
      <enabled>true</enabled>
    </objectStoreV2>
  </services>
</integrations>

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.
For high availability, set this value to true.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application. You can add multiple comma-separated values.

endpoint

Defines application endpoints by specifying the url, pathRewrite, and access attributes. Accepted values for access are internal and external.

pathRewrite

Supplies the base path expected by the HTTP listener in your application. This value must begin with /. This parameter is used only for applications that are deployed to private space.

lastMileSecurity

Enable Last-Mile security to perform TLS termination and decryption for forwarded HTTPS connections directly within the Mule application. This requires the Mule application to include an SSL certificate and consumes additional CPU resources. The default value is false.

forwardSslSession

Enables SSL forwarding during a session. The default value is false.

Mule Maven Plugin supports both publicUrl and endpoint for configuring application endpoints. Configure either publicUrl or endpoints, but not both in the same deployment configuration.

Configuration example:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.anypoint.com</publicUrl>
      <pathRewrite>/api</pathRewrite>
      <lastMileSecurity>true</lastMileSecurity>
      <forwardSslSession>true</forwardSslSession>
    </inbound>
  </http>
</deploymentSettings>

Example using endpoint:

<deploymentSettings>
  <http>
    <inbound>
      <endpoints>
        <endpoint>
          <url>https://test1.com/ch2testapp1</url>
          <pathRewrite>/</pathRewrite>
          <access>external</access>
        </endpoint>
      </endpoints>
    </inbound>
  </http>
</deploymentSettings>

generateDefaultPublicUrl

When set to true, CloudHub 2.0 generates a public URL for the deployed application.
This parameter is used only for applications that are deployed to private space. Applications that are deployed to shared space always get a generated public URL.

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. The default value is false.

tracingEnabled

Exposes tracing information in OpenTelemetry standard from Mule runtime into all APM solutions. See Enable Trace Data Collection.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>

instanceType

Specifies the capacity of the replica for application deployment. This flag is available only for organizations using a usage-based pricing (UBP) package. Non-UBP organizations use the vCores parameter instead. See Anypoint Platform Pricing.

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password aren’t set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) - [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) --- product: Mule Runtime version: 4.12 --- # Deploy Applications to CloudHub 2.0 Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to CloudHub 2.0, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub 2.0 deployment strategy in your project’s `pom.xml` file. ## Before You Begin - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). - The Mule Maven Facade API (v3) is added as a repository in the distribution management section of your project’s POM file. For example: ```xml Repository Corporate Repository https://maven.anypoint.mulesoft.com/api/v3/organizations/ORGANIZATION_ID/maven default ``` See [The Mule Maven Facade API documentation](https://anypoint.mulesoft.com/exchange/portals/anypoint-platform/f1e97bc6-315a-4490-82a7-23abe036327a.anypoint-platform/exchange-maven-facade-api-http/) for more information. ## Configure the CloudHub 2.0 Deployment Strategy Inside the `plugin` element, add a configuration for your CloudHub 2.0 deployment, replacing the following placeholder values with your CloudHub 2.0 information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com MC ${environment} ${targetName} ${muleVersion} ${user} ${pass} ${appName} 1 1 ${publicUrl} true true ``` ## Deploy to CloudHub 2.0 From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` To deploy the artifact without rebuilding it, run: ```bash mvn mule:deploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into CloudHub 2.0. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to CloudHub 2.0 via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to CloudHub 2.0 To redeploy the application, run the same command as you did to deploy. CloudHub 2.0 rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub 2.0 username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub 2.0 Deployment Parameters Reference](#cloudhub2-deploy-reference). ## CloudHub 2.0 Deployment Parameters Reference
ParameterDescriptionRequired

cloudhub2Deployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub 2.0 instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to select a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.
Because Mule runtime 4.4 Standard Support ends in October 2024, new Mule apps can be deployed on either Mule 4.6 LTS or Mule 4.8 Edge. As LTS channel isn’t supported for customers using a Mule Maven plugin version 4.1.0 or earlier, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

scopeLoggingConfigurations

scopeLoggingConfiguration

scope

The package of the logging library to use.

logLevel

The log level. Accepted values: INFO, DEBUG, WARN, ERROR, FATAL.

Configuration example:

<scopeLoggingConfigurations>
  <scopeLoggingConfiguration>
    <scope>com.pkg.warning</scope>
    <logLevel>WARN</logLevel>
  </scopeLoggingConfiguration>
  <scopeLoggingConfiguration>
    <scope>com.pkg.debug</scope>
    <logLevel>DEBUG</logLevel>
  </scopeLoggingConfiguration>
</scopeLoggingConfigurations>

No

target

The CloudHub 2.0 target name to deploy the app to.
Specify either a shared space or a private space available in your Deployment Target values in CloudHub 2.0. See Features of CloudHub 2.0 for a detailed description on shared and private spaces. Use a target name value from the list of regions. For example, Cloudhub-US-East-1.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for CloudHub 2.0.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy.

Only when autoscaling is set to false.

vCores

The size of each replica specified in vCores. Accepted values: 0.1, 0.2, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4. See CloudHub 2.0 Replicas for a detailed description of available vCore sizes and their assigned hardware resources.
This parameter cannot be used if you configure instanceType.

Yes (Only when instanceType isn’t configured.)

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

If you redeploy the application and neither the properties nor the secureProperties element is configured in the deployment POM file, CloudHub 2.0 preserves the existing properties configured in your CloudHub 2.0 environment. If either element is present, CloudHub 2.0 deploys the application using only the properties and secure properties defined in the POM. It doesn’t merge them with values configured in Runtime Manager. Any existing properties that aren’t included in the deployment configuration are removed. To keep existing values, omit both elements, or send the full set of properties and secure properties on every redeploy.

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct CloudHub 2.0 to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

If you redeploy the application and neither the secureProperties nor the properties element is configured in the deployment POM file, CloudHub 2.0 preserves the existing secure properties configured in your CloudHub 2.0 environment. If either element is present, CloudHub 2.0 deploys the application using only the properties and secure properties defined in the POM. It doesn’t merge them with values configured in Runtime Manager. Any existing secure properties that aren’t included in the deployment configuration are removed. To keep existing values, omit both elements, or send the full set of properties and secure properties on every redeploy.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference.

No

integrations

services

objectStoreV2

enabled

When set to true, instructs the deployment to use Object Store v2.

Configuration example:

<integrations>
  <services>
    <objectStoreV2>
      <enabled>true</enabled>
    </objectStoreV2>
  </services>
</integrations>

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.
For high availability, set this value to true.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application. You can add multiple comma-separated values.

endpoint

Defines application endpoints by specifying the url, pathRewrite, and access attributes. Accepted values for access are internal and external.

pathRewrite

Supplies the base path expected by the HTTP listener in your application. This value must begin with /. This parameter is used only for applications that are deployed to private space.

lastMileSecurity

Enable Last-Mile security to perform TLS termination and decryption for forwarded HTTPS connections directly within the Mule application. This requires the Mule application to include an SSL certificate and consumes additional CPU resources. The default value is false.

forwardSslSession

Enables SSL forwarding during a session. The default value is false.

Mule Maven Plugin supports both publicUrl and endpoint for configuring application endpoints. Configure either publicUrl or endpoints, but not both in the same deployment configuration.

Configuration example:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.anypoint.com</publicUrl>
      <pathRewrite>/api</pathRewrite>
      <lastMileSecurity>true</lastMileSecurity>
      <forwardSslSession>true</forwardSslSession>
    </inbound>
  </http>
</deploymentSettings>

Example using endpoint:

<deploymentSettings>
  <http>
    <inbound>
      <endpoints>
        <endpoint>
          <url>https://test1.com/ch2testapp1</url>
          <pathRewrite>/</pathRewrite>
          <access>external</access>
        </endpoint>
      </endpoints>
    </inbound>
  </http>
</deploymentSettings>

generateDefaultPublicUrl

When set to true, CloudHub 2.0 generates a public URL for the deployed application.
This parameter is used only for applications that are deployed to private space. Applications that are deployed to shared space always get a generated public URL.

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. The default value is false.

tracingEnabled

Exposes tracing information in OpenTelemetry standard from Mule runtime into all APM solutions. See Enable Trace Data Collection.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>

instanceType

Specifies the capacity of the replica for application deployment. This flag is available only for organizations using a usage-based pricing (UBP) package. Non-UBP organizations use the vCores parameter instead. See Anypoint Platform Pricing.

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password aren’t set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) - [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) --- product: Mule Runtime version: 4.4 --- # Deploy Applications to CloudHub 2.0 Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to CloudHub 2.0, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub 2.0 deployment strategy in your project’s `pom.xml` file. ## Before You Begin - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). - The Mule Maven Facade API (v3) is added as a repository in the distribution management section of your project’s POM file. For example: ```xml Repository Corporate Repository https://maven.anypoint.mulesoft.com/api/v3/organizations/ORGANIZATION_ID/maven default ``` See [The Mule Maven Facade API documentation](https://anypoint.mulesoft.com/exchange/portals/anypoint-platform/f1e97bc6-315a-4490-82a7-23abe036327a.anypoint-platform/exchange-maven-facade-api-http/) for more information. ## Configure the CloudHub 2.0 Deployment Strategy Inside the `plugin` element, add a configuration for your CloudHub 2.0 deployment, replacing the following placeholder values with your CloudHub 2.0 information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com MC ${environment} ${targetName} ${muleVersion} ${user} ${pass} ${appName} 1 1 ${publicUrl} true true ``` ## Deploy to CloudHub 2.0 From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` To deploy the artifact without rebuilding it, run: ```bash mvn mule:deploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into CloudHub 2.0. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to CloudHub 2.0 via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to CloudHub 2.0 To redeploy the application, run the same command as you did to deploy. CloudHub 2.0 rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub 2.0 username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub 2.0 Deployment Parameters Reference](#cloudhub2-deploy-reference). ## CloudHub 2.0 Deployment Parameters Reference
ParameterDescriptionRequired

cloudhub2Deployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub 2.0 instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to select a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.
Because Mule runtime 4.4 Standard Support ends in October 2024, new Mule apps can be deployed on either Mule 4.6 LTS or Mule 4.8 Edge. As LTS channel isn’t supported for customers using a Mule Maven plugin version 4.1.0 or earlier, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

scopeLoggingConfigurations

scopeLoggingConfiguration

scope

The package of the logging library to use.

logLevel

The log level. Accepted values: INFO, DEBUG, WARN, ERROR, FATAL.

Configuration example:

<scopeLoggingConfigurations>
  <scopeLoggingConfiguration>
    <scope>com.pkg.warning</scope>
    <logLevel>WARN</logLevel>
  </scopeLoggingConfiguration>
  <scopeLoggingConfiguration>
    <scope>com.pkg.debug</scope>
    <logLevel>DEBUG</logLevel>
  </scopeLoggingConfiguration>
</scopeLoggingConfigurations>

No

target

The CloudHub 2.0 target name to deploy the app to.
Specify either a shared space or a private space available in your Deployment Target values in CloudHub 2.0. See Features of CloudHub 2.0 for a detailed description on shared and private spaces. Use a target name value from the list of regions. For example, Cloudhub-US-East-1.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for CloudHub 2.0.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy.

Only when autoscaling is set to false.

vCores

The size of each replica specified in vCores. Accepted values: 0.1, 0.2, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4. See CloudHub 2.0 Replicas for a detailed description of available vCore sizes and their assigned hardware resources.
This parameter cannot be used if you configure instanceType.

Yes (Only when instanceType isn’t configured.)

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

If you redeploy the application and neither the properties nor the secureProperties element is configured in the deployment POM file, CloudHub 2.0 preserves the existing properties configured in your CloudHub 2.0 environment. If either element is present, CloudHub 2.0 deploys the application using only the properties and secure properties defined in the POM. It doesn’t merge them with values configured in Runtime Manager. Any existing properties that aren’t included in the deployment configuration are removed. To keep existing values, omit both elements, or send the full set of properties and secure properties on every redeploy.

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct CloudHub 2.0 to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

If you redeploy the application and neither the secureProperties nor the properties element is configured in the deployment POM file, CloudHub 2.0 preserves the existing secure properties configured in your CloudHub 2.0 environment. If either element is present, CloudHub 2.0 deploys the application using only the properties and secure properties defined in the POM. It doesn’t merge them with values configured in Runtime Manager. Any existing secure properties that aren’t included in the deployment configuration are removed. To keep existing values, omit both elements, or send the full set of properties and secure properties on every redeploy.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference.

No

integrations

services

objectStoreV2

enabled

When set to true, instructs the deployment to use Object Store v2.

Configuration example:

<integrations>
  <services>
    <objectStoreV2>
      <enabled>true</enabled>
    </objectStoreV2>
  </services>
</integrations>

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.
For high availability, set this value to true.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application. You can add multiple comma-separated values.

endpoint

Defines application endpoints by specifying the url, pathRewrite, and access attributes. Accepted values for access are internal and external.

pathRewrite

Supplies the base path expected by the HTTP listener in your application. This value must begin with /. This parameter is used only for applications that are deployed to private space.

lastMileSecurity

Enable Last-Mile security to perform TLS termination and decryption for forwarded HTTPS connections directly within the Mule application. This requires the Mule application to include an SSL certificate and consumes additional CPU resources. The default value is false.

forwardSslSession

Enables SSL forwarding during a session. The default value is false.

Mule Maven Plugin supports both publicUrl and endpoint for configuring application endpoints. Configure either publicUrl or endpoints, but not both in the same deployment configuration.

Configuration example:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.anypoint.com</publicUrl>
      <pathRewrite>/api</pathRewrite>
      <lastMileSecurity>true</lastMileSecurity>
      <forwardSslSession>true</forwardSslSession>
    </inbound>
  </http>
</deploymentSettings>

Example using endpoint:

<deploymentSettings>
  <http>
    <inbound>
      <endpoints>
        <endpoint>
          <url>https://test1.com/ch2testapp1</url>
          <pathRewrite>/</pathRewrite>
          <access>external</access>
        </endpoint>
      </endpoints>
    </inbound>
  </http>
</deploymentSettings>

generateDefaultPublicUrl

When set to true, CloudHub 2.0 generates a public URL for the deployed application.
This parameter is used only for applications that are deployed to private space. Applications that are deployed to shared space always get a generated public URL.

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. The default value is false.

tracingEnabled

Exposes tracing information in OpenTelemetry standard from Mule runtime into all APM solutions. See Enable Trace Data Collection.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>

instanceType

Specifies the capacity of the replica for application deployment. This flag is available only for organizations using a usage-based pricing (UBP) package. Non-UBP organizations use the vCores parameter instead. See Anypoint Platform Pricing.

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password aren’t set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) - [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) --- product: Mule Runtime version: 4.6 --- # Deploy Applications to CloudHub 2.0 Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to CloudHub 2.0, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub 2.0 deployment strategy in your project’s `pom.xml` file. ## Before You Begin - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). - The Mule Maven Facade API (v3) is added as a repository in the distribution management section of your project’s POM file. For example: ```xml Repository Corporate Repository https://maven.anypoint.mulesoft.com/api/v3/organizations/ORGANIZATION_ID/maven default ``` See [The Mule Maven Facade API documentation](https://anypoint.mulesoft.com/exchange/portals/anypoint-platform/f1e97bc6-315a-4490-82a7-23abe036327a.anypoint-platform/exchange-maven-facade-api-http/) for more information. ## Configure the CloudHub 2.0 Deployment Strategy Inside the `plugin` element, add a configuration for your CloudHub 2.0 deployment, replacing the following placeholder values with your CloudHub 2.0 information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com MC ${environment} ${targetName} ${muleVersion} ${user} ${pass} ${appName} 1 1 ${publicUrl} true true ``` ## Deploy to CloudHub 2.0 From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` To deploy the artifact without rebuilding it, run: ```bash mvn mule:deploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into CloudHub 2.0. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to CloudHub 2.0 via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to CloudHub 2.0 To redeploy the application, run the same command as you did to deploy. CloudHub 2.0 rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub 2.0 username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub 2.0 Deployment Parameters Reference](#cloudhub2-deploy-reference). ## CloudHub 2.0 Deployment Parameters Reference
ParameterDescriptionRequired

cloudhub2Deployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub 2.0 instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to select a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.
Because Mule runtime 4.4 Standard Support ends in October 2024, new Mule apps can be deployed on either Mule 4.6 LTS or Mule 4.8 Edge. As LTS channel isn’t supported for customers using a Mule Maven plugin version 4.1.0 or earlier, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

scopeLoggingConfigurations

scopeLoggingConfiguration

scope

The package of the logging library to use.

logLevel

The log level. Accepted values: INFO, DEBUG, WARN, ERROR, FATAL.

Configuration example:

<scopeLoggingConfigurations>
  <scopeLoggingConfiguration>
    <scope>com.pkg.warning</scope>
    <logLevel>WARN</logLevel>
  </scopeLoggingConfiguration>
  <scopeLoggingConfiguration>
    <scope>com.pkg.debug</scope>
    <logLevel>DEBUG</logLevel>
  </scopeLoggingConfiguration>
</scopeLoggingConfigurations>

No

target

The CloudHub 2.0 target name to deploy the app to.
Specify either a shared space or a private space available in your Deployment Target values in CloudHub 2.0. See Features of CloudHub 2.0 for a detailed description on shared and private spaces. Use a target name value from the list of regions. For example, Cloudhub-US-East-1.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for CloudHub 2.0.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy.

Only when autoscaling is set to false.

vCores

The size of each replica specified in vCores. Accepted values: 0.1, 0.2, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4. See CloudHub 2.0 Replicas for a detailed description of available vCore sizes and their assigned hardware resources.
This parameter cannot be used if you configure instanceType.

Yes (Only when instanceType isn’t configured.)

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

If you redeploy the application and neither the properties nor the secureProperties element is configured in the deployment POM file, CloudHub 2.0 preserves the existing properties configured in your CloudHub 2.0 environment. If either element is present, CloudHub 2.0 deploys the application using only the properties and secure properties defined in the POM. It doesn’t merge them with values configured in Runtime Manager. Any existing properties that aren’t included in the deployment configuration are removed. To keep existing values, omit both elements, or send the full set of properties and secure properties on every redeploy.

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct CloudHub 2.0 to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

If you redeploy the application and neither the secureProperties nor the properties element is configured in the deployment POM file, CloudHub 2.0 preserves the existing secure properties configured in your CloudHub 2.0 environment. If either element is present, CloudHub 2.0 deploys the application using only the properties and secure properties defined in the POM. It doesn’t merge them with values configured in Runtime Manager. Any existing secure properties that aren’t included in the deployment configuration are removed. To keep existing values, omit both elements, or send the full set of properties and secure properties on every redeploy.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference.

No

integrations

services

objectStoreV2

enabled

When set to true, instructs the deployment to use Object Store v2.

Configuration example:

<integrations>
  <services>
    <objectStoreV2>
      <enabled>true</enabled>
    </objectStoreV2>
  </services>
</integrations>

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.
For high availability, set this value to true.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application. You can add multiple comma-separated values.

endpoint

Defines application endpoints by specifying the url, pathRewrite, and access attributes. Accepted values for access are internal and external.

pathRewrite

Supplies the base path expected by the HTTP listener in your application. This value must begin with /. This parameter is used only for applications that are deployed to private space.

lastMileSecurity

Enable Last-Mile security to perform TLS termination and decryption for forwarded HTTPS connections directly within the Mule application. This requires the Mule application to include an SSL certificate and consumes additional CPU resources. The default value is false.

forwardSslSession

Enables SSL forwarding during a session. The default value is false.

Mule Maven Plugin supports both publicUrl and endpoint for configuring application endpoints. Configure either publicUrl or endpoints, but not both in the same deployment configuration.

Configuration example:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.anypoint.com</publicUrl>
      <pathRewrite>/api</pathRewrite>
      <lastMileSecurity>true</lastMileSecurity>
      <forwardSslSession>true</forwardSslSession>
    </inbound>
  </http>
</deploymentSettings>

Example using endpoint:

<deploymentSettings>
  <http>
    <inbound>
      <endpoints>
        <endpoint>
          <url>https://test1.com/ch2testapp1</url>
          <pathRewrite>/</pathRewrite>
          <access>external</access>
        </endpoint>
      </endpoints>
    </inbound>
  </http>
</deploymentSettings>

generateDefaultPublicUrl

When set to true, CloudHub 2.0 generates a public URL for the deployed application.
This parameter is used only for applications that are deployed to private space. Applications that are deployed to shared space always get a generated public URL.

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. The default value is false.

tracingEnabled

Exposes tracing information in OpenTelemetry standard from Mule runtime into all APM solutions. See Enable Trace Data Collection.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>

instanceType

Specifies the capacity of the replica for application deployment. This flag is available only for organizations using a usage-based pricing (UBP) package. Non-UBP organizations use the vCores parameter instead. See Anypoint Platform Pricing.

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password aren’t set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) - [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) --- product: Mule Runtime version: 4.9 --- # Deploy Applications to CloudHub 2.0 Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to CloudHub 2.0, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub 2.0 deployment strategy in your project’s `pom.xml` file. ## Before You Begin - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). - The Mule Maven Facade API (v3) is added as a repository in the distribution management section of your project’s POM file. For example: ```xml Repository Corporate Repository https://maven.anypoint.mulesoft.com/api/v3/organizations/ORGANIZATION_ID/maven default ``` See [The Mule Maven Facade API documentation](https://anypoint.mulesoft.com/exchange/portals/anypoint-platform/f1e97bc6-315a-4490-82a7-23abe036327a.anypoint-platform/exchange-maven-facade-api-http/) for more information. ## Configure the CloudHub 2.0 Deployment Strategy Inside the `plugin` element, add a configuration for your CloudHub 2.0 deployment, replacing the following placeholder values with your CloudHub 2.0 information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com MC ${environment} ${targetName} ${muleVersion} ${user} ${pass} ${appName} 1 1 ${publicUrl} true true ``` ## Deploy to CloudHub 2.0 From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` To deploy the artifact without rebuilding it, run: ```bash mvn mule:deploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into CloudHub 2.0. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to CloudHub 2.0 via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to CloudHub 2.0 To redeploy the application, run the same command as you did to deploy. CloudHub 2.0 rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub 2.0 username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub 2.0 Deployment Parameters Reference](#cloudhub2-deploy-reference). ## CloudHub 2.0 Deployment Parameters Reference
ParameterDescriptionRequired

cloudhub2Deployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub 2.0 instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to select a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.
Because Mule runtime 4.4 Standard Support ends in October 2024, new Mule apps can be deployed on either Mule 4.6 LTS or Mule 4.8 Edge. As LTS channel isn’t supported for customers using a Mule Maven plugin version 4.1.0 or earlier, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

scopeLoggingConfigurations

scopeLoggingConfiguration

scope

The package of the logging library to use.

logLevel

The log level. Accepted values: INFO, DEBUG, WARN, ERROR, FATAL.

Configuration example:

<scopeLoggingConfigurations>
  <scopeLoggingConfiguration>
    <scope>com.pkg.warning</scope>
    <logLevel>WARN</logLevel>
  </scopeLoggingConfiguration>
  <scopeLoggingConfiguration>
    <scope>com.pkg.debug</scope>
    <logLevel>DEBUG</logLevel>
  </scopeLoggingConfiguration>
</scopeLoggingConfigurations>

No

target

The CloudHub 2.0 target name to deploy the app to.
Specify either a shared space or a private space available in your Deployment Target values in CloudHub 2.0. See Features of CloudHub 2.0 for a detailed description on shared and private spaces. Use a target name value from the list of regions. For example, Cloudhub-US-East-1.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for CloudHub 2.0.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy.

Only when autoscaling is set to false.

vCores

The size of each replica specified in vCores. Accepted values: 0.1, 0.2, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4. See CloudHub 2.0 Replicas for a detailed description of available vCore sizes and their assigned hardware resources.
This parameter cannot be used if you configure instanceType.

Yes (Only when instanceType isn’t configured.)

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

If you must redeploy the application and there aren’t properties configured in the deployment POM file, the existing properties in your CloudHub 2.0 environment are kept. Note that if properties are defined in the POM file, the app is deployed using those properties and overrides any properties set in the UI.

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct CloudHub 2.0 to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference.

No

integrations

services

objectStoreV2

enabled

When set to true, instructs the deployment to use Object Store v2.

Configuration example:

<integrations>
  <services>
    <objectStoreV2>
      <enabled>true</enabled>
    </objectStoreV2>
  </services>
</integrations>

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.
For high availability, set this value to true.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application. You can add multiple comma-separated values.

endpoint

Defines application endpoints by specifying attributes such as url, pathRewrite, and access.

pathRewrite

Supplies the base path expected by the HTTP listener in your application. This value must begin with /. This parameter is used only for applications that are deployed to private space.

lastMileSecurity

Enable Last-Mile security to perform TLS termination and decryption for forwarded HTTPS connections directly within the Mule application. This requires the Mule application to include an SSL certificate and consumes additional CPU resources. The default value is false.

forwardSslSession

Enables SSL forwarding during a session. The default value is false.

Mule Maven Plugin supports both publicUrl and endpoint for configuring application endpoints. Configure either publicUrl or endpoints, but not both in the same deployment configuration.

Configuration example:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.anypoint.com</publicUrl>
      <pathRewrite>/api</pathRewrite>
      <lastMileSecurity>true</lastMileSecurity>
      <forwardSslSession>true</forwardSslSession>
    </inbound>
  </http>
</deploymentSettings>

Example using endpoint:

<deploymentSettings>
  <http>
    <inbound>
      <endpoints>
        <endpoint>
          <url>https://test1.com/ch2testapp1</url>
          <pathRewrite>/</pathRewrite>
          <access>external</access>
        </endpoint>
      </endpoints>
    </inbound>
  </http>
</deploymentSettings>

generateDefaultPublicUrl

When set to true, CloudHub 2.0 generates a public URL for the deployed application.
This parameter is used only for applications that are deployed to private space. Applications that are deployed to shared space always get a generated public URL.

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. The default value is false.

tracingEnabled

Exposes tracing information in OpenTelemetry standard from Mule runtime into all APM solutions. See Enable Trace Data Collection.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>

instanceType

Specifies the capacity of the replica for application deployment. This flag is available only for organizations using a usage-based pricing (UBP) package. Non-UBP organizations use the vCores parameter instead. See Anypoint Platform Pricing.

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password aren’t set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) - [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Deploy Applications to CloudHub 2.0 Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to CloudHub 2.0, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub 2.0 deployment strategy in your project’s `pom.xml` file. ## Before You Begin - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). - The Mule Maven Facade API (v3) is added as a repository in the distribution management section of your project’s POM file. For example: ```xml Repository Corporate Repository https://maven.anypoint.mulesoft.com/api/v3/organizations/ORGANIZATION_ID/maven default ``` See [The Mule Maven Facade API documentation](https://anypoint.mulesoft.com/exchange/portals/anypoint-platform/f1e97bc6-315a-4490-82a7-23abe036327a.anypoint-platform/exchange-maven-facade-api-http/) for more information. ## Configure the CloudHub 2.0 Deployment Strategy Inside the `plugin` element, add a configuration for your CloudHub 2.0 deployment, replacing the following placeholder values with your CloudHub 2.0 information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com MC ${environment} ${targetName} ${muleVersion} ${user} ${pass} ${appName} 1 1 ${publicUrl} true true ``` ## Deploy to CloudHub 2.0 From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` To deploy the artifact without rebuilding it, run: ```bash mvn mule:deploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into CloudHub 2.0. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to CloudHub 2.0 via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to CloudHub 2.0 To redeploy the application, run the same command as you did to deploy. CloudHub 2.0 rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub 2.0 username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub 2.0 Deployment Parameters Reference](#cloudhub2-deploy-reference). ## CloudHub 2.0 Deployment Parameters Reference
ParameterDescriptionRequired

cloudhub2Deployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub 2.0 instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to select a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.
Because Mule runtime 4.4 Standard Support ends in October 2024, new Mule apps can be deployed on either Mule 4.6 LTS or Mule 4.8 Edge. As LTS channel isn’t supported for customers using a Mule Maven plugin version 4.1.0 or earlier, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

scopeLoggingConfigurations

scopeLoggingConfiguration

scope

The package of the logging library to use.

logLevel

The log level. Accepted values: INFO, DEBUG, WARN, ERROR, FATAL.

Configuration example:

<scopeLoggingConfigurations>
  <scopeLoggingConfiguration>
    <scope>com.pkg.warning</scope>
    <logLevel>WARN</logLevel>
  </scopeLoggingConfiguration>
  <scopeLoggingConfiguration>
    <scope>com.pkg.debug</scope>
    <logLevel>DEBUG</logLevel>
  </scopeLoggingConfiguration>
</scopeLoggingConfigurations>

No

target

The CloudHub 2.0 target name to deploy the app to.
Specify either a shared space or a private space available in your Deployment Target values in CloudHub 2.0. See Features of CloudHub 2.0 for a detailed description on shared and private spaces. Use a target name value from the list of regions. For example, Cloudhub-US-East-1.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for CloudHub 2.0.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy.

Only when autoscaling is set to false.

vCores

The size of each replica specified in vCores. Accepted values: 0.1, 0.2, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4. See CloudHub 2.0 Replicas for a detailed description of available vCore sizes and their assigned hardware resources.
This parameter cannot be used if you configure instanceType.

Yes (Only when instanceType isn’t configured.)

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

If you redeploy the application and neither the properties nor the secureProperties element is configured in the deployment POM file, CloudHub 2.0 preserves the existing properties configured in your CloudHub 2.0 environment. If either element is present, CloudHub 2.0 deploys the application using only the properties and secure properties defined in the POM. It doesn’t merge them with values configured in Runtime Manager. Any existing properties that aren’t included in the deployment configuration are removed. To keep existing values, omit both elements, or send the full set of properties and secure properties on every redeploy.

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct CloudHub 2.0 to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

If you redeploy the application and neither the secureProperties nor the properties element is configured in the deployment POM file, CloudHub 2.0 preserves the existing secure properties configured in your CloudHub 2.0 environment. If either element is present, CloudHub 2.0 deploys the application using only the properties and secure properties defined in the POM. It doesn’t merge them with values configured in Runtime Manager. Any existing secure properties that aren’t included in the deployment configuration are removed. To keep existing values, omit both elements, or send the full set of properties and secure properties on every redeploy.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference.

No

integrations

services

objectStoreV2

enabled

When set to true, instructs the deployment to use Object Store v2.

Configuration example:

<integrations>
  <services>
    <objectStoreV2>
      <enabled>true</enabled>
    </objectStoreV2>
  </services>
</integrations>

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.
For high availability, set this value to true.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application. You can add multiple comma-separated values.

endpoint

Defines application endpoints by specifying the url, pathRewrite, and access attributes. Accepted values for access are internal and external.

pathRewrite

Supplies the base path expected by the HTTP listener in your application. This value must begin with /. This parameter is used only for applications that are deployed to private space.

lastMileSecurity

Enable Last-Mile security to perform TLS termination and decryption for forwarded HTTPS connections directly within the Mule application. This requires the Mule application to include an SSL certificate and consumes additional CPU resources. The default value is false.

forwardSslSession

Enables SSL forwarding during a session. The default value is false.

Mule Maven Plugin supports both publicUrl and endpoint for configuring application endpoints. Configure either publicUrl or endpoints, but not both in the same deployment configuration.

Configuration example:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.anypoint.com</publicUrl>
      <pathRewrite>/api</pathRewrite>
      <lastMileSecurity>true</lastMileSecurity>
      <forwardSslSession>true</forwardSslSession>
    </inbound>
  </http>
</deploymentSettings>

Example using endpoint:

<deploymentSettings>
  <http>
    <inbound>
      <endpoints>
        <endpoint>
          <url>https://test1.com/ch2testapp1</url>
          <pathRewrite>/</pathRewrite>
          <access>external</access>
        </endpoint>
      </endpoints>
    </inbound>
  </http>
</deploymentSettings>

generateDefaultPublicUrl

When set to true, CloudHub 2.0 generates a public URL for the deployed application.
This parameter is used only for applications that are deployed to private space. Applications that are deployed to shared space always get a generated public URL.

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. The default value is false.

tracingEnabled

Exposes tracing information in OpenTelemetry standard from Mule runtime into all APM solutions. See Enable Trace Data Collection.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>

instanceType

Specifies the capacity of the replica for application deployment. This flag is available only for organizations using a usage-based pricing (UBP) package. Non-UBP organizations use the vCores parameter instead. See Anypoint Platform Pricing.

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password aren’t set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) - [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) --- product: Mule Runtime version: 4.11 --- # Deploy Applications to CloudHub Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications to CloudHub, you can also deploy, redeploy, or undeploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to CloudHub using a different method, see: - [Deploy Applications to CloudHub Using Anypoint Studio](https://docs.mulesoft.com/studio/deploy-mule-application-task) - [Deploy Applications to CloudHub Using the Anypoint CLI](https://docs.mulesoft.com/anypoint-cli/latest/cloudhub-apps#deploy-to-cloudhub) - [Deploy Applications to CloudHub Using Runtime Manager](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub) ## Prerequisites Before you can deploy to CloudHub using the Mule Maven plugin, you must complete the following tasks: - Add the Mule Maven plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/4.11/mmp-concept#add-mmp) for instructions. - If you are using the HTTP Listener as source for your flow, you need to set its host to **0.0.0.0** and its port to **${http.port}** - Declare all external classes and resources in the `exportedPackages` and `exportedResources` fields on the `mule-artifact.json` file ## Configure the CloudHub Deployment Strategy Configure the CloudHub deployment strategy in your project’s `pom.xml` file so you can deploy, redeploy and undeploy your Mule application using the Mule Maven plugin. Inside the `plugin` element in your project’s `pom.xml` file, configure your CloudHub deployment, replacing the placeholder values with your CloudHub information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com ${app.runtime} ${username} ${password} ${cloudhub.application.name} ${environment} ${region} ${workers} ${workerType} value ``` ## Deploy to CloudHub From the command line in your project’s folder, package the app and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ## Redeploy to CloudHub To redeploy a Mule application using Mule Maven plugin, run `mvn clean deploy -DmuleDeploy` as you did to previously deploy the app. CloudHub rewrites the app you had deployed. ## Undeploy from CloudHub To undeploy a Mule application using Mule Maven plugin, run the following command: ```console mvn mule:undeploy ``` The undeploy command also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub Deployment Reference](#cloudhub-deploy-reference). ## CloudHub Deployment Reference The following table shows the available parameters to configure the CloudHub deployment strategy in your project’s `pom.xml` file.
ParameterDescriptionRequired

cloudHubDeployment

Top-level element

Yes

uri

Your Anypoint Platform URI
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application.
Example value: 4.3.0
Starting with Mule 4.5, deployments to CloudHub accept the Mule version exact name or the semantic versioning, which deploys the latest version of Mule runtime.
Example values: 4.6, 4.6-e-java8 (Edge), 4.6-e-java17 (Edge), 4.6-java8 (LTS), 4.6-java17 (LTS)
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, MuleSoft doesn’t guarantee support for LTS channel. We recommend that you use Mule Maven plugin version 4.1.1 or later. For example, specifying <muleVersion>4.6-java17</muleVersion> in the plugin 3.8.0 or 4.0.0 deploys the application with an Edge release channel and a Java 8 selection. To specify releaseChannel and javaVersion, upgrade the plugin to version 4.1.1 or later.

Yes

releaseChannel

Set the name of the release channel to use for the selected Mule version. Supported values are NONE, EDGE, and LTS. If you don’t specify a Mule version, the default Mule version for the selected release channel is used. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the name of the Java version to use for the selected Mule version. Supported values are 8 and 17. If you don’t specify a Mule version, the default Mule version for the selected Java version is used. If the Java version you select isn’t available for the specified Mule version, an error occurs.

No

username

Your CloudHub username

Only when using Anypoint Platform credentials to login.

password

Your CloudHub password

Only when using Anypoint Platform credentials to login.

applicationName

The name of your application in CloudHub
This name is part of the domain of your deployed app. For example, naming your application application-1 makes your app’s public domain application-1.cloudhub.io.

Yes

artifact

The absolute path of the JAR file to be deployed
If not set, the path defaults to the location of the JAR file generated at the package phase.

No

environment

The CloudHub environment to which you want to deploy
This value must match any environment configured in your CloudHub account.

<environment>Sandbox</environment>

Yes

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

workers

The number of workers
By default, this value is 1.

No

workerType

Size of each worker; one of the following values:

  • MICRO (default; 0.1 vCores)

  • SMALL (0.2 vCores)

  • MEDIUM (1 vCore )

  • LARGE (2 vCores)

  • XLARGE (4 vCores)

  • XXLARGE (8 vCores)

  • 4XLARGE (16 vCores)

No

region

Region of worker clouds; one of the following values:

  • us-east-1 (default; US East, N. Virginia)

  • us-east-2 (US East, Ohio)

  • us-west-1 (US West, N. California)

  • us-west-2 (US West, Oregon)

  • us-gov-west-1 (MuleSoft Government Cloud)

  • eu-central-1 (EU, Frankfurt)

  • eu-west-1 (EU, Ireland)

  • eu-west-2 (UK, London)

  • ap-southeast-1 (Asia Pacific, Singapore)

  • ap-southeast-2 (Asia Pacific, Sydney)

  • ap-northeast-1 (Asia Pacific, Tokyo)

  • ca-central-1 (Canada, Central)

  • sa-east-1 (South America, São Paulo)

No

objectStoreV2

Enables Object Store V2
By default, this value is set to true to match the Runtime Manager configuration of OSv2.

No

persistentQueues

Enables persistent queues
By default, it is set to false.

No

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

applyLatestRuntimePatch

When set to true, the plugin instructs CloudHub to update the worker to the latest available patch for the Mule runtime engine version specified in the deployment configuration, and then deploys the application.
By default, it is set to false.

No

disableCloudHubLogs

When set to true, the plugin instructs CloudHub to disable CloudHub logging and instead use the application configured in the log4j2.xml file.
By default, it is set to false.

No

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.11/mmp-concept) - [Export Resources](https://docs.mulesoft.com/mule-runtime/4.11/how-to-export-resources) --- product: Mule Runtime version: 4.12 --- # Deploy Applications to CloudHub Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications to CloudHub, you can also deploy, redeploy, or undeploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to CloudHub using a different method, see: - [Deploy Applications to CloudHub Using Anypoint Studio](https://docs.mulesoft.com/studio/deploy-mule-application-task) - [Deploy Applications to CloudHub Using the Anypoint CLI](https://docs.mulesoft.com/anypoint-cli/latest/cloudhub-apps#deploy-to-cloudhub) - [Deploy Applications to CloudHub Using Runtime Manager](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub) ## Prerequisites Before you can deploy to CloudHub using the Mule Maven plugin, you must complete the following tasks: - Add the Mule Maven plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/4.12/mmp-concept#add-mmp) for instructions. - If you are using the HTTP Listener as source for your flow, you need to set its host to **0.0.0.0** and its port to **${http.port}** - Declare all external classes and resources in the `exportedPackages` and `exportedResources` fields on the `mule-artifact.json` file ## Configure the CloudHub Deployment Strategy Configure the CloudHub deployment strategy in your project’s `pom.xml` file so you can deploy, redeploy and undeploy your Mule application using the Mule Maven plugin. Inside the `plugin` element in your project’s `pom.xml` file, configure your CloudHub deployment, replacing the placeholder values with your CloudHub information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com ${app.runtime} ${username} ${password} ${cloudhub.application.name} ${environment} ${region} ${workers} ${workerType} value ``` ## Deploy to CloudHub From the command line in your project’s folder, package the app and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ## Redeploy to CloudHub To redeploy a Mule application using Mule Maven plugin, run `mvn clean deploy -DmuleDeploy` as you did to previously deploy the app. CloudHub rewrites the app you had deployed. ## Undeploy from CloudHub To undeploy a Mule application using Mule Maven plugin, run the following command: ```console mvn mule:undeploy ``` The undeploy command also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub Deployment Reference](#cloudhub-deploy-reference). ## CloudHub Deployment Reference The following table shows the available parameters to configure the CloudHub deployment strategy in your project’s `pom.xml` file.
ParameterDescriptionRequired

cloudHubDeployment

Top-level element

Yes

uri

Your Anypoint Platform URI
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application.
Example value: 4.3.0
Starting with Mule 4.5, deployments to CloudHub accept the Mule version exact name or the semantic versioning, which deploys the latest version of Mule runtime.
Example values: 4.6, 4.6-e-java8 (Edge), 4.6-e-java17 (Edge), 4.6-java8 (LTS), 4.6-java17 (LTS)
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, MuleSoft doesn’t guarantee support for LTS channel. We recommend that you use Mule Maven plugin version 4.1.1 or later. For example, specifying <muleVersion>4.6-java17</muleVersion> in the plugin 3.8.0 or 4.0.0 deploys the application with an Edge release channel and a Java 8 selection. To specify releaseChannel and javaVersion, upgrade the plugin to version 4.1.1 or later.

Yes

releaseChannel

Set the name of the release channel to use for the selected Mule version. Supported values are NONE, EDGE, and LTS. If you don’t specify a Mule version, the default Mule version for the selected release channel is used. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the name of the Java version to use for the selected Mule version. Supported values are 8 and 17. If you don’t specify a Mule version, the default Mule version for the selected Java version is used. If the Java version you select isn’t available for the specified Mule version, an error occurs.

No

username

Your CloudHub username

Only when using Anypoint Platform credentials to login.

password

Your CloudHub password

Only when using Anypoint Platform credentials to login.

applicationName

The name of your application in CloudHub
This name is part of the domain of your deployed app. For example, naming your application application-1 makes your app’s public domain application-1.cloudhub.io.

Yes

artifact

The absolute path of the JAR file to be deployed
If not set, the path defaults to the location of the JAR file generated at the package phase.

No

environment

The CloudHub environment to which you want to deploy
This value must match any environment configured in your CloudHub account.

<environment>Sandbox</environment>

Yes

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

workers

The number of workers
By default, this value is 1.

No

workerType

Size of each worker; one of the following values:

  • MICRO (default; 0.1 vCores)

  • SMALL (0.2 vCores)

  • MEDIUM (1 vCore )

  • LARGE (2 vCores)

  • XLARGE (4 vCores)

  • XXLARGE (8 vCores)

  • 4XLARGE (16 vCores)

No

region

Region of worker clouds; one of the following values:

  • us-east-1 (default; US East, N. Virginia)

  • us-east-2 (US East, Ohio)

  • us-west-1 (US West, N. California)

  • us-west-2 (US West, Oregon)

  • us-gov-west-1 (MuleSoft Government Cloud)

  • eu-central-1 (EU, Frankfurt)

  • eu-west-1 (EU, Ireland)

  • eu-west-2 (UK, London)

  • ap-southeast-1 (Asia Pacific, Singapore)

  • ap-southeast-2 (Asia Pacific, Sydney)

  • ap-northeast-1 (Asia Pacific, Tokyo)

  • ca-central-1 (Canada, Central)

  • sa-east-1 (South America, São Paulo)

No

objectStoreV2

Enables Object Store V2
By default, this value is set to true to match the Runtime Manager configuration of OSv2.

No

persistentQueues

Enables persistent queues
By default, it is set to false.

No

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

applyLatestRuntimePatch

When set to true, the plugin instructs CloudHub to update the worker to the latest available patch for the Mule runtime engine version specified in the deployment configuration, and then deploys the application.
By default, it is set to false.

No

disableCloudHubLogs

When set to true, the plugin instructs CloudHub to disable CloudHub logging and instead use the application configured in the log4j2.xml file.
By default, it is set to false.

No

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.12/mmp-concept) - [Export Resources](https://docs.mulesoft.com/mule-runtime/4.12/how-to-export-resources) --- product: Mule Runtime version: 4.3 --- # Deploy Applications to CloudHub Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications to CloudHub, you can also deploy, redeploy, or undeploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to CloudHub using a different method, see: - [Deploy Applications to CloudHub Using Anypoint Studio](https://docs.mulesoft.com/studio/deploy-mule-application-task) - [Deploy Applications to CloudHub Using the Anypoint CLI](https://docs.mulesoft.com/anypoint-cli/latest/cloudhub-apps#deploy-to-cloudhub) - [Deploy Applications to CloudHub Using Runtime Manager](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub) ## Prerequisites Before you can deploy to CloudHub using the Mule Maven plugin, you must complete the following tasks: - Add the Mule Maven plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/4.3/mmp-concept#add-mmp) for instructions. - If you are using the HTTP Listener as source for your flow, you need to set its host to **0.0.0.0** and its port to **${http.port}** - Declare all external classes and resources in the `exportedPackages` and `exportedResources` fields on the `mule-artifact.json` file ## Configure the CloudHub Deployment Strategy Configure the CloudHub deployment strategy in your project’s `pom.xml` file so you can deploy, redeploy and undeploy your Mule application using the Mule Maven plugin. Inside the `plugin` element in your project’s `pom.xml` file, configure your CloudHub deployment, replacing the placeholder values with your CloudHub information: ```xml org.mule.tools.maven mule-maven-plugin 3.4.2 true https://anypoint.mulesoft.com ${app.runtime} ${username} ${password} ${cloudhub.application.name} ${environment} ${region} ${workers} ${workerType} value ``` ## Deploy to CloudHub From the command line in your project’s folder, package the app and execute the deploy goal: ```console mvn clean package deploy -DmuleDeploy ``` ## Redeploy to CloudHub To redeploy a Mule application using Mule Maven plugin, run `mvn clean package deploy -DmuleDeploy` as you did to previously deploy the app. CloudHub rewrites the app you had deployed. ## Undeploy from CloudHub To undeploy a Mule application using Mule Maven plugin, run the following command: ```console mvn mule:undeploy ``` The undeploy command also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub Deployment Reference](#cloudhub-deploy-reference). ## CloudHub Deployment Reference The following table shows the available parameters to configure the CloudHub deployment strategy in your project’s `pom.xml` file.
ParameterDescriptionRequired

cloudHubDeployment

Top-level element

Yes

uri

Your Anypoint Platform URI
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application.
Example values: 4.3.0, 4.2.2-hf4

Yes

username

Your CloudHub username

Only when using Anypoint Platform credentials to login.

password

Your CloudHub password

Only when using Anypoint Platform credentials to login.

applicationName

The name of your application in CloudHub
This name is part of the domain of your deployed app. For example, naming your application application-1 makes your app’s public domain application-1.cloudhub.io.

Yes

artifact

The absolute path of the JAR file to be deployed
If not set, the path defaults to the location of the JAR file generated at the package phase.

No

environment

The CloudHub environment to which you want to deploy
This value must match any environment configured in your CloudHub account.

<environment>Sandbox</environment>

Yes

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

workers

The number of workers
By default, this value is 1.

No

workerType

Size of each worker; one of the following values:

  • MICRO (default; 0.1 vCores)

  • SMALL (0.2 vCores)

  • MEDIUM (1 vCore )

  • LARGE (2 vCores)

  • XLARGE (4 vCores)

  • XXLARGE (8 vCores)

  • 4XLARGE (16 vCores)

No

region

Region of worker clouds; one of the following values:

  • us-east-1 (default; US East, N. Virginia)

  • us-east-2 (US East, Ohio)

  • us-west-1 (US West, N. California)

  • us-west-2 (US West, Oregon)

  • us-gov-west-1 (MuleSoft Government Cloud)

  • eu-central-1 (EU, Frankfurt)

  • eu-west-1 (EU, Ireland)

  • eu-west-2 (EU, London)

  • ap-southeast-1 (Asia Pacific, Singapore)

  • ap-southeast-2 (Asia Pacific, Sydney)

  • ap-northeast-1 (Asia Pacific, Tokyo)

  • ca-central-1 (Canada, Central)

  • sa-east-1 (South America, São Paulo)

No

objectStoreV2

Enables Object Store V2
By default, this value is set to true to match the Runtime Manager configuration of OSv2.
This parameter is available in plugin version 3.3.3 and later.

No

persistentQueues

Enables persistent queues
By default, it is set to false.

No

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

applyLatestRuntimePatch

When set to true, the plugin instructs CloudHub to update the worker to the latest available patch for the Mule runtime engine version specified in the deployment configuration, and then deploys the application.
By default, it is set to false.

No

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.3/mmp-concept) - [Export Resources](https://docs.mulesoft.com/mule-runtime/4.3/how-to-export-resources) --- product: Mule Runtime version: 4.4 --- # Deploy Applications to CloudHub Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications to CloudHub, you can also deploy, redeploy, or undeploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to CloudHub using a different method, see: - [Deploy Applications to CloudHub Using Anypoint Studio](https://docs.mulesoft.com/studio/deploy-mule-application-task) - [Deploy Applications to CloudHub Using the Anypoint CLI](https://docs.mulesoft.com/anypoint-cli/latest/cloudhub-apps#deploy-to-cloudhub) - [Deploy Applications to CloudHub Using Runtime Manager](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub) ## Prerequisites Before you can deploy to CloudHub using the Mule Maven plugin, you must complete the following tasks: - Add the Mule Maven plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/4.4/mmp-concept#add-mmp) for instructions. - If you are using the HTTP Listener as source for your flow, you need to set its host to **0.0.0.0** and its port to **${http.port}** - Declare all external classes and resources in the `exportedPackages` and `exportedResources` fields on the `mule-artifact.json` file ## Configure the CloudHub Deployment Strategy Configure the CloudHub deployment strategy in your project’s `pom.xml` file so you can deploy, redeploy and undeploy your Mule application using the Mule Maven plugin. Inside the `plugin` element in your project’s `pom.xml` file, configure your CloudHub deployment, replacing the placeholder values with your CloudHub information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com ${app.runtime} ${username} ${password} ${cloudhub.application.name} ${environment} ${region} ${workers} ${workerType} value ``` ## Deploy to CloudHub From the command line in your project’s folder, package the app and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ## Redeploy to CloudHub To redeploy a Mule application using Mule Maven plugin, run `mvn clean deploy -DmuleDeploy` as you did to previously deploy the app. CloudHub rewrites the app you had deployed. ## Undeploy from CloudHub To undeploy a Mule application using Mule Maven plugin, run the following command: ```console mvn mule:undeploy ``` The undeploy command also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub Deployment Reference](#cloudhub-deploy-reference). ## CloudHub Deployment Reference The following table shows the available parameters to configure the CloudHub deployment strategy in your project’s `pom.xml` file.
ParameterDescriptionRequired

cloudHubDeployment

Top-level element

Yes

uri

Your Anypoint Platform URI
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application.
Example value: 4.3.0

Starting with Mule 4.5, deployments to CloudHub require Major.Minor version, which deploys the latest version of Mule runtime. Example value: 4.5

Yes

username

Your CloudHub username

Only when using Anypoint Platform credentials to login.

password

Your CloudHub password

Only when using Anypoint Platform credentials to login.

applicationName

The name of your application in CloudHub
This name is part of the domain of your deployed app. For example, naming your application application-1 makes your app’s public domain application-1.cloudhub.io.

Yes

artifact

The absolute path of the JAR file to be deployed
If not set, the path defaults to the location of the JAR file generated at the package phase.

No

environment

The CloudHub environment to which you want to deploy
This value must match any environment configured in your CloudHub account.

<environment>Sandbox</environment>

Yes

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

workers

The number of workers
By default, this value is 1.

No

workerType

Size of each worker; one of the following values:

  • MICRO (default; 0.1 vCores)

  • SMALL (0.2 vCores)

  • MEDIUM (1 vCore )

  • LARGE (2 vCores)

  • XLARGE (4 vCores)

  • XXLARGE (8 vCores)

  • 4XLARGE (16 vCores)

No

region

Region of worker clouds; one of the following values:

  • us-east-1 (default; US East, N. Virginia)

  • us-east-2 (US East, Ohio)

  • us-west-1 (US West, N. California)

  • us-west-2 (US West, Oregon)

  • us-gov-west-1 (MuleSoft Government Cloud)

  • eu-central-1 (EU, Frankfurt)

  • eu-west-1 (EU, Ireland)

  • eu-west-2 (UK, London)

  • ap-southeast-1 (Asia Pacific, Singapore)

  • ap-southeast-2 (Asia Pacific, Sydney)

  • ap-northeast-1 (Asia Pacific, Tokyo)

  • ca-central-1 (Canada, Central)

  • sa-east-1 (South America, São Paulo)

No

objectStoreV2

Enables Object Store V2
By default, this value is set to true to match the Runtime Manager configuration of OSv2.

No

persistentQueues

Enables persistent queues
By default, it is set to false.

No

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

applyLatestRuntimePatch

When set to true, the plugin instructs CloudHub to update the worker to the latest available patch for the Mule runtime engine version specified in the deployment configuration, and then deploys the application.
By default, it is set to false.

No

disableCloudHubLogs

When set to true, the plugin instructs CloudHub to disable CloudHub logging and instead use the application configured in the log4j2.xml file.
By default, it is set to false.
This parameter is available in plugin version 3.8.1 and later.

No

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.4/mmp-concept) - [Export Resources](https://docs.mulesoft.com/mule-runtime/4.4/how-to-export-resources) --- product: Mule Runtime version: 4.6 --- # Deploy Applications to CloudHub Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications to CloudHub, you can also deploy, redeploy, or undeploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to CloudHub using a different method, see: - [Deploy Applications to CloudHub Using Anypoint Studio](https://docs.mulesoft.com/studio/deploy-mule-application-task) - [Deploy Applications to CloudHub Using the Anypoint CLI](https://docs.mulesoft.com/anypoint-cli/latest/cloudhub-apps#deploy-to-cloudhub) - [Deploy Applications to CloudHub Using Runtime Manager](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub) ## Prerequisites Before you can deploy to CloudHub using the Mule Maven plugin, you must complete the following tasks: - Add the Mule Maven plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/4.6/mmp-concept#add-mmp) for instructions. - If you are using the HTTP Listener as source for your flow, you need to set its host to **0.0.0.0** and its port to **${http.port}** - Declare all external classes and resources in the `exportedPackages` and `exportedResources` fields on the `mule-artifact.json` file ## Configure the CloudHub Deployment Strategy Configure the CloudHub deployment strategy in your project’s `pom.xml` file so you can deploy, redeploy and undeploy your Mule application using the Mule Maven plugin. Inside the `plugin` element in your project’s `pom.xml` file, configure your CloudHub deployment, replacing the placeholder values with your CloudHub information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com ${app.runtime} ${username} ${password} ${cloudhub.application.name} ${environment} ${region} ${workers} ${workerType} value ``` ## Deploy to CloudHub From the command line in your project’s folder, package the app and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ## Redeploy to CloudHub To redeploy a Mule application using Mule Maven plugin, run `mvn clean deploy -DmuleDeploy` as you did to previously deploy the app. CloudHub rewrites the app you had deployed. ## Undeploy from CloudHub To undeploy a Mule application using Mule Maven plugin, run the following command: ```console mvn mule:undeploy ``` The undeploy command also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub Deployment Reference](#cloudhub-deploy-reference). ## CloudHub Deployment Reference The following table shows the available parameters to configure the CloudHub deployment strategy in your project’s `pom.xml` file.
ParameterDescriptionRequired

cloudHubDeployment

Top-level element

Yes

uri

Your Anypoint Platform URI
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application.
Example value: 4.3.0
Starting with Mule 4.5, deployments to CloudHub accept the Mule version exact name or the semantic versioning, which deploys the latest version of Mule runtime.
Example values: 4.6, 4.6-e-java8 (Edge), 4.6-e-java17 (Edge), 4.6-java8 (LTS), 4.6-java17 (LTS)
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, MuleSoft doesn’t guarantee support for LTS channel. We recommend that you use Mule Maven plugin version 4.1.1 or later. For example, specifying <muleVersion>4.6-java17</muleVersion> in the plugin 3.8.0 or 4.0.0 deploys the application with an Edge release channel and a Java 8 selection. To specify releaseChannel and javaVersion, upgrade the plugin to version 4.1.1 or later.

Yes

releaseChannel

Set the name of the release channel to use for the selected Mule version. Supported values are NONE, EDGE, and LTS. If you don’t specify a Mule version, the default Mule version for the selected release channel is used. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the name of the Java version to use for the selected Mule version. Supported values are 8 and 17. If you don’t specify a Mule version, the default Mule version for the selected Java version is used. If the Java version you select isn’t available for the specified Mule version, an error occurs.

No

username

Your CloudHub username

Only when using Anypoint Platform credentials to login.

password

Your CloudHub password

Only when using Anypoint Platform credentials to login.

applicationName

The name of your application in CloudHub
This name is part of the domain of your deployed app. For example, naming your application application-1 makes your app’s public domain application-1.cloudhub.io.

Yes

artifact

The absolute path of the JAR file to be deployed
If not set, the path defaults to the location of the JAR file generated at the package phase.

No

environment

The CloudHub environment to which you want to deploy
This value must match any environment configured in your CloudHub account.

<environment>Sandbox</environment>

Yes

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

workers

The number of workers
By default, this value is 1.

No

workerType

Size of each worker; one of the following values:

  • MICRO (default; 0.1 vCores)

  • SMALL (0.2 vCores)

  • MEDIUM (1 vCore )

  • LARGE (2 vCores)

  • XLARGE (4 vCores)

  • XXLARGE (8 vCores)

  • 4XLARGE (16 vCores)

No

region

Region of worker clouds; one of the following values:

  • us-east-1 (default; US East, N. Virginia)

  • us-east-2 (US East, Ohio)

  • us-west-1 (US West, N. California)

  • us-west-2 (US West, Oregon)

  • us-gov-west-1 (MuleSoft Government Cloud)

  • eu-central-1 (EU, Frankfurt)

  • eu-west-1 (EU, Ireland)

  • eu-west-2 (UK, London)

  • ap-southeast-1 (Asia Pacific, Singapore)

  • ap-southeast-2 (Asia Pacific, Sydney)

  • ap-northeast-1 (Asia Pacific, Tokyo)

  • ca-central-1 (Canada, Central)

  • sa-east-1 (South America, São Paulo)

No

objectStoreV2

Enables Object Store V2
By default, this value is set to true to match the Runtime Manager configuration of OSv2.

No

persistentQueues

Enables persistent queues
By default, it is set to false.

No

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

applyLatestRuntimePatch

When set to true, the plugin instructs CloudHub to update the worker to the latest available patch for the Mule runtime engine version specified in the deployment configuration, and then deploys the application.
By default, it is set to false.

No

disableCloudHubLogs

When set to true, the plugin instructs CloudHub to disable CloudHub logging and instead use the application configured in the log4j2.xml file.
By default, it is set to false.

No

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.6/mmp-concept) - [Export Resources](https://docs.mulesoft.com/mule-runtime/4.6/how-to-export-resources) --- product: Mule Runtime version: 4.9 --- # Deploy Applications to CloudHub Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications to CloudHub, you can also deploy, redeploy, or undeploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to CloudHub using a different method, see: - [Deploy Applications to CloudHub Using Anypoint Studio](https://docs.mulesoft.com/studio/deploy-mule-application-task) - [Deploy Applications to CloudHub Using the Anypoint CLI](https://docs.mulesoft.com/anypoint-cli/latest/cloudhub-apps#deploy-to-cloudhub) - [Deploy Applications to CloudHub Using Runtime Manager](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub) ## Prerequisites Before you can deploy to CloudHub using the Mule Maven plugin, you must complete the following tasks: - Add the Mule Maven plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/4.9/mmp-concept#add-mmp) for instructions. - If you are using the HTTP Listener as source for your flow, you need to set its host to **0.0.0.0** and its port to **${http.port}** - Declare all external classes and resources in the `exportedPackages` and `exportedResources` fields on the `mule-artifact.json` file ## Configure the CloudHub Deployment Strategy Configure the CloudHub deployment strategy in your project’s `pom.xml` file so you can deploy, redeploy and undeploy your Mule application using the Mule Maven plugin. Inside the `plugin` element in your project’s `pom.xml` file, configure your CloudHub deployment, replacing the placeholder values with your CloudHub information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com ${app.runtime} ${username} ${password} ${cloudhub.application.name} ${environment} ${region} ${workers} ${workerType} value ``` ## Deploy to CloudHub From the command line in your project’s folder, package the app and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ## Redeploy to CloudHub To redeploy a Mule application using Mule Maven plugin, run `mvn clean deploy -DmuleDeploy` as you did to previously deploy the app. CloudHub rewrites the app you had deployed. ## Undeploy from CloudHub To undeploy a Mule application using Mule Maven plugin, run the following command: ```console mvn mule:undeploy ``` The undeploy command also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub Deployment Reference](#cloudhub-deploy-reference). ## CloudHub Deployment Reference The following table shows the available parameters to configure the CloudHub deployment strategy in your project’s `pom.xml` file.
ParameterDescriptionRequired

cloudHubDeployment

Top-level element

Yes

uri

Your Anypoint Platform URI
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application.
Example value: 4.3.0
Starting with Mule 4.5, deployments to CloudHub accept the Mule version exact name or the semantic versioning, which deploys the latest version of Mule runtime.
Example values: 4.6, 4.6-e-java8 (Edge), 4.6-e-java17 (Edge), 4.6-java8 (LTS), 4.6-java17 (LTS)
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, MuleSoft doesn’t guarantee support for LTS channel. We recommend that you use Mule Maven plugin version 4.1.1 or later. For example, specifying <muleVersion>4.6-java17</muleVersion> in the plugin 3.8.0 or 4.0.0 deploys the application with an Edge release channel and a Java 8 selection. To specify releaseChannel and javaVersion, upgrade the plugin to version 4.1.1 or later.

Yes

releaseChannel

Set the name of the release channel to use for the selected Mule version. Supported values are NONE, EDGE, and LTS. If you don’t specify a Mule version, the default Mule version for the selected release channel is used. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the name of the Java version to use for the selected Mule version. Supported values are 8 and 17. If you don’t specify a Mule version, the default Mule version for the selected Java version is used. If the Java version you select isn’t available for the specified Mule version, an error occurs.

No

username

Your CloudHub username

Only when using Anypoint Platform credentials to login.

password

Your CloudHub password

Only when using Anypoint Platform credentials to login.

applicationName

The name of your application in CloudHub
This name is part of the domain of your deployed app. For example, naming your application application-1 makes your app’s public domain application-1.cloudhub.io.

Yes

artifact

The absolute path of the JAR file to be deployed
If not set, the path defaults to the location of the JAR file generated at the package phase.

No

environment

The CloudHub environment to which you want to deploy
This value must match any environment configured in your CloudHub account.

<environment>Sandbox</environment>

Yes

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

workers

The number of workers
By default, this value is 1.

No

workerType

Size of each worker; one of the following values:

  • MICRO (default; 0.1 vCores)

  • SMALL (0.2 vCores)

  • MEDIUM (1 vCore )

  • LARGE (2 vCores)

  • XLARGE (4 vCores)

  • XXLARGE (8 vCores)

  • 4XLARGE (16 vCores)

No

region

Region of worker clouds; one of the following values:

  • us-east-1 (default; US East, N. Virginia)

  • us-east-2 (US East, Ohio)

  • us-west-1 (US West, N. California)

  • us-west-2 (US West, Oregon)

  • us-gov-west-1 (MuleSoft Government Cloud)

  • eu-central-1 (EU, Frankfurt)

  • eu-west-1 (EU, Ireland)

  • eu-west-2 (UK, London)

  • ap-southeast-1 (Asia Pacific, Singapore)

  • ap-southeast-2 (Asia Pacific, Sydney)

  • ap-northeast-1 (Asia Pacific, Tokyo)

  • ca-central-1 (Canada, Central)

  • sa-east-1 (South America, São Paulo)

No

objectStoreV2

Enables Object Store V2
By default, this value is set to true to match the Runtime Manager configuration of OSv2.

No

persistentQueues

Enables persistent queues
By default, it is set to false.

No

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

applyLatestRuntimePatch

When set to true, the plugin instructs CloudHub to update the worker to the latest available patch for the Mule runtime engine version specified in the deployment configuration, and then deploys the application.
By default, it is set to false.

No

disableCloudHubLogs

When set to true, the plugin instructs CloudHub to disable CloudHub logging and instead use the application configured in the log4j2.xml file.
By default, it is set to false.

No

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.9/mmp-concept) - [Export Resources](https://docs.mulesoft.com/mule-runtime/4.9/how-to-export-resources) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Deploy Applications to CloudHub Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications to CloudHub, you can also deploy, redeploy, or undeploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your CloudHub deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to CloudHub using a different method, see: - [Deploy Applications to CloudHub Using Anypoint Studio](https://docs.mulesoft.com/studio/deploy-mule-application-task) - [Deploy Applications to CloudHub Using the Anypoint CLI](https://docs.mulesoft.com/anypoint-cli/latest/cloudhub-apps#deploy-to-cloudhub) - [Deploy Applications to CloudHub Using Runtime Manager](https://docs.mulesoft.com/cloudhub/deploying-to-cloudhub) ## Prerequisites Before you can deploy to CloudHub using the Mule Maven plugin, you must complete the following tasks: - Add the Mule Maven plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - If you are using the HTTP Listener as source for your flow, you need to set its host to **0.0.0.0** and its port to **${http.port}** - Declare all external classes and resources in the `exportedPackages` and `exportedResources` fields on the `mule-artifact.json` file ## Configure the CloudHub Deployment Strategy Configure the CloudHub deployment strategy in your project’s `pom.xml` file so you can deploy, redeploy and undeploy your Mule application using the Mule Maven plugin. Inside the `plugin` element in your project’s `pom.xml` file, configure your CloudHub deployment, replacing the placeholder values with your CloudHub information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com ${app.runtime} ${username} ${password} ${cloudhub.application.name} ${environment} ${region} ${workers} ${workerType} value ``` ## Deploy to CloudHub From the command line in your project’s folder, package the app and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ## Redeploy to CloudHub To redeploy a Mule application using Mule Maven plugin, run `mvn clean deploy -DmuleDeploy` as you did to previously deploy the app. CloudHub rewrites the app you had deployed. ## Undeploy from CloudHub To undeploy a Mule application using Mule Maven plugin, run the following command: ```console mvn mule:undeploy ``` The undeploy command also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a CloudHub username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [CloudHub Deployment Reference](#cloudhub-deploy-reference). ## CloudHub Deployment Reference The following table shows the available parameters to configure the CloudHub deployment strategy in your project’s `pom.xml` file.
ParameterDescriptionRequired

cloudHubDeployment

Top-level element

Yes

uri

Your Anypoint Platform URI
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your CloudHub instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application.
Example value: 4.3.0
Starting with Mule 4.5, deployments to CloudHub accept the Mule version exact name or the semantic versioning, which deploys the latest version of Mule runtime.
Example values: 4.6, 4.6-e-java8 (Edge), 4.6-e-java17 (Edge), 4.6-java8 (LTS), 4.6-java17 (LTS)
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, MuleSoft doesn’t guarantee support for LTS channel. We recommend that you use Mule Maven plugin version 4.1.1 or later. For example, specifying <muleVersion>4.6-java17</muleVersion> in the plugin 3.8.0 or 4.0.0 deploys the application with an Edge release channel and a Java 8 selection. To specify releaseChannel and javaVersion, upgrade the plugin to version 4.1.1 or later.

Yes

releaseChannel

Set the name of the release channel to use for the selected Mule version. Supported values are NONE, EDGE, and LTS. If you don’t specify a Mule version, the default Mule version for the selected release channel is used. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the name of the Java version to use for the selected Mule version. Supported values are 8 and 17. If you don’t specify a Mule version, the default Mule version for the selected Java version is used. If the Java version you select isn’t available for the specified Mule version, an error occurs.

No

username

Your CloudHub username

Only when using Anypoint Platform credentials to login.

password

Your CloudHub password

Only when using Anypoint Platform credentials to login.

applicationName

The name of your application in CloudHub
This name is part of the domain of your deployed app. For example, naming your application application-1 makes your app’s public domain application-1.cloudhub.io.

Yes

artifact

The absolute path of the JAR file to be deployed
If not set, the path defaults to the location of the JAR file generated at the package phase.

No

environment

The CloudHub environment to which you want to deploy
This value must match any environment configured in your CloudHub account.

<environment>Sandbox</environment>

Yes

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

workers

The number of workers
By default, this value is 1.

No

workerType

Size of each worker; one of the following values:

  • MICRO (default; 0.1 vCores)

  • SMALL (0.2 vCores)

  • MEDIUM (1 vCore )

  • LARGE (2 vCores)

  • XLARGE (4 vCores)

  • XXLARGE (8 vCores)

  • 4XLARGE (16 vCores)

No

region

Region of worker clouds; one of the following values:

  • us-east-1 (default; US East, N. Virginia)

  • us-east-2 (US East, Ohio)

  • us-west-1 (US West, N. California)

  • us-west-2 (US West, Oregon)

  • us-gov-west-1 (MuleSoft Government Cloud)

  • eu-central-1 (EU, Frankfurt)

  • eu-west-1 (EU, Ireland)

  • eu-west-2 (UK, London)

  • ap-southeast-1 (Asia Pacific, Singapore)

  • ap-southeast-2 (Asia Pacific, Sydney)

  • ap-northeast-1 (Asia Pacific, Tokyo)

  • ca-central-1 (Canada, Central)

  • sa-east-1 (South America, São Paulo)

No

objectStoreV2

Enables Object Store V2
By default, this value is set to true to match the Runtime Manager configuration of OSv2.

No

persistentQueues

Enables persistent queues
By default, it is set to false.

No

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

applyLatestRuntimePatch

When set to true, the plugin instructs CloudHub to update the worker to the latest available patch for the Mule runtime engine version specified in the deployment configuration, and then deploys the application.
By default, it is set to false.

No

disableCloudHubLogs

When set to true, the plugin instructs CloudHub to disable CloudHub logging and instead use the application configured in the log4j2.xml file.
By default, it is set to false.

No

## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) - [Export Resources](https://docs.mulesoft.com/mule-runtime/latest/how-to-export-resources) --- product: Mule Runtime version: 4.11 --- # Deploy Applications to On-Premises Mule Instances Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications on-premises, you can also deploy Mule applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure the desired deployment strategy in your project’s `pom.xml` file. If you want to deploy applications on-premises using a different method, see: - [Deploy Applications On-Premises Using Runtime Manager](https://docs.mulesoft.com/runtime-manager/deploying-to-your-own-servers) - [Deploy Applications On-Premises Using the Anypoint Platform CLI](https://docs.mulesoft.com/anypoint-cli/latest/standalone-apps#runtime-mgr-standalone-application-deploy) - [Deploy Applications On-Premises Using Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages#export-project-studio) ## On-premises Deployment Strategies When you deploy applications on-premises using the Mule Maven plugin, you can select three different methods for deployment: - Standalone deployment By using this method you perform a manual deployment of your Mule application to your on-premises Mule instance. - Runtime Manager REST API deployment This method enables you to deploy an application using the Runtime Manager REST API, which links your on-premises Mule instance with your Anypoint Runtime Manager account, where you can do further management and monitoring of your deployed application. - Runtime Manager Agent deployment This method enables you to deploy an application using the Runtime Manager agent, which exposes a local API that you can call to manage and monitor your deployed application. The Mule Maven plugin also supports deploying domains when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. Additional operations enable you to deploy applications in parallel and update applications at runtime. ## Prerequisites - Add the Mule Maven Plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/4.11/mmp-concept#add-mmp) for instructions. ## Deploy a Mule Application to a Standalone Mule Runtime Engine Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} ${app.runtime} ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Standalone Deployment Parameters Reference
ParameterDescriptionRequired

standaloneDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version running in your local machine instance.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

muleHome

The location of the Mule instance in your local machine.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Mule Application Using the Runtime Manager REST API Mule Maven plugin enables you to deploy a Mule Application to a local Mule instance using the Runtime Manager REST API. ### Prerequisites - You need a server, server group or cluster created in Runtime Manager. - To create a server, see [Add Servers](https://docs.mulesoft.com/runtime-manager/servers-create). - To create a server group, see [Create Server Groups](https://docs.mulesoft.com/runtime-manager/server-group-create). - To create a cluster, see [Create Clusters](https://docs.mulesoft.com/runtime-manager/cluster-create). ### Deploying Using the Runtime Manager REST API Inside the `plugin` element, add a configuration for your Runtime Manager deployment, replacing the placeholder values with your Runtime Manager information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${app.runtime} https://anypoint.mulesoft.com ${target} ${target.type} ${username} ${password} ${environment} value ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Authenticate with the username and password for the server where your Mule instances are installed.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Manager REST API Deployment Parameters Reference](#arm-deploy-reference). ### Runtime Manager REST API Deployment Parameters Reference
ParameterDescriptionRequired

armDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The Anypoint Platform URI. If you are using Anypoint Platform PCE, specify this parameter with your Anypoint Platform installation URI.
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

target

The server name for the server where your Mule instances are installed.

Yes

targetType

The type of target to which you are deploying.

Valid values are:

  • server

  • serverGroup

  • cluster

Yes

username

Your username for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

password

Your password for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

environment

The environment name for the server where your Mule instances are installed. This value must match any environment configured in your Runtime Manager account.
For Example:

<environment>Sandbox</environment>

Yes

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

### Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ### Troubleshoot TLS Errors in Anypoint Private Cloud Edition When trying to connect to an instance of Runtime Manager that’s on an [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) installation, the plugin validates certificates for that server. If you haven’t installed the server certificates in your truststore, an SSL error occurs. To avoid this problem, you can run the plugin in an insecure mode, which skips the security validations. You can use the **armInsecure** tag or the **arm.insecure** system property. > [!WARNING] Enabling an insecure connection is a dangerous practice. Don’t use this unless you know > what you are doing and your On-Premises installation is isolated in a local network. See the configuration example below: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${target} ${target.type} ${username} ${password} ${environment} true ``` ## Deploy a Mule Application Using the Runtime Manager Agent Inside the `plugin` element, add a configuration for your Runtime Manager agent deployment, replacing the URI value with your remote server information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true http://localhost:9999/ ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Runtime Manager Agent Deployment Parameters Reference
ParameterDescriptionRequired

agentDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The server URI where your Mule instances are installed.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Domain The Mule Maven plugin supports deploying domains only when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. To deploy a domain, use the same configuration and deployment steps you use when deploying an application. For example, to deploy a domain to a standalone instance: 1. Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} ${app.runtime} ``` 2. From the command line in your project’s folder, package the domain and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ## Deploy Applications in Parallel You can deploy applications in parallel to on-premises Mule instances. Deploying applications in parallel reduces the startup time when you deploy a large number of apps. To prevent deployment failure, ensure that applications are not dependent on each other because a particular start order cannot be guaranteed. Parallelism is fixed at 20. To enable parallel deployment: 1. Package or export your Mule applications to the `/apps` directory of your Mule runtime engine instance. 2. Start Mule using the `-M-Dmule.deployment.parallel` option: ```none mule -M-Dmule.deployment.parallel ``` After performing these steps, Mule deploys in parallel all applications in the `/apps` directory. ## Undeploy Applications You can undeploy Mule applications by deleting an app’s anchor file only instead of deleting the application folder directly. Deleting only the app’s anchor file: - Prevents any interference from the hot-deployment layer and leaves no room for concurrent conflicting actions. - Avoids potential application JAR file locking issues on some operation systems and allows for clean shutdown and undeployment. For example, if the `stockTrader` app is running (app folder is there as well as the `$MULE_HOME/apps/stockTrader-anchor.txt` file), just delete the anchor file to have the app removed from the Mule instance at runtime. Application folder is removed after the app terminates. > [!NOTE] After undeploying a Mule application, there is a timeout of 15 seconds until > `LoggerContext` stops. Log files for an application only release after this timeout expires. This > information is important in Windows, where you can’t remove files that are in use by other > processes. After undeploying a Mule application, there is a timeout of 15 seconds until > LoggerContext stops. Log files for an application only release after this timeout expires. This > information is important in Windows, where you can’t remove files that are in use by other > processes. ## Update Applications at Runtime Updating a Mule application at runtime can be a complex change involving class modifications, endpoint modifications (for example, changing ports), and reconfiguring flows. An application update first performs a graceful app shutdown and then reconfigures itself in the background within seconds. This process is transparent for the users. There are two ways you can update an application: - By adding the modifications over an existing unpacked app folder and touching the main configuration file (`mule-config.xml` located in the app’s root directory by default). For this option to be valid, start the runtime with the system property `-M-Dmule.deployment.forceParseConfigXmls=true`. - By adding a new `jar` with an updated version of the app into the `$MULE_HOME/apps` directory. Mule detects the `jar` as an updated version of an existing application and ensures the update by a clean redeployment of the app. Note that Mule discards any modifications to the old application folder. The new app folder is a clean unpacked application from a `jar`. Either method integrates well with existing build tools. ## See Also - [Anypoint Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.11/mmp-concept) --- product: Mule Runtime version: 4.12 --- # Deploy Applications to On-Premises Mule Instances Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications on-premises, you can also deploy Mule applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure the desired deployment strategy in your project’s `pom.xml` file. If you want to deploy applications on-premises using a different method, see: - [Deploy Applications On-Premises Using Runtime Manager](https://docs.mulesoft.com/runtime-manager/deploying-to-your-own-servers) - [Deploy Applications On-Premises Using the Anypoint Platform CLI](https://docs.mulesoft.com/anypoint-cli/latest/standalone-apps#runtime-mgr-standalone-application-deploy) - [Deploy Applications On-Premises Using Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages#export-project-studio) ## On-premises Deployment Strategies When you deploy applications on-premises using the Mule Maven plugin, you can select three different methods for deployment: - Standalone deployment By using this method you perform a manual deployment of your Mule application to your on-premises Mule instance. - Runtime Manager REST API deployment This method enables you to deploy an application using the Runtime Manager REST API, which links your on-premises Mule instance with your Anypoint Runtime Manager account, where you can do further management and monitoring of your deployed application. - Runtime Manager Agent deployment This method enables you to deploy an application using the Runtime Manager agent, which exposes a local API that you can call to manage and monitor your deployed application. The Mule Maven plugin also supports deploying domains when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. Additional operations enable you to deploy applications in parallel and update applications at runtime. ## Prerequisites - Add the Mule Maven Plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/4.12/mmp-concept#add-mmp) for instructions. ## Deploy a Mule Application to a Standalone Mule Runtime Engine Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} ${app.runtime} ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Standalone Deployment Parameters Reference
ParameterDescriptionRequired

standaloneDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version running in your local machine instance.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

muleHome

The location of the Mule instance in your local machine.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Mule Application Using the Runtime Manager REST API Mule Maven plugin enables you to deploy a Mule Application to a local Mule instance using the Runtime Manager REST API. ### Prerequisites - You need a server, server group or cluster created in Runtime Manager. - To create a server, see [Add Servers](https://docs.mulesoft.com/runtime-manager/servers-create). - To create a server group, see [Create Server Groups](https://docs.mulesoft.com/runtime-manager/server-group-create). - To create a cluster, see [Create Clusters](https://docs.mulesoft.com/runtime-manager/cluster-create). ### Deploying Using the Runtime Manager REST API Inside the `plugin` element, add a configuration for your Runtime Manager deployment, replacing the placeholder values with your Runtime Manager information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${app.runtime} https://anypoint.mulesoft.com ${target} ${target.type} ${username} ${password} ${environment} value ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Authenticate with the username and password for the server where your Mule instances are installed.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Manager REST API Deployment Parameters Reference](#arm-deploy-reference). ### Runtime Manager REST API Deployment Parameters Reference
ParameterDescriptionRequired

armDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The Anypoint Platform URI. If you are using Anypoint Platform PCE, specify this parameter with your Anypoint Platform installation URI.
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

target

The server name for the server where your Mule instances are installed.

Yes

targetType

The type of target to which you are deploying.

Valid values are:

  • server

  • serverGroup

  • cluster

Yes

username

Your username for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

password

Your password for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

environment

The environment name for the server where your Mule instances are installed. This value must match any environment configured in your Runtime Manager account.
For Example:

<environment>Sandbox</environment>

Yes

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

### Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ### Troubleshoot TLS Errors in Anypoint Private Cloud Edition When trying to connect to an instance of Runtime Manager that’s on an [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) installation, the plugin validates certificates for that server. If you haven’t installed the server certificates in your truststore, an SSL error occurs. To avoid this problem, you can run the plugin in an insecure mode, which skips the security validations. You can use the **armInsecure** tag or the **arm.insecure** system property. > [!WARNING] Enabling an insecure connection is a dangerous practice. Don’t use this unless you know > what you are doing and your On-Premises installation is isolated in a local network. See the configuration example below: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${target} ${target.type} ${username} ${password} ${environment} true ``` ## Deploy a Mule Application Using the Runtime Manager Agent Inside the `plugin` element, add a configuration for your Runtime Manager agent deployment, replacing the URI value with your remote server information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true http://localhost:9999/ ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Runtime Manager Agent Deployment Parameters Reference
ParameterDescriptionRequired

agentDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The server URI where your Mule instances are installed.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Domain The Mule Maven plugin supports deploying domains only when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. To deploy a domain, use the same configuration and deployment steps you use when deploying an application. For example, to deploy a domain to a standalone instance: 1. Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} ${app.runtime} ``` 2. From the command line in your project’s folder, package the domain and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ## Deploy Applications in Parallel You can deploy applications in parallel to on-premises Mule instances. Deploying applications in parallel reduces the startup time when you deploy a large number of apps. To prevent deployment failure, ensure that applications are not dependent on each other because a particular start order cannot be guaranteed. Parallelism is fixed at 20. To enable parallel deployment: 1. Package or export your Mule applications to the `/apps` directory of your Mule runtime engine instance. 2. Start Mule using the `-M-Dmule.deployment.parallel` option: ```none mule -M-Dmule.deployment.parallel ``` After performing these steps, Mule deploys in parallel all applications in the `/apps` directory. ## Undeploy Applications You can undeploy Mule applications by deleting an app’s anchor file only instead of deleting the application folder directly. Deleting only the app’s anchor file: - Prevents any interference from the hot-deployment layer and leaves no room for concurrent conflicting actions. - Avoids potential application JAR file locking issues on some operation systems and allows for clean shutdown and undeployment. For example, if the `stockTrader` app is running (app folder is there as well as the `$MULE_HOME/apps/stockTrader-anchor.txt` file), just delete the anchor file to have the app removed from the Mule instance at runtime. Application folder is removed after the app terminates. > [!NOTE] After undeploying a Mule application, there is a timeout of 15 seconds until > `LoggerContext` stops. Log files for an application only release after this timeout expires. This > information is important in Windows, where you can’t remove files that are in use by other > processes. After undeploying a Mule application, there is a timeout of 15 seconds until > LoggerContext stops. Log files for an application only release after this timeout expires. This > information is important in Windows, where you can’t remove files that are in use by other > processes. ## Update Applications at Runtime Updating a Mule application at runtime can be a complex change involving class modifications, endpoint modifications (for example, changing ports), and reconfiguring flows. An application update first performs a graceful app shutdown and then reconfigures itself in the background within seconds. This process is transparent for the users. There are two ways you can update an application: - By adding the modifications over an existing unpacked app folder and touching the main configuration file (`mule-config.xml` located in the app’s root directory by default). For this option to be valid, start the runtime with the system property `-M-Dmule.deployment.forceParseConfigXmls=true`. - By adding a new `jar` with an updated version of the app into the `$MULE_HOME/apps` directory. Mule detects the `jar` as an updated version of an existing application and ensures the update by a clean redeployment of the app. Note that Mule discards any modifications to the old application folder. The new app folder is a clean unpacked application from a `jar`. Either method integrates well with existing build tools. ## See Also - [Anypoint Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.12/mmp-concept) --- product: Mule Runtime version: 4.3 --- # Deploy Applications to On-Premises Mule Instances Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications on-premises, you can also deploy Mule applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure the desired deployment strategy in your project’s `pom.xml` file. If you want to deploy applications on-premises using a different method, see: - [Deploy Applications On-Premises Using Runtime Manager](https://docs.mulesoft.com/runtime-manager/deploying-to-your-own-servers) - [Deploy Applications On-Premises Using the Anypoint Platform CLI](https://docs.mulesoft.com/anypoint-cli/latest/standalone-apps#runtime-mgr-standalone-application-deploy) - [Deploy Applications On-Premises Using Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages#export-project-studio) ## On-premises Deployment Strategies When you deploy applications on-premises using the Mule Maven plugin, you can select three different methods for deployment: - Standalone deployment By using this method you perform a manual deployment of your Mule application to your on-premises Mule instance. - Runtime Manager REST API deployment This method enables you to deploy an application using the Runtime Manager REST API, which links your on-premises Mule instance with your Anypoint Runtime Manager account, where you can do further management and monitoring of your deployed application. - Runtime Manager Agent deployment This method enables you to deploy an application using the Runtime Manager agent, which exposes a local API that you can call to manage and monitor your deployed application. The Mule Maven plugin also supports deploying domains when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. Additional operations enable you to deploy applications in parallel and update applications at runtime. ## Prerequisites - Add the Mule Maven Plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/4.3/mmp-concept#add-mmp) for instructions. ## Deploy a Mule Application to a Standalone Mule Runtime Engine Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.4.2 true ${mule.home.test} ${app.runtime} ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean package deploy -DmuleDeploy ``` ### Standalone Deployment Parameters Reference
ParameterDescriptionRequired

standaloneDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version running in your local machine instance.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

muleHome

The location of the Mule instance in your local machine.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Mule Application Using the Runtime Manager REST API Mule Maven plugin enables you to deploy a Mule Application to a local Mule instance using the Runtime Manager REST API. ### Prerequisites - You need a server, server group or cluster created in Runtime Manager. - To create a server, see [Add Servers](https://docs.mulesoft.com/runtime-manager/servers-create). - To create a server group, see [Create Server Groups](https://docs.mulesoft.com/runtime-manager/server-group-create). - To create a cluster, see [Create Clusters](https://docs.mulesoft.com/runtime-manager/cluster-create). ### Deploying Using the Runtime Manager REST API Inside the `plugin` element, add a configuration for your Runtime Manager deployment, replacing the placeholder values with your Runtime Manager information: ```xml org.mule.tools.maven mule-maven-plugin 3.4.2 true ${app.runtime} https://anypoint.mulesoft.com ${target} ${target.type} ${username} ${password} ${environment} value ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean package deploy -DmuleDeploy ``` ### Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Authenticate with the username and password for the server where your Mule instances are installed.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Manager REST API Deployment Parameters Reference](#arm-deploy-reference). ### Runtime Manager REST API Deployment Parameters Reference
ParameterDescriptionRequired

armDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The Anypoint Platform URI. If you are using Anypoint Platform PCE, specify this parameter with your Anypoint Platform installation URI.
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

target

The server name for the server where your Mule instances are installed.

Yes

targetType

The type of target to which you are deploying.

Valid values are:

  • server

  • serverGroup

  • cluster

Yes

username

Your username for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

password

Your password for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

environment

The environment name for the server where your Mule instances are installed. This value must match any environment configured in your Runtime Manager account.
For Example:

<environment>Sandbox</environment>

Yes

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

### Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ### Troubleshoot TLS Errors in Anypoint Private Cloud Edition When trying to connect to an instance of Runtime Manager that’s on an [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) installation, the plugin validates certificates for that server. If you haven’t installed the server certificates in your truststore, an SSL error occurs. To avoid this problem, you can run the plugin in an insecure mode, which skips the security validations. You can use the **armInsecure** tag or the **arm.insecure** system property. > [!WARNING] Enabling an insecure connection is a dangerous practice. Don’t use this unless you know > what you are doing and your On-Premises installation is isolated in a local network. See the configuration example below: ```xml org.mule.tools.maven mule-maven-plugin 3.4.2 true ${target} ${target.type} ${username} ${password} ${environment} true ``` ## Deploy a Mule Application Using the Runtime Manager Agent Inside the `plugin` element, add a configuration for your Runtime Manager agent deployment, replacing the URI value with your remote server information: ```xml org.mule.tools.maven mule-maven-plugin 3.4.2 true http://localhost:9999/ ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean package deploy -DmuleDeploy ``` ### Runtime Manager Agent Deployment Parameters Reference
ParameterDescriptionRequired

agentDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The server URI where your Mule instances are installed.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Domain The Mule Maven plugin supports deploying domains only when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. To deploy a domain, use the same configuration and deployment steps you use when deploying an application. For example, to deploy a domain to a standalone instance: 1. Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.4.2 true ${mule.home.test} ${app.runtime} ``` 2. From the command line in your project’s folder, package the domain and execute the deploy goal: ```console mvn clean package deploy -DmuleDeploy ``` ## Deploy Applications in Parallel You can deploy applications in parallel to on-premises Mule instances. Deploying applications in parallel reduces the startup time when you deploy a large number of apps. To prevent deployment failure, ensure that applications are not dependent on each other because a particular start order cannot be guaranteed. Parallelism is fixed at 20. To enable parallel deployment: 1. Package or export your Mule applications to the `/apps` directory of your Mule runtime engine instance. 2. Start Mule using the `-M-Dmule.deployment.parallel` option: ```none mule -M-Dmule.deployment.parallel ``` After performing these steps, Mule deploys in parallel all applications in the `/apps` directory. ## Update Applications at Runtime Updating a Mule application at runtime can be a complex change involving class modifications, endpoint modifications (for example, changing ports), and reconfiguring flows. An application update first performs a graceful app shutdown and then reconfigures itself in the background within seconds. This process is transparent for the users. There are two ways you can update an application: - By adding the modifications over an existing unpacked app folder and touching the main configuration file (`mule-config.xml` located in the app’s root directory by default). - By adding a new `jar` with an updated version of the app into the `$MULE_HOME/apps` directory. Mule detects the `jar` as an updated version of an existing application and ensures the update by a clean redeployment of the app. Note that Mule discards any modifications to the old application folder. The new app folder is a clean unpacked application from a `jar`. Either method integrates well with existing build tools. ## See Also - [Anypoint Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.3/mmp-concept) --- product: Mule Runtime version: 4.4 --- # Deploy Applications to On-Premises Mule Instances Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications on-premises, you can also deploy Mule applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure the desired deployment strategy in your project’s `pom.xml` file. If you want to deploy applications on-premises using a different method, see: - [Deploy Applications On-Premises Using Runtime Manager](https://docs.mulesoft.com/runtime-manager/deploying-to-your-own-servers) - [Deploy Applications On-Premises Using the Anypoint Platform CLI](https://docs.mulesoft.com/anypoint-cli/latest/standalone-apps#runtime-mgr-standalone-application-deploy) - [Deploy Applications On-Premises Using Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages#export-project-studio) ## On-premises Deployment Strategies When you deploy applications on-premises using the Mule Maven plugin, you can select three different methods for deployment: - Standalone deployment By using this method you perform a manual deployment of your Mule application to your on-premises Mule instance. - Runtime Manager REST API deployment This method enables you to deploy an application using the Runtime Manager REST API, which links your on-premises Mule instance with your Anypoint Runtime Manager account, where you can do further management and monitoring of your deployed application. - Runtime Manager Agent deployment This method enables you to deploy an application using the Runtime Manager agent, which exposes a local API that you can call to manage and monitor your deployed application. The Mule Maven plugin also supports deploying domains when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. Additional operations enable you to deploy applications in parallel and update applications at runtime. ## Prerequisites - Add the Mule Maven Plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/4.4/mmp-concept#add-mmp) for instructions. ## Deploy a Mule Application to a Standalone Mule Runtime Engine Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} ${app.runtime} ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Standalone Deployment Parameters Reference
ParameterDescriptionRequired

standaloneDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version running in your local machine instance.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

muleHome

The location of the Mule instance in your local machine.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Mule Application Using the Runtime Manager REST API Mule Maven plugin enables you to deploy a Mule Application to a local Mule instance using the Runtime Manager REST API. ### Prerequisites - You need a server, server group or cluster created in Runtime Manager. - To create a server, see [Add Servers](https://docs.mulesoft.com/runtime-manager/servers-create). - To create a server group, see [Create Server Groups](https://docs.mulesoft.com/runtime-manager/server-group-create). - To create a cluster, see [Create Clusters](https://docs.mulesoft.com/runtime-manager/cluster-create). ### Deploying Using the Runtime Manager REST API Inside the `plugin` element, add a configuration for your Runtime Manager deployment, replacing the placeholder values with your Runtime Manager information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${app.runtime} https://anypoint.mulesoft.com ${target} ${target.type} ${username} ${password} ${environment} value ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Authenticate with the username and password for the server where your Mule instances are installed.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Manager REST API Deployment Parameters Reference](#arm-deploy-reference). ### Runtime Manager REST API Deployment Parameters Reference
ParameterDescriptionRequired

armDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The Anypoint Platform URI. If you are using Anypoint Platform PCE, specify this parameter with your Anypoint Platform installation URI.
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

target

The server name for the server where your Mule instances are installed.

Yes

targetType

The type of target to which you are deploying.

Valid values are:

  • server

  • serverGroup

  • cluster

Yes

username

Your username for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

password

Your password for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

environment

The environment name for the server where your Mule instances are installed. This value must match any environment configured in your Runtime Manager account.
For Example:

<environment>Sandbox</environment>

Yes

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

### Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ### Troubleshoot TLS Errors in Anypoint Private Cloud Edition When trying to connect to an instance of Runtime Manager that’s on an [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) installation, the plugin validates certificates for that server. If you haven’t installed the server certificates in your truststore, an SSL error occurs. To avoid this problem, you can run the plugin in an insecure mode, which skips the security validations. You can use the **armInsecure** tag or the **arm.insecure** system property. > [!WARNING] Enabling an insecure connection is a dangerous practice. Don’t use this unless you know > what you are doing and your On-Premises installation is isolated in a local network. See the configuration example below: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${target} ${target.type} ${username} ${password} ${environment} true ``` ## Deploy a Mule Application Using the Runtime Manager Agent Inside the `plugin` element, add a configuration for your Runtime Manager agent deployment, replacing the URI value with your remote server information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true http://localhost:9999/ ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Runtime Manager Agent Deployment Parameters Reference
ParameterDescriptionRequired

agentDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The server URI where your Mule instances are installed.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Domain The Mule Maven plugin supports deploying domains only when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. To deploy a domain, use the same configuration and deployment steps you use when deploying an application. For example, to deploy a domain to a standalone instance: 1. Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} ${app.runtime} ``` 2. From the command line in your project’s folder, package the domain and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ## Deploy Applications in Parallel You can deploy applications in parallel to on-premises Mule instances. Deploying applications in parallel reduces the startup time when you deploy a large number of apps. To prevent deployment failure, ensure that applications are not dependent on each other because a particular start order cannot be guaranteed. Parallelism is fixed at 20. To enable parallel deployment: 1. Package or export your Mule applications to the `/apps` directory of your Mule runtime engine instance. 2. Start Mule using the `-M-Dmule.deployment.parallel` option: ```none mule -M-Dmule.deployment.parallel ``` After performing these steps, Mule deploys in parallel all applications in the `/apps` directory. ## Undeploy Applications You can undeploy Mule applications by deleting an app’s anchor file only instead of deleting the application folder directly. Deleting only the app’s anchor file: - Prevents any interference from the hot-deployment layer and leaves no room for concurrent conflicting actions. - Avoids potential application JAR file locking issues on some operation systems and allows for clean shutdown and undeployment. For example, if the `stockTrader` app is running (app folder is there as well as the `$MULE_HOME/apps/stockTrader-anchor.txt` file), just delete the anchor file to have the app removed from the Mule instance at runtime. Application folder is removed after the app terminates. > [!NOTE] After undeploying a Mule application, there is a timeout of 15 seconds until > `LoggerContext` stops. Log files for an application only release after this timeout expires. This > information is important in Windows, where you can’t remove files that are in use by other > processes. After undeploying a Mule application, there is a timeout of 15 seconds until > LoggerContext stops. Log files for an application only release after this timeout expires. This > information is important in Windows, where you can’t remove files that are in use by other > processes. ## Update Applications at Runtime Updating a Mule application at runtime can be a complex change involving class modifications, endpoint modifications (for example, changing ports), and reconfiguring flows. An application update first performs a graceful app shutdown and then reconfigures itself in the background within seconds. This process is transparent for the users. There are two ways you can update an application: - By adding the modifications over an existing unpacked app folder and touching the main configuration file (`mule-config.xml` located in the app’s root directory by default). For this option to be valid, start the runtime with the system property `-M-Dmule.deployment.forceParseConfigXmls=true`. - By adding a new `jar` with an updated version of the app into the `$MULE_HOME/apps` directory. Mule detects the `jar` as an updated version of an existing application and ensures the update by a clean redeployment of the app. Note that Mule discards any modifications to the old application folder. The new app folder is a clean unpacked application from a `jar`. Either method integrates well with existing build tools. ## See Also - [Anypoint Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.4/mmp-concept) --- product: Mule Runtime version: 4.6 --- # Deploy Applications to On-Premises Mule Instances Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications on-premises, you can also deploy Mule applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure the desired deployment strategy in your project’s `pom.xml` file. If you want to deploy applications on-premises using a different method, see: - [Deploy Applications On-Premises Using Runtime Manager](https://docs.mulesoft.com/runtime-manager/deploying-to-your-own-servers) - [Deploy Applications On-Premises Using the Anypoint Platform CLI](https://docs.mulesoft.com/anypoint-cli/latest/standalone-apps#runtime-mgr-standalone-application-deploy) - [Deploy Applications On-Premises Using Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages#export-project-studio) ## On-premises Deployment Strategies When you deploy applications on-premises using the Mule Maven plugin, you can select three different methods for deployment: - Standalone deployment By using this method you perform a manual deployment of your Mule application to your on-premises Mule instance. - Runtime Manager REST API deployment This method enables you to deploy an application using the Runtime Manager REST API, which links your on-premises Mule instance with your Anypoint Runtime Manager account, where you can do further management and monitoring of your deployed application. - Runtime Manager Agent deployment This method enables you to deploy an application using the Runtime Manager agent, which exposes a local API that you can call to manage and monitor your deployed application. The Mule Maven plugin also supports deploying domains when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. Additional operations enable you to deploy applications in parallel and update applications at runtime. ## Prerequisites - Add the Mule Maven Plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/4.6/mmp-concept#add-mmp) for instructions. ## Deploy a Mule Application to a Standalone Mule Runtime Engine Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} ${app.runtime} ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Standalone Deployment Parameters Reference
ParameterDescriptionRequired

standaloneDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version running in your local machine instance.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

muleHome

The location of the Mule instance in your local machine.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Mule Application Using the Runtime Manager REST API Mule Maven plugin enables you to deploy a Mule Application to a local Mule instance using the Runtime Manager REST API. ### Prerequisites - You need a server, server group or cluster created in Runtime Manager. - To create a server, see [Add Servers](https://docs.mulesoft.com/runtime-manager/servers-create). - To create a server group, see [Create Server Groups](https://docs.mulesoft.com/runtime-manager/server-group-create). - To create a cluster, see [Create Clusters](https://docs.mulesoft.com/runtime-manager/cluster-create). ### Deploying Using the Runtime Manager REST API Inside the `plugin` element, add a configuration for your Runtime Manager deployment, replacing the placeholder values with your Runtime Manager information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${app.runtime} https://anypoint.mulesoft.com ${target} ${target.type} ${username} ${password} ${environment} value ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Authenticate with the username and password for the server where your Mule instances are installed.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Manager REST API Deployment Parameters Reference](#arm-deploy-reference). ### Runtime Manager REST API Deployment Parameters Reference
ParameterDescriptionRequired

armDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The Anypoint Platform URI. If you are using Anypoint Platform PCE, specify this parameter with your Anypoint Platform installation URI.
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

target

The server name for the server where your Mule instances are installed.

Yes

targetType

The type of target to which you are deploying.

Valid values are:

  • server

  • serverGroup

  • cluster

Yes

username

Your username for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

password

Your password for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

environment

The environment name for the server where your Mule instances are installed. This value must match any environment configured in your Runtime Manager account.
For Example:

<environment>Sandbox</environment>

Yes

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

### Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ### Troubleshoot TLS Errors in Anypoint Private Cloud Edition When trying to connect to an instance of Runtime Manager that’s on an [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) installation, the plugin validates certificates for that server. If you haven’t installed the server certificates in your truststore, an SSL error occurs. To avoid this problem, you can run the plugin in an insecure mode, which skips the security validations. You can use the **armInsecure** tag or the **arm.insecure** system property. > [!WARNING] Enabling an insecure connection is a dangerous practice. Don’t use this unless you know > what you are doing and your On-Premises installation is isolated in a local network. See the configuration example below: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${target} ${target.type} ${username} ${password} ${environment} true ``` ## Deploy a Mule Application Using the Runtime Manager Agent Inside the `plugin` element, add a configuration for your Runtime Manager agent deployment, replacing the URI value with your remote server information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true http://localhost:9999/ ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Runtime Manager Agent Deployment Parameters Reference
ParameterDescriptionRequired

agentDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The server URI where your Mule instances are installed.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Domain The Mule Maven plugin supports deploying domains only when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. To deploy a domain, use the same configuration and deployment steps you use when deploying an application. For example, to deploy a domain to a standalone instance: 1. Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} ${app.runtime} ``` 2. From the command line in your project’s folder, package the domain and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ## Deploy Applications in Parallel You can deploy applications in parallel to on-premises Mule instances. Deploying applications in parallel reduces the startup time when you deploy a large number of apps. To prevent deployment failure, ensure that applications are not dependent on each other because a particular start order cannot be guaranteed. Parallelism is fixed at 20. To enable parallel deployment: 1. Package or export your Mule applications to the `/apps` directory of your Mule runtime engine instance. 2. Start Mule using the `-M-Dmule.deployment.parallel` option: ```none mule -M-Dmule.deployment.parallel ``` After performing these steps, Mule deploys in parallel all applications in the `/apps` directory. ## Undeploy Applications You can undeploy Mule applications by deleting an app’s anchor file only instead of deleting the application folder directly. Deleting only the app’s anchor file: - Prevents any interference from the hot-deployment layer and leaves no room for concurrent conflicting actions. - Avoids potential application JAR file locking issues on some operation systems and allows for clean shutdown and undeployment. For example, if the `stockTrader` app is running (app folder is there as well as the `$MULE_HOME/apps/stockTrader-anchor.txt` file), just delete the anchor file to have the app removed from the Mule instance at runtime. Application folder is removed after the app terminates. > [!NOTE] After undeploying a Mule application, there is a timeout of 15 seconds until > `LoggerContext` stops. Log files for an application only release after this timeout expires. This > information is important in Windows, where you can’t remove files that are in use by other > processes. After undeploying a Mule application, there is a timeout of 15 seconds until > LoggerContext stops. Log files for an application only release after this timeout expires. This > information is important in Windows, where you can’t remove files that are in use by other > processes. ## Update Applications at Runtime Updating a Mule application at runtime can be a complex change involving class modifications, endpoint modifications (for example, changing ports), and reconfiguring flows. An application update first performs a graceful app shutdown and then reconfigures itself in the background within seconds. This process is transparent for the users. There are two ways you can update an application: - By adding the modifications over an existing unpacked app folder and touching the main configuration file (`mule-config.xml` located in the app’s root directory by default). For this option to be valid, start the runtime with the system property `-M-Dmule.deployment.forceParseConfigXmls=true`. - By adding a new `jar` with an updated version of the app into the `$MULE_HOME/apps` directory. Mule detects the `jar` as an updated version of an existing application and ensures the update by a clean redeployment of the app. Note that Mule discards any modifications to the old application folder. The new app folder is a clean unpacked application from a `jar`. Either method integrates well with existing build tools. ## See Also - [Anypoint Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.6/mmp-concept) --- product: Mule Runtime version: 4.9 --- # Deploy Applications to On-Premises Mule Instances Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications on-premises, you can also deploy Mule applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure the desired deployment strategy in your project’s `pom.xml` file. If you want to deploy applications on-premises using a different method, see: - [Deploy Applications On-Premises Using Runtime Manager](https://docs.mulesoft.com/runtime-manager/deploying-to-your-own-servers) - [Deploy Applications On-Premises Using the Anypoint Platform CLI](https://docs.mulesoft.com/anypoint-cli/latest/standalone-apps#runtime-mgr-standalone-application-deploy) - [Deploy Applications On-Premises Using Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages#export-project-studio) ## On-premises Deployment Strategies When you deploy applications on-premises using the Mule Maven plugin, you can select three different methods for deployment: - Standalone deployment By using this method you perform a manual deployment of your Mule application to your on-premises Mule instance. - Runtime Manager REST API deployment This method enables you to deploy an application using the Runtime Manager REST API, which links your on-premises Mule instance with your Anypoint Runtime Manager account, where you can do further management and monitoring of your deployed application. - Runtime Manager Agent deployment This method enables you to deploy an application using the Runtime Manager agent, which exposes a local API that you can call to manage and monitor your deployed application. The Mule Maven plugin also supports deploying domains when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. Additional operations enable you to deploy applications in parallel and update applications at runtime. ## Prerequisites - Add the Mule Maven Plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/4.9/mmp-concept#add-mmp) for instructions. ## Deploy a Mule Application to a Standalone Mule Runtime Engine Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} ${app.runtime} ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Standalone Deployment Parameters Reference
ParameterDescriptionRequired

standaloneDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version running in your local machine instance.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

muleHome

The location of the Mule instance in your local machine.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Mule Application Using the Runtime Manager REST API Mule Maven plugin enables you to deploy a Mule Application to a local Mule instance using the Runtime Manager REST API. ### Prerequisites - You need a server, server group or cluster created in Runtime Manager. - To create a server, see [Add Servers](https://docs.mulesoft.com/runtime-manager/servers-create). - To create a server group, see [Create Server Groups](https://docs.mulesoft.com/runtime-manager/server-group-create). - To create a cluster, see [Create Clusters](https://docs.mulesoft.com/runtime-manager/cluster-create). ### Deploying Using the Runtime Manager REST API Inside the `plugin` element, add a configuration for your Runtime Manager deployment, replacing the placeholder values with your Runtime Manager information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${app.runtime} https://anypoint.mulesoft.com ${target} ${target.type} ${username} ${password} ${environment} value ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Authenticate with the username and password for the server where your Mule instances are installed.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Manager REST API Deployment Parameters Reference](#arm-deploy-reference). ### Runtime Manager REST API Deployment Parameters Reference
ParameterDescriptionRequired

armDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The Anypoint Platform URI. If you are using Anypoint Platform PCE, specify this parameter with your Anypoint Platform installation URI.
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

target

The server name for the server where your Mule instances are installed.

Yes

targetType

The type of target to which you are deploying.

Valid values are:

  • server

  • serverGroup

  • cluster

Yes

username

Your username for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

password

Your password for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

environment

The environment name for the server where your Mule instances are installed. This value must match any environment configured in your Runtime Manager account.
For Example:

<environment>Sandbox</environment>

Yes

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

### Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ### Troubleshoot TLS Errors in Anypoint Private Cloud Edition When trying to connect to an instance of Runtime Manager that’s on an [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) installation, the plugin validates certificates for that server. If you haven’t installed the server certificates in your truststore, an SSL error occurs. To avoid this problem, you can run the plugin in an insecure mode, which skips the security validations. You can use the **armInsecure** tag or the **arm.insecure** system property. > [!WARNING] Enabling an insecure connection is a dangerous practice. Don’t use this unless you know > what you are doing and your On-Premises installation is isolated in a local network. See the configuration example below: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${target} ${target.type} ${username} ${password} ${environment} true ``` ## Deploy a Mule Application Using the Runtime Manager Agent Inside the `plugin` element, add a configuration for your Runtime Manager agent deployment, replacing the URI value with your remote server information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true http://localhost:9999/ ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Runtime Manager Agent Deployment Parameters Reference
ParameterDescriptionRequired

agentDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The server URI where your Mule instances are installed.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Domain The Mule Maven plugin supports deploying domains only when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. To deploy a domain, use the same configuration and deployment steps you use when deploying an application. For example, to deploy a domain to a standalone instance: 1. Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} ${app.runtime} ``` 2. From the command line in your project’s folder, package the domain and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ## Deploy Applications in Parallel You can deploy applications in parallel to on-premises Mule instances. Deploying applications in parallel reduces the startup time when you deploy a large number of apps. To prevent deployment failure, ensure that applications are not dependent on each other because a particular start order cannot be guaranteed. Parallelism is fixed at 20. To enable parallel deployment: 1. Package or export your Mule applications to the `/apps` directory of your Mule runtime engine instance. 2. Start Mule using the `-M-Dmule.deployment.parallel` option: ```none mule -M-Dmule.deployment.parallel ``` After performing these steps, Mule deploys in parallel all applications in the `/apps` directory. ## Undeploy Applications You can undeploy Mule applications by deleting an app’s anchor file only instead of deleting the application folder directly. Deleting only the app’s anchor file: - Prevents any interference from the hot-deployment layer and leaves no room for concurrent conflicting actions. - Avoids potential application JAR file locking issues on some operation systems and allows for clean shutdown and undeployment. For example, if the `stockTrader` app is running (app folder is there as well as the `$MULE_HOME/apps/stockTrader-anchor.txt` file), just delete the anchor file to have the app removed from the Mule instance at runtime. Application folder is removed after the app terminates. > [!NOTE] After undeploying a Mule application, there is a timeout of 15 seconds until > `LoggerContext` stops. Log files for an application only release after this timeout expires. This > information is important in Windows, where you can’t remove files that are in use by other > processes. After undeploying a Mule application, there is a timeout of 15 seconds until > LoggerContext stops. Log files for an application only release after this timeout expires. This > information is important in Windows, where you can’t remove files that are in use by other > processes. ## Update Applications at Runtime Updating a Mule application at runtime can be a complex change involving class modifications, endpoint modifications (for example, changing ports), and reconfiguring flows. An application update first performs a graceful app shutdown and then reconfigures itself in the background within seconds. This process is transparent for the users. There are two ways you can update an application: - By adding the modifications over an existing unpacked app folder and touching the main configuration file (`mule-config.xml` located in the app’s root directory by default). For this option to be valid, start the runtime with the system property `-M-Dmule.deployment.forceParseConfigXmls=true`. - By adding a new `jar` with an updated version of the app into the `$MULE_HOME/apps` directory. Mule detects the `jar` as an updated version of an existing application and ensures the update by a clean redeployment of the app. Note that Mule discards any modifications to the old application folder. The new app folder is a clean unpacked application from a `jar`. Either method integrates well with existing build tools. ## See Also - [Anypoint Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.9/mmp-concept) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Deploy Applications to On-Premises Mule Instances Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Studio, Anypoint Runtime Manager, or the Anypoint Platform CLI to deploy applications on-premises, you can also deploy Mule applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure the desired deployment strategy in your project’s `pom.xml` file. If you want to deploy applications on-premises using a different method, see: - [Deploy Applications On-Premises Using Runtime Manager](https://docs.mulesoft.com/runtime-manager/deploying-to-your-own-servers) - [Deploy Applications On-Premises Using the Anypoint Platform CLI](https://docs.mulesoft.com/anypoint-cli/latest/standalone-apps#runtime-mgr-standalone-application-deploy) - [Deploy Applications On-Premises Using Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages#export-project-studio) ## On-premises Deployment Strategies When you deploy applications on-premises using the Mule Maven plugin, you can select three different methods for deployment: - Standalone deployment By using this method you perform a manual deployment of your Mule application to your on-premises Mule instance. - Runtime Manager REST API deployment This method enables you to deploy an application using the Runtime Manager REST API, which links your on-premises Mule instance with your Anypoint Runtime Manager account, where you can do further management and monitoring of your deployed application. - Runtime Manager Agent deployment This method enables you to deploy an application using the Runtime Manager agent, which exposes a local API that you can call to manage and monitor your deployed application. The Mule Maven plugin also supports deploying domains when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. Additional operations enable you to deploy applications in parallel and update applications at runtime. ## Prerequisites - Add the Mule Maven Plugin to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. ## Deploy a Mule Application to a Standalone Mule Runtime Engine Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} ${app.runtime} ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Standalone Deployment Parameters Reference
ParameterDescriptionRequired

standaloneDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version running in your local machine instance.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

muleHome

The location of the Mule instance in your local machine.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Mule Application Using the Runtime Manager REST API Mule Maven plugin enables you to deploy a Mule Application to a local Mule instance using the Runtime Manager REST API. ### Prerequisites - You need a server, server group or cluster created in Runtime Manager. - To create a server, see [Add Servers](https://docs.mulesoft.com/runtime-manager/servers-create). - To create a server group, see [Create Server Groups](https://docs.mulesoft.com/runtime-manager/server-group-create). - To create a cluster, see [Create Clusters](https://docs.mulesoft.com/runtime-manager/cluster-create). ### Deploying Using the Runtime Manager REST API Inside the `plugin` element, add a configuration for your Runtime Manager deployment, replacing the placeholder values with your Runtime Manager information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${app.runtime} https://anypoint.mulesoft.com ${target} ${target.type} ${username} ${password} ${environment} value ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Authenticate with the username and password for the server where your Mule instances are installed.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Manager REST API Deployment Parameters Reference](#arm-deploy-reference). ### Runtime Manager REST API Deployment Parameters Reference
ParameterDescriptionRequired

armDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The Anypoint Platform URI. If you are using Anypoint Platform PCE, specify this parameter with your Anypoint Platform installation URI.
If not set, by default this value is set to https://anypoint.mulesoft.com.

No

target

The server name for the server where your Mule instances are installed.

Yes

targetType

The type of target to which you are deploying.

Valid values are:

  • server

  • serverGroup

  • cluster

Yes

username

Your username for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

password

Your password for the server where your Mule instances are installed.

Only when using Anypoint Platform credentials to login.

environment

The environment name for the server where your Mule instances are installed. This value must match any environment configured in your Runtime Manager account.
For Example:

<environment>Sandbox</environment>

Yes

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

### Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ### Troubleshoot TLS Errors in Anypoint Private Cloud Edition When trying to connect to an instance of Runtime Manager that’s on an [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) installation, the plugin validates certificates for that server. If you haven’t installed the server certificates in your truststore, an SSL error occurs. To avoid this problem, you can run the plugin in an insecure mode, which skips the security validations. You can use the **armInsecure** tag or the **arm.insecure** system property. > [!WARNING] Enabling an insecure connection is a dangerous practice. Don’t use this unless you know > what you are doing and your On-Premises installation is isolated in a local network. See the configuration example below: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${target} ${target.type} ${username} ${password} ${environment} true ``` ## Deploy a Mule Application Using the Runtime Manager Agent Inside the `plugin` element, add a configuration for your Runtime Manager agent deployment, replacing the URI value with your remote server information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true http://localhost:9999/ ``` From the command line in your project’s folder, package the application and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ### Runtime Manager Agent Deployment Parameters Reference
ParameterDescriptionRequired

agentDeployment

Top-Level Element.

Yes

applicationName

Specifies the application name to use during deployment.

Yes

muleVersion

The Mule version required for your application to run in your deployment target.
If this value does not match the Mule version running in your deployment target, the plugin raises an exception.

The Mule Maven Plugin does not download a Mule runtime engine if these values don’t match.

Yes

uri

The server URI where your Mule instances are installed.

Yes

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

## Deploy a Domain The Mule Maven plugin supports deploying domains only when using the standalone deployment strategy, or the Runtime Manager agent deployment strategy. To deploy a domain, use the same configuration and deployment steps you use when deploying an application. For example, to deploy a domain to a standalone instance: 1. Inside the `plugin` element, add a configuration for your standalone deployment, replacing the placeholder values with your local Mule runtime engine information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} ${app.runtime} ``` 2. From the command line in your project’s folder, package the domain and execute the deploy goal: ```console mvn clean deploy -DmuleDeploy ``` ## Deploy Applications in Parallel You can deploy applications in parallel to on-premises Mule instances. Deploying applications in parallel reduces the startup time when you deploy a large number of apps. To prevent deployment failure, ensure that applications are not dependent on each other because a particular start order cannot be guaranteed. Parallelism is fixed at 20. To enable parallel deployment: 1. Package or export your Mule applications to the `/apps` directory of your Mule runtime engine instance. 2. Start Mule using the `-M-Dmule.deployment.parallel` option: ```none mule -M-Dmule.deployment.parallel ``` After performing these steps, Mule deploys in parallel all applications in the `/apps` directory. ## Undeploy Applications You can undeploy Mule applications by deleting an app’s anchor file only instead of deleting the application folder directly. Deleting only the app’s anchor file: - Prevents any interference from the hot-deployment layer and leaves no room for concurrent conflicting actions. - Avoids potential application JAR file locking issues on some operation systems and allows for clean shutdown and undeployment. For example, if the `stockTrader` app is running (app folder is there as well as the `$MULE_HOME/apps/stockTrader-anchor.txt` file), just delete the anchor file to have the app removed from the Mule instance at runtime. Application folder is removed after the app terminates. > [!NOTE] After undeploying a Mule application, there is a timeout of 15 seconds until > `LoggerContext` stops. Log files for an application only release after this timeout expires. This > information is important in Windows, where you can’t remove files that are in use by other > processes. After undeploying a Mule application, there is a timeout of 15 seconds until > LoggerContext stops. Log files for an application only release after this timeout expires. This > information is important in Windows, where you can’t remove files that are in use by other > processes. ## Update Applications at Runtime Updating a Mule application at runtime can be a complex change involving class modifications, endpoint modifications (for example, changing ports), and reconfiguring flows. An application update first performs a graceful app shutdown and then reconfigures itself in the background within seconds. This process is transparent for the users. There are two ways you can update an application: - By adding the modifications over an existing unpacked app folder and touching the main configuration file (`mule-config.xml` located in the app’s root directory by default). For this option to be valid, start the runtime with the system property `-M-Dmule.deployment.forceParseConfigXmls=true`. - By adding a new `jar` with an updated version of the app into the `$MULE_HOME/apps` directory. Mule detects the `jar` as an updated version of an existing application and ensures the update by a clean redeployment of the app. Note that Mule discards any modifications to the old application folder. The new app folder is a clean unpacked application from a `jar`. Either method integrates well with existing build tools. ## See Also - [Anypoint Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) --- product: Mule Runtime version: 4.11 --- # Deploy Applications to Runtime Fabric Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to Anypoint Runtime Fabric, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your Runtime Fabric deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to Runtime Fabric using a different method, see: - [Deploy Applications to Runtime Fabric Using Runtime Manager](https://docs.mulesoft.com/runtime-fabric/latest/deploy-to-runtime-fabric) ## Prerequisites - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - You understand and have available the number of resources required to deploy to Runtime Fabric See [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed)for more information. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). ## Configure the Runtime Fabric Deployment Strategy Inside the `plugin` element, add a configuration for your Runtime Fabric deployment, replacing the following placeholder values with your Runtime Fabric information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com 4.3.0 user pass newapp rtf Sandbox MC 1 value false recreate false false false 20m 1500m 700Mi url ``` ## Deploy to Runtime Fabric From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into Runtime Fabric. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to Runtime Fabric via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to Runtime Fabric To redeploy the application, run the same command as you did to deploy. Runtime Fabric rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a Runtime Fabric username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Fabric Deployment Parameters Reference](#rtf-deploy-reference). ## Runtime Fabric Deployment Parameters Reference
ParameterDescriptionRequired

runtimeFabricDeployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your Runtime Fabric instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to choose a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

target

The Runtime Fabric target name where to deploy the app.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for Runtime Fabric.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy. The maximum number of replicas per application is 16.

Only when autoscaling is set to false.

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct Runtime Fabric to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

resources

cpu

reserved

Specifies the number of cores to allocate for each application replica. The default value is 0.5 vCores.

limit

Specifies the number of max cores to allocate for each replica of the application.
If a reserved configuration is present, ensure that this value is equal or higher.

memory

reserved

Specifies the amount of memory to allocate for each application replica. The default value is 700 MB.

limit

Specifies the maximum memory allocated per application replica. If a reserved configuration is present, ensure that this value is equal or higher.

Configuration example:

<deploymentSettings>
  <resources>
    <cpu>
      <reserved>20m</reserved>
      <limit>1500m</limit>
    </cpu>
    <memory>
      <reserved>700Mi</reserved>
    </memory>
  </resources>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application.

Configuration example using wildcard URL:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.example.com</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

Configuration example for path-based routing:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://www.example.com/myapp</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

persistentObjectStore

Configures the Mule application to use a persistent object store. By default, it is set to false.

jvm

args

Specifies JVM arguments to pass to Runtime Fabric when deploying the application. Use spaces to separate each argument.

Configuration example:

<deploymentSettings>
  <jvm>
    <args>
      -XX:MaxMetaspaceSize=500m -XX:MaxRAMPercentage=60.0
    </args>
  </jvm>
</deploymentSettings>

generateDefaultPublicUrl

Not applicable for Runtime Fabric BYOK. By default, it is set to false

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. By default, it is set to false.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>
## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) --- product: Mule Runtime version: 4.12 --- # Deploy Applications to Runtime Fabric Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to Anypoint Runtime Fabric, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your Runtime Fabric deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to Runtime Fabric using a different method, see: - [Deploy Applications to Runtime Fabric Using Runtime Manager](https://docs.mulesoft.com/runtime-fabric/latest/deploy-to-runtime-fabric) ## Prerequisites - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - You understand and have available the number of resources required to deploy to Runtime Fabric See [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed)for more information. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). ## Configure the Runtime Fabric Deployment Strategy Inside the `plugin` element, add a configuration for your Runtime Fabric deployment, replacing the following placeholder values with your Runtime Fabric information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com 4.3.0 user pass newapp rtf Sandbox MC 1 value false recreate false false false 20m 1500m 700Mi url ``` ## Deploy to Runtime Fabric From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into Runtime Fabric. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to Runtime Fabric via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to Runtime Fabric To redeploy the application, run the same command as you did to deploy. Runtime Fabric rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a Runtime Fabric username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Fabric Deployment Parameters Reference](#rtf-deploy-reference). ## Runtime Fabric Deployment Parameters Reference
ParameterDescriptionRequired

runtimeFabricDeployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your Runtime Fabric instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to choose a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

target

The Runtime Fabric target name where to deploy the app.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for Runtime Fabric.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy. The maximum number of replicas per application is 16.

Only when autoscaling is set to false.

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct Runtime Fabric to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

resources

cpu

reserved

Specifies the number of cores to allocate for each application replica. The default value is 0.5 vCores.

limit

Specifies the number of max cores to allocate for each replica of the application.
If a reserved configuration is present, ensure that this value is equal or higher.

memory

reserved

Specifies the amount of memory to allocate for each application replica. The default value is 700 MB.

limit

Specifies the maximum memory allocated per application replica. If a reserved configuration is present, ensure that this value is equal or higher.

Configuration example:

<deploymentSettings>
  <resources>
    <cpu>
      <reserved>20m</reserved>
      <limit>1500m</limit>
    </cpu>
    <memory>
      <reserved>700Mi</reserved>
    </memory>
  </resources>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application.

Configuration example using wildcard URL:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.example.com</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

Configuration example for path-based routing:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://www.example.com/myapp</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

persistentObjectStore

Configures the Mule application to use a persistent object store. By default, it is set to false.

jvm

args

Specifies JVM arguments to pass to Runtime Fabric when deploying the application. Use spaces to separate each argument.

Configuration example:

<deploymentSettings>
  <jvm>
    <args>
      -XX:MaxMetaspaceSize=500m -XX:MaxRAMPercentage=60.0
    </args>
  </jvm>
</deploymentSettings>

generateDefaultPublicUrl

Not applicable for Runtime Fabric BYOK. By default, it is set to false

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. By default, it is set to false.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>
## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) --- product: Mule Runtime version: 4.3 --- # Deploy Applications to Runtime Fabric Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to Anypoint Runtime Fabric, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your Runtime Fabric deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to Runtime Fabric using a different method, see: - [Deploy Applications to Runtime Fabric Using Runtime Manager](https://docs.mulesoft.com/runtime-fabric/latest/deploy-to-runtime-fabric) ## Prerequisites - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - You understand and have available the number of resources required to deploy to Runtime Fabric See [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed)for more information. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). ## Configure the Runtime Fabric Deployment Strategy Inside the `plugin` element, add a configuration for your Runtime Fabric deployment, replacing the following placeholder values with your Runtime Fabric information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com 4.3.0 user pass newapp rtf Sandbox MC 1 value false recreate false false false 20m 1500m 700Mi url ``` ## Deploy to Runtime Fabric From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into Runtime Fabric. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to Runtime Fabric via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to Runtime Fabric To redeploy the application, run the same command as you did to deploy. Runtime Fabric rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a Runtime Fabric username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Fabric Deployment Parameters Reference](#rtf-deploy-reference). ## Runtime Fabric Deployment Parameters Reference
ParameterDescriptionRequired

runtimeFabricDeployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your Runtime Fabric instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to choose a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

target

The Runtime Fabric target name where to deploy the app.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for Runtime Fabric.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy. The maximum number of replicas per application is 16.

Only when autoscaling is set to false.

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct Runtime Fabric to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

resources

cpu

reserved

Specifies the number of cores to allocate for each application replica. The default value is 0.5 vCores.

limit

Specifies the number of max cores to allocate for each replica of the application.
If a reserved configuration is present, ensure that this value is equal or higher.

memory

reserved

Specifies the amount of memory to allocate for each application replica. The default value is 700 MB.

limit

Specifies the maximum memory allocated per application replica. If a reserved configuration is present, ensure that this value is equal or higher.

Configuration example:

<deploymentSettings>
  <resources>
    <cpu>
      <reserved>20m</reserved>
      <limit>1500m</limit>
    </cpu>
    <memory>
      <reserved>700Mi</reserved>
    </memory>
  </resources>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application.

Configuration example using wildcard URL:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.example.com</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

Configuration example for path-based routing:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://www.example.com/myapp</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

persistentObjectStore

Configures the Mule application to use a persistent object store. By default, it is set to false.

jvm

args

Specifies JVM arguments to pass to Runtime Fabric when deploying the application. Use spaces to separate each argument.

Configuration example:

<deploymentSettings>
  <jvm>
    <args>
      -XX:MaxMetaspaceSize=500m -XX:MaxRAMPercentage=60.0
    </args>
  </jvm>
</deploymentSettings>

generateDefaultPublicUrl

Not applicable for Runtime Fabric BYOK. By default, it is set to false

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. By default, it is set to false.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>
## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) --- product: Mule Runtime version: 4.4 --- # Deploy Applications to Runtime Fabric Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to Anypoint Runtime Fabric, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your Runtime Fabric deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to Runtime Fabric using a different method, see: - [Deploy Applications to Runtime Fabric Using Runtime Manager](https://docs.mulesoft.com/runtime-fabric/latest/deploy-to-runtime-fabric) ## Prerequisites - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - You understand and have available the number of resources required to deploy to Runtime Fabric See [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed)for more information. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). ## Configure the Runtime Fabric Deployment Strategy Inside the `plugin` element, add a configuration for your Runtime Fabric deployment, replacing the following placeholder values with your Runtime Fabric information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com 4.3.0 user pass newapp rtf Sandbox MC 1 value false recreate false false false 20m 1500m 700Mi url ``` ## Deploy to Runtime Fabric From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into Runtime Fabric. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to Runtime Fabric via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to Runtime Fabric To redeploy the application, run the same command as you did to deploy. Runtime Fabric rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a Runtime Fabric username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Fabric Deployment Parameters Reference](#rtf-deploy-reference). ## Runtime Fabric Deployment Parameters Reference
ParameterDescriptionRequired

runtimeFabricDeployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your Runtime Fabric instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to choose a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

target

The Runtime Fabric target name where to deploy the app.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for Runtime Fabric.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy. The maximum number of replicas per application is 16.

Only when autoscaling is set to false.

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct Runtime Fabric to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

resources

cpu

reserved

Specifies the number of cores to allocate for each application replica. The default value is 0.5 vCores.

limit

Specifies the number of max cores to allocate for each replica of the application.
If a reserved configuration is present, ensure that this value is equal or higher.

memory

reserved

Specifies the amount of memory to allocate for each application replica. The default value is 700 MB.

limit

Specifies the maximum memory allocated per application replica. If a reserved configuration is present, ensure that this value is equal or higher.

Configuration example:

<deploymentSettings>
  <resources>
    <cpu>
      <reserved>20m</reserved>
      <limit>1500m</limit>
    </cpu>
    <memory>
      <reserved>700Mi</reserved>
    </memory>
  </resources>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application.

Configuration example using wildcard URL:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.example.com</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

Configuration example for path-based routing:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://www.example.com/myapp</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

persistentObjectStore

Configures the Mule application to use a persistent object store. By default, it is set to false.

jvm

args

Specifies JVM arguments to pass to Runtime Fabric when deploying the application. Use spaces to separate each argument.

Configuration example:

<deploymentSettings>
  <jvm>
    <args>
      -XX:MaxMetaspaceSize=500m -XX:MaxRAMPercentage=60.0
    </args>
  </jvm>
</deploymentSettings>

generateDefaultPublicUrl

Not applicable for Runtime Fabric BYOK. By default, it is set to false

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. By default, it is set to false.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>
## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) --- product: Mule Runtime version: 4.6 --- # Deploy Applications to Runtime Fabric Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to Anypoint Runtime Fabric, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your Runtime Fabric deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to Runtime Fabric using a different method, see: - [Deploy Applications to Runtime Fabric Using Runtime Manager](https://docs.mulesoft.com/runtime-fabric/latest/deploy-to-runtime-fabric) ## Prerequisites - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - You understand and have available the number of resources required to deploy to Runtime Fabric See [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed)for more information. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). ## Configure the Runtime Fabric Deployment Strategy Inside the `plugin` element, add a configuration for your Runtime Fabric deployment, replacing the following placeholder values with your Runtime Fabric information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com 4.3.0 user pass newapp rtf Sandbox MC 1 value false recreate false false false 20m 1500m 700Mi url ``` ## Deploy to Runtime Fabric From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into Runtime Fabric. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to Runtime Fabric via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to Runtime Fabric To redeploy the application, run the same command as you did to deploy. Runtime Fabric rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a Runtime Fabric username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Fabric Deployment Parameters Reference](#rtf-deploy-reference). ## Runtime Fabric Deployment Parameters Reference
ParameterDescriptionRequired

runtimeFabricDeployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your Runtime Fabric instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to choose a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

target

The Runtime Fabric target name where to deploy the app.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for Runtime Fabric.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy. The maximum number of replicas per application is 16.

Only when autoscaling is set to false.

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct Runtime Fabric to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

resources

cpu

reserved

Specifies the number of cores to allocate for each application replica. The default value is 0.5 vCores.

limit

Specifies the number of max cores to allocate for each replica of the application.
If a reserved configuration is present, ensure that this value is equal or higher.

memory

reserved

Specifies the amount of memory to allocate for each application replica. The default value is 700 MB.

limit

Specifies the maximum memory allocated per application replica. If a reserved configuration is present, ensure that this value is equal or higher.

Configuration example:

<deploymentSettings>
  <resources>
    <cpu>
      <reserved>20m</reserved>
      <limit>1500m</limit>
    </cpu>
    <memory>
      <reserved>700Mi</reserved>
    </memory>
  </resources>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application.

Configuration example using wildcard URL:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.example.com</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

Configuration example for path-based routing:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://www.example.com/myapp</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

persistentObjectStore

Configures the Mule application to use a persistent object store. By default, it is set to false.

jvm

args

Specifies JVM arguments to pass to Runtime Fabric when deploying the application. Use spaces to separate each argument.

Configuration example:

<deploymentSettings>
  <jvm>
    <args>
      -XX:MaxMetaspaceSize=500m -XX:MaxRAMPercentage=60.0
    </args>
  </jvm>
</deploymentSettings>

generateDefaultPublicUrl

Not applicable for Runtime Fabric BYOK. By default, it is set to false

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. By default, it is set to false.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>
## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) --- product: Mule Runtime version: 4.9 --- # Deploy Applications to Runtime Fabric Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to Anypoint Runtime Fabric, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your Runtime Fabric deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to Runtime Fabric using a different method, see: - [Deploy Applications to Runtime Fabric Using Runtime Manager](https://docs.mulesoft.com/runtime-fabric/latest/deploy-to-runtime-fabric) ## Prerequisites - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - You understand and have available the number of resources required to deploy to Runtime Fabric See [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed)for more information. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). ## Configure the Runtime Fabric Deployment Strategy Inside the `plugin` element, add a configuration for your Runtime Fabric deployment, replacing the following placeholder values with your Runtime Fabric information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com 4.3.0 user pass newapp rtf Sandbox MC 1 value false recreate false false false 20m 1500m 700Mi url ``` ## Deploy to Runtime Fabric From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into Runtime Fabric. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to Runtime Fabric via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to Runtime Fabric To redeploy the application, run the same command as you did to deploy. Runtime Fabric rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a Runtime Fabric username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Fabric Deployment Parameters Reference](#rtf-deploy-reference). ## Runtime Fabric Deployment Parameters Reference
ParameterDescriptionRequired

runtimeFabricDeployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your Runtime Fabric instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to choose a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

target

The Runtime Fabric target name where to deploy the app.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for Runtime Fabric.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy. The maximum number of replicas per application is 16.

Only when autoscaling is set to false.

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct Runtime Fabric to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

resources

cpu

reserved

Specifies the number of cores to allocate for each application replica. The default value is 0.5 vCores.

limit

Specifies the number of max cores to allocate for each replica of the application.
If a reserved configuration is present, ensure that this value is equal or higher.

memory

reserved

Specifies the amount of memory to allocate for each application replica. The default value is 700 MB.

limit

Specifies the maximum memory allocated per application replica. If a reserved configuration is present, ensure that this value is equal or higher.

Configuration example:

<deploymentSettings>
  <resources>
    <cpu>
      <reserved>20m</reserved>
      <limit>1500m</limit>
    </cpu>
    <memory>
      <reserved>700Mi</reserved>
    </memory>
  </resources>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application.

Configuration example using wildcard URL:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.example.com</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

Configuration example for path-based routing:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://www.example.com/myapp</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

persistentObjectStore

Configures the Mule application to use a persistent object store. By default, it is set to false.

jvm

args

Specifies JVM arguments to pass to Runtime Fabric when deploying the application. Use spaces to separate each argument.

Configuration example:

<deploymentSettings>
  <jvm>
    <args>
      -XX:MaxMetaspaceSize=500m -XX:MaxRAMPercentage=60.0
    </args>
  </jvm>
</deploymentSettings>

generateDefaultPublicUrl

Not applicable for Runtime Fabric BYOK. By default, it is set to false

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. By default, it is set to false.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>
## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Deploy Applications to Runtime Fabric Using the Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In addition to using Anypoint Runtime Manager, to deploy applications to Anypoint Runtime Fabric, you can also deploy applications by using the Mule Maven plugin. To do so, you must meet certain prerequisites, and configure your Runtime Fabric deployment strategy in your project’s `pom.xml` file. If you want to deploy applications to Runtime Fabric using a different method, see: - [Deploy Applications to Runtime Fabric Using Runtime Manager](https://docs.mulesoft.com/runtime-fabric/latest/deploy-to-runtime-fabric) ## Prerequisites - Ensure that the Mule Maven Plugin is added to your project See [Add the Mule Maven Plugin to a Mule Project](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#add-mmp) for instructions. - You understand and have available the number of resources required to deploy to Runtime Fabric See [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed)for more information. - The application is already published in Exchange See [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). ## Configure the Runtime Fabric Deployment Strategy Inside the `plugin` element, add a configuration for your Runtime Fabric deployment, replacing the following placeholder values with your Runtime Fabric information: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true https://anypoint.mulesoft.com 4.3.0 user pass newapp rtf Sandbox MC 1 value false recreate false false false 20m 1500m 700Mi url ``` ## Deploy to Runtime Fabric From the command line in your project’s folder, package the application and execute the deploy goal: ```bash mvn clean deploy -DmuleDeploy ``` ### Exchange Snapshot Assets You can also deploy Exchange snapshot assets into Runtime Fabric. By using `SNAPSHOT` version assets in Anypoint Exchange during the development and testing phase, you can avoid incrementing your application’s version number for small changes. After your `SNAPSHOT` version application has been overwritten in Anypoint Exchange, you can redeploy your `SNAPSHOT` version application to Runtime Fabric via the Mule Maven plugin to deploy the latest changes. To learn more about publishing snapshot assets to Anypoint Exchange, see [Asset Lifecycle State](https://docs.mulesoft.com/exchange/to-publish-assets-maven#asset-lifecycle-state). > [!NOTE] Each time you update your application’s snapshot, redeploy the application to refresh it > with the latest snapshot binaries. > > Because snapshot assets can change after deployment, avoid deploying them into your production > environment. ## Redeploy to Runtime Fabric To redeploy the application, run the same command as you did to deploy. Runtime Fabric rewrites the application you had deployed. ## Authentication Methods When you deploy applications using Mule Maven plugin, you can use different methods to provide your credentials to authenticate against the deployment platform. Depending on the authentication method you use, the parameters to set in the deployment configuration differ:
Authentication MethodDescriptionConfiguration Parameters

Username and password

Use a Runtime Fabric username and password to authenticate.

  • username

  • password

Server

Use credentials stored in a Maven server, configured inside the Maven settings.xml file.

  • server

Authorization Token

Use an authorization token to access the platform.
See Identity Management for a list of supported single sign-on (SSO) types.

  • authToken

Connected Apps

Use a Connected App to perform the authentication programmatically by communicating with Anypoint Platform.
Note that the Connected App credentials must have the Design Center Developer access scope.
See Connected Apps for Developers for instructions about creating Connected Apps.

  • connectedAppClientId

  • connectedAppClientSecret

  • connectedAppGrantType

For a detailed description of the configuration parameters, see the [Runtime Fabric Deployment Parameters Reference](#rtf-deploy-reference). ## Runtime Fabric Deployment Parameters Reference
ParameterDescriptionRequired

runtimeFabricDeployment

Top-Level Element

Yes

uri

Your Anypoint Platform URI.
If not set, defaults to https://anypoint.mulesoft.com.

No

muleVersion

The Mule runtime engine version to run in your Runtime Fabric instance.
Ensure that this value is equal to or higher than the earliest required Mule version of your application. By default, the latest available Mule version is selected.
Example values: 4.6.0 selects the last build where it defaults to Edge channel and Java 8. If you want to choose a different LTS or Edge selection or Java version, specify the full Mule version name as in 4.6.0:1e-java17.
When using Mule Maven plugin versions 3.8.0 and 4.0.0 for deployments, the muleVersion property doesn’t allow you to specify releaseChannel and javaVersion. To specify these properties, upgrade the plugin to version 4.1.1 or later.

No

releaseChannel

Set the name of the release channel used to select the Mule image. Supported values are NONE, EDGE, and LTS. By default, the value is set to EDGE. If the selected release channel doesn’t exist, an error occurs.

No

javaVersion

Set the Java version used in the deploy. Supported values are 8 and 17. By default, the value is set to 8. If the selected Java version doesn’t exist, an error occurs.

No

username

Your Anypoint Platform username

Only when using Anypoint Platform credentials to login.

password

Your Anypoint Platform password

Only when using Anypoint Platform credentials to login.

applicationName

The application name displayed in Runtime Manager after the app deploys.

Yes

target

The Runtime Fabric target name where to deploy the app.

Yes

provider

Provider MC (MuleSoft Control Plane) indicates that the deployment is managed through Anypoint Runtime Manager. Set to MC for Runtime Fabric.

Yes

environment

Target Anypoint Platform environment.
This value must match an environment configured in your Anypoint Platform account, as shown here:

<environment>Sandbox</environment>

Yes

replicas

Specifies the number of replicas, or instances, of the Mule application to deploy. The maximum number of replicas per application is 16.

Only when autoscaling is set to false.

businessGroup

The Business group path of the deployment
Specify the full hierarchical path from the parent organization to the target Business group, for example:

<businessGroup>ParentOrg\SubOrg1\myBusinessGroup</businessGroup>

This value is omitted if businessGroupId is set. If businessGroup and businessGroupId are not set, the value defaults to the main business group of the user.

No

businessGroupId

The Business group ID of the deployment
Instead of specifying the Business group path, you can specify the Business group ID to deploy your application. If businessGroupId and businessGroup are not set, the value defaults to the main business group of the user.
The Business group ID is a mandatory parameter when you have access only to a specific Business group but not to the parent organization.
This parameter is available in plugin version 3.2.7 and later.

No

deploymentTimeout

The allowed elapsed time, in milliseconds, between the start of the deployment process and the confirmation that the artifact has been deployed

The default value is 600000.

No

server

Maven server with Anypoint Platform credentials
This is only needed if you want to use your credentials stored in your Maven settings.xml file. This is not the Mule server name.

No

properties

Top-Level element
If you need to set properties for the Mule application you are deploying, you can use the <properties> top-level element:

<properties>
  <key>value</key>
</properties>

For example:

<properties>
  <http.port>8081</http.port>
</properties>

No

propertiesFile

Top-level element
Specifies a file that contains properties for the Mule application being deployed. Use this parameter as an alternative to defining properties inline with <properties>. The file must use the Java properties format, with one key=value pair per line.

No

secureProperties

Top-Level element
Use the secureProperties top-level element to set properties for the Mule application and instruct Runtime Fabric to encrypt the values before storing them:

<secureProperties>
  <key>value</key>
</secureProperties>

For example:

<secureProperties>
  <http.port>8081</http.port>
</secureProperties>

No

skip

When set to true, skips the plugin deployment goal.
Its default value is false.

No

skipDeploymentVerification

When set to true, skips the status verification of your deployed app.
Its default value is false.

No

authToken

Specifies the authorization token to access the platform. You can use this authentication method instead of setting username and password.
See Identity Management for a list of supported single sign-on (SSO) types.

Only when using an Authorization token to login.

connectedAppClientId

Specifies the Connected App clientID value.

Only when using Connected Apps credentials to login.

connectedAppClientSecret

Specifies the Connected App secret key.

Only when using Connected Apps credentials to login.

connectedAppGrantType

Specifies the only supported connection type: client_credentials.

Only when using Connected Apps credentials to login.

deploymentSettings

Any of the parameters documented in deploymentSettings Reference

No

### deploymentSettings Parameters Reference
ParameterDescription

enforceDeployingReplicasAcrossNodes

Enforces the deployment of replicas across different nodes. The default value is false.

Configuration example:

<deploymentSettings>
  <enforceDeployingReplicasAcrossNodes>false</enforceDeployingReplicasAcrossNodes>
</deploymentSettings>

updateStrategy

Accepted valuesDescription

rolling

Maintains availability by updating replicas incrementally. Requires one additional replica’s worth of resources to succeed.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is one less than the total number of nodes.

recreate

Terminates replicas before re-deployment. Re-deployment is quicker than rolling and doesn’t require additional resources.
If enforceDeployingReplicasAcrossNodes is enabled, the maximum number of replicas you can configure is equal to the number of nodes.

The default value is rolling.

Configuration example:

<deploymentSettings>
  <updateStrategy>recreate</updateStrategy>
</deploymentSettings>

clustered

Enables clustering across two or more replicas of the application. The default value is false.

Configuration example:

<deploymentSettings>
    <clustered>true</clustered>
</deploymentSettings>

resources

cpu

reserved

Specifies the number of cores to allocate for each application replica. The default value is 0.5 vCores.

limit

Specifies the number of max cores to allocate for each replica of the application.
If a reserved configuration is present, ensure that this value is equal or higher.

memory

reserved

Specifies the amount of memory to allocate for each application replica. The default value is 700 MB.

limit

Specifies the maximum memory allocated per application replica. If a reserved configuration is present, ensure that this value is equal or higher.

Configuration example:

<deploymentSettings>
  <resources>
    <cpu>
      <reserved>20m</reserved>
      <limit>1500m</limit>
    </cpu>
    <memory>
      <reserved>700Mi</reserved>
    </memory>
  </resources>
</deploymentSettings>

http

inbound

publicUrl

URL of the deployed application.

Configuration example using wildcard URL:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://myapp.example.com</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

Configuration example for path-based routing:

<deploymentSettings>
  <http>
    <inbound>
      <publicUrl>https://www.example.com/myapp</publicUrl>
    </inbound>
  </http>
</deploymentSettings>

persistentObjectStore

Configures the Mule application to use a persistent object store. By default, it is set to false.

jvm

args

Specifies JVM arguments to pass to Runtime Fabric when deploying the application. Use spaces to separate each argument.

Configuration example:

<deploymentSettings>
  <jvm>
    <args>
      -XX:MaxMetaspaceSize=500m -XX:MaxRAMPercentage=60.0
    </args>
  </jvm>
</deploymentSettings>

generateDefaultPublicUrl

Not applicable for Runtime Fabric BYOK. By default, it is set to false

disableAmLogForwarding

Disables the application-level log forwarding to Anypoint Monitoring. By default, it is set to false.

autoscaling

Provides CPU based horizontal autoscaling configuration for deployment and redeployment operations. If autoscaling is disabled and the fields minReplicas and maxReplicas are provided, they must match the value of the target.replicas field. See Enable Trace Data Collection. Configuration example:

<deploymentSettings>
  <autoscaling>
    <enabled>true</enabled>
    <minReplicas>1</minReplicas>
    <maxReplicas>2</maxReplicas>
  </autoscaling>
</deploymentSettings>
## Encrypt Credentials To use encrypted credentials when deploying, you need to set up your Maven master encrypted password and your `settings-security.xml` file. 1. Create a master password for your Maven configuration. mvn --encrypt-master-password Maven returns your master password encrypted: {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} 2. Create a `settings-security.xml` file in your ~/.m2 repository and add your encrypted master password: ```xml {l9vZ2uM5SdgHy+H12z4pX7LEOZn3Kbnqmt3kIquLjnQ=} ``` 3. Encrypt your Anypoint platform password: mvn --encrypt-password Maven returns your Anypoint platform password encrypted: {HTWFGH5BG9QmvJ1B=} 4. Add your encrypted Anypoint Platform password to your `settings.xml` file in the section: ```xml ... ... my.anypoint.credentials my.anypoint.username {HTWFGH5BG9QmvJ1B=} ... ... ``` 5. In your configuration deployment, reference the credentials injecting the server ID configured in your `settings.xml` file: ```xml ... ... ... my.anypoint.credentials ... ... ... ``` > [!NOTE] Make sure that the username and password are not set in the deployment configuration, > or they will overwrite the defined server ID. ## See Also - [Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) --- product: Mule Runtime version: 4.11 keywords: deploy, deploying, cloudhub, on premises, on premise --- # Deploy Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications require deployment to a Mule runtime engine instance to run. MuleSoft supports three different deployment targets: CloudHub, Anypoint Runtime Fabric, and on-premises Mule instances. When you deploy applications to CloudHub or to Anypoint Runtime Fabric, these services automatically manage the Mule runtime engine instances needed to run the applications. If you deploy applications on-premises, the installation of Mule runtime engine is required. See [On-Premises Deployment Model](https://docs.mulesoft.com/on-premises/latest/mule-deployment-model) for more information about characteristics specific to on-premises deployments. In addition, different tools are available to deploy applications to each of the deployment targets:
Deployment TargetAvailable Deployment ToolsMule Runtime Engine Installation

CloudHub

  • Anypoint Code Builder

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub workers start Mule instances as part of the deployment process.

CloudHub 2.0

  • Anypoint Code Builder

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub 2.0 replicas start Mule instances as part of the deployment process.

Anypoint Runtime Fabric

  • Anypoint Runtime Manager

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because Anypoint Runtime Fabric internally starts Mule instances as part of the deployment process.

  • Installation of Anypoint Runtime Fabric in your desired infrastructure is required

On-premises

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • Installation of Mule runtime engine in your desired infrastructure is required.

  • You are responsible for the installation and configuration of your Mule instances.

## See Also - [CloudHub](https://docs.mulesoft.com/cloudhub/) - [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) - [Anypoint Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/) - [Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/) - [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.11/shared-resources) - [Mule High Availability Clusters](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.12 keywords: deploy, deploying, cloudhub, on premises, on premise --- # Deploy Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications require deployment to a Mule runtime engine instance to run. MuleSoft supports three different deployment targets: CloudHub, Anypoint Runtime Fabric, and on-premises Mule instances. When you deploy applications to CloudHub or to Anypoint Runtime Fabric, these services automatically manage the Mule runtime engine instances needed to run the applications. If you deploy applications on-premises, the installation of Mule runtime engine is required. See [On-Premises Deployment Model](https://docs.mulesoft.com/on-premises/latest/mule-deployment-model) for more information about characteristics specific to on-premises deployments. In addition, different tools are available to deploy applications to each of the deployment targets:
Deployment TargetAvailable Deployment ToolsMule Runtime Engine Installation

CloudHub

  • Anypoint Code Builder

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub workers start Mule instances as part of the deployment process.

CloudHub 2.0

  • Anypoint Code Builder

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub 2.0 replicas start Mule instances as part of the deployment process.

Anypoint Runtime Fabric

  • Anypoint Runtime Manager

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because Anypoint Runtime Fabric internally starts Mule instances as part of the deployment process.

  • Installation of Anypoint Runtime Fabric in your desired infrastructure is required

On-premises

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • Installation of Mule runtime engine in your desired infrastructure is required.

  • You are responsible for the installation and configuration of your Mule instances.

## See Also - [CloudHub](https://docs.mulesoft.com/cloudhub/) - [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) - [Anypoint Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/) - [Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/) - [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.12/shared-resources) - [Mule High Availability Clusters](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.3 keywords: deploy, deploying, cloudhub, on premises, on premise --- # Deploy Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications are deployed to a Mule runtime engine instance. MuleSoft supports three different deployment targets: CloudHub, Anypoint Runtime Fabric, and on-premises Mule instances. When you deploy applications to CloudHub or to Anypoint Runtime Fabric, these services take care of the Mule runtime engine instances needed to run applications. If you deploy applications on-premises, the installation of Mule runtime engine is required. See [On-Premises Deployment Model](https://docs.mulesoft.com/on-premises/latest/mule-deployment-model) for more information about characteristics specific to on-premises deployments. In addition, the tools available to deploy applications to each of the deployment targets differ:
Deployment TargetAvailable Deployment ToolsMule Runtime Engine Installation

CloudHub

  • Anypoint Studio

  • Anypoint Runtime Manager

  • Anypoint Platform CLI

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub workers start Mule instances as part of the deployment process.

Anypoint Runtime Fabric

  • Anypoint Runtime Manager

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because Anypoint Runtime Fabric internally starts Mule instances as part of the deployment process.

  • Installation of Anypoint Runtime Fabric in your desired infrastructure is required

On-premises

  • Anypoint Studio

  • Anypoint Runtime Manager

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Anypoint Platform CLI

  • Mule Maven plugin

  • Installation of Mule runtime engine in your desired infrastructure is required.

  • You are responsible for the installation and configuration of your Mule instances.

> [!NOTE] After End of Extended Support for Mule runtime 4.3, Mule applications deployed to CloudHub > or CloudHub 2.0 environments are stopped. ## See Also - [CloudHub](https://docs.mulesoft.com/cloudhub/) - [Anypoint Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/) - [Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/) - [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.3/shared-resources) - [Mule High Availability Clusters](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.4 keywords: deploy, deploying, cloudhub, on premises, on premise --- # Deploy Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications require deployment to a Mule runtime engine instance to run. MuleSoft supports three different deployment targets: CloudHub, Anypoint Runtime Fabric, and on-premises Mule instances. When you deploy applications to CloudHub or to Anypoint Runtime Fabric, these services automatically manage the Mule runtime engine instances needed to run the applications. If you deploy applications on-premises, the installation of Mule runtime engine is required. See [On-Premises Deployment Model](https://docs.mulesoft.com/on-premises/latest/mule-deployment-model) for more information about characteristics specific to on-premises deployments. In addition, different tools are available to deploy applications to each of the deployment targets:
Deployment TargetAvailable Deployment ToolsMule Runtime Engine Installation

CloudHub

  • Anypoint Code Builder

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub workers start Mule instances as part of the deployment process.

CloudHub 2.0

  • Anypoint Code Builder

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub 2.0 replicas start Mule instances as part of the deployment process.

Anypoint Runtime Fabric

  • Anypoint Runtime Manager

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because Anypoint Runtime Fabric internally starts Mule instances as part of the deployment process.

  • Installation of Anypoint Runtime Fabric in your desired infrastructure is required

On-premises

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • Installation of Mule runtime engine in your desired infrastructure is required.

  • You are responsible for the installation and configuration of your Mule instances.

> [!NOTE] After End of Extended Support for Mule runtime 4.4, Mule applications deployed to CloudHub > or CloudHub 2.0 environments are stopped. ## See Also - [CloudHub](https://docs.mulesoft.com/cloudhub/) - [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) - [Anypoint Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/) - [Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/) - [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.4/shared-resources) - [Mule High Availability Clusters](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.6 keywords: deploy, deploying, cloudhub, on premises, on premise --- # Deploy Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications require deployment to a Mule runtime engine instance to run. MuleSoft supports three different deployment targets: CloudHub, Anypoint Runtime Fabric, and on-premises Mule instances. When you deploy applications to CloudHub or to Anypoint Runtime Fabric, these services automatically manage the Mule runtime engine instances needed to run the applications. If you deploy applications on-premises, the installation of Mule runtime engine is required. See [On-Premises Deployment Model](https://docs.mulesoft.com/on-premises/latest/mule-deployment-model) for more information about characteristics specific to on-premises deployments. In addition, different tools are available to deploy applications to each of the deployment targets:
Deployment TargetAvailable Deployment ToolsMule Runtime Engine Installation

CloudHub

  • Anypoint Code Builder

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub workers start Mule instances as part of the deployment process.

CloudHub 2.0

  • Anypoint Code Builder

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub 2.0 replicas start Mule instances as part of the deployment process.

Anypoint Runtime Fabric

  • Anypoint Runtime Manager

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because Anypoint Runtime Fabric internally starts Mule instances as part of the deployment process.

  • Installation of Anypoint Runtime Fabric in your desired infrastructure is required

On-premises

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • Installation of Mule runtime engine in your desired infrastructure is required.

  • You are responsible for the installation and configuration of your Mule instances.

## See Also - [CloudHub](https://docs.mulesoft.com/cloudhub/) - [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) - [Anypoint Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/) - [Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/) - [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.6/shared-resources) - [Mule High Availability Clusters](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.9 keywords: deploy, deploying, cloudhub, on premises, on premise --- # Deploy Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications require deployment to a Mule runtime engine instance to run. MuleSoft supports three different deployment targets: CloudHub, Anypoint Runtime Fabric, and on-premises Mule instances. When you deploy applications to CloudHub or to Anypoint Runtime Fabric, these services automatically manage the Mule runtime engine instances needed to run the applications. If you deploy applications on-premises, the installation of Mule runtime engine is required. See [On-Premises Deployment Model](https://docs.mulesoft.com/on-premises/latest/mule-deployment-model) for more information about characteristics specific to on-premises deployments. In addition, different tools are available to deploy applications to each of the deployment targets:
Deployment TargetAvailable Deployment ToolsMule Runtime Engine Installation

CloudHub

  • Anypoint Code Builder

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub workers start Mule instances as part of the deployment process.

CloudHub 2.0

  • Anypoint Code Builder

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub 2.0 replicas start Mule instances as part of the deployment process.

Anypoint Runtime Fabric

  • Anypoint Runtime Manager

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because Anypoint Runtime Fabric internally starts Mule instances as part of the deployment process.

  • Installation of Anypoint Runtime Fabric in your desired infrastructure is required

On-premises

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • Installation of Mule runtime engine in your desired infrastructure is required.

  • You are responsible for the installation and configuration of your Mule instances.

## See Also - [CloudHub](https://docs.mulesoft.com/cloudhub/) - [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) - [Anypoint Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/) - [Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/) - [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.9/shared-resources) - [Mule High Availability Clusters](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: deploy, deploying, cloudhub, on premises, on premise --- # Deploy Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications require deployment to a Mule runtime engine instance to run. MuleSoft supports three different deployment targets: CloudHub, Anypoint Runtime Fabric, and on-premises Mule instances. When you deploy applications to CloudHub or to Anypoint Runtime Fabric, these services automatically manage the Mule runtime engine instances needed to run the applications. If you deploy applications on-premises, the installation of Mule runtime engine is required. See [On-Premises Deployment Model](https://docs.mulesoft.com/on-premises/latest/mule-deployment-model) for more information about characteristics specific to on-premises deployments. In addition, different tools are available to deploy applications to each of the deployment targets:
Deployment TargetAvailable Deployment ToolsMule Runtime Engine Installation

CloudHub

  • Anypoint Code Builder

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub workers start Mule instances as part of the deployment process.

CloudHub 2.0

  • Anypoint Code Builder

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because CloudHub 2.0 replicas start Mule instances as part of the deployment process.

Anypoint Runtime Fabric

  • Anypoint Runtime Manager

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • No installation of Mule runtime engine is required, because Anypoint Runtime Fabric internally starts Mule instances as part of the deployment process.

  • Installation of Anypoint Runtime Fabric in your desired infrastructure is required

On-premises

  • Anypoint Platform CLI

  • Anypoint Runtime Manager

  • Anypoint Studio

  • Runtime Manager in Anypoint Platform Private Cloud Edition

  • Mule Maven plugin

  • Installation of Mule runtime engine in your desired infrastructure is required.

  • You are responsible for the installation and configuration of your Mule instances.

## See Also - [CloudHub](https://docs.mulesoft.com/cloudhub/) - [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) - [Anypoint Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/) - [Anypoint Runtime Manager](https://docs.mulesoft.com/runtime-manager/) - [Anypoint Platform Private Cloud Edition](https://docs.mulesoft.com/private-cloud/latest/) - [Shared Resources](https://docs.mulesoft.com/mule-runtime/latest/shared-resources) - [Mule High Availability Clusters](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.11 --- # Developing Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Develop Mule applications to integrate systems, process data, and automate workflows. Mule applications read data from internal or external sources, transform it, and send the processed output to other systems. Mule applications run in Mule runtime engine (Mule). Requests to an application generate Mule events that move through flows for processing. Mule encodes the request and data in the event and passes them to single or multiple threads. ## Getting Started with Mule Application Development To get started with Mule application development, you can follow the steps in these tutorials: - [Create a "Hello World" Mule app](https://docs.mulesoft.com/mule-runtime/4.11/mule-app-dev-hellomule) Build a Mule application that interacts with a user in a simple HTTP request-response flow. - [Create a Mule app that uses the Database Connector and DataWeave](https://docs.mulesoft.com/mule-runtime/4.11/mule-app-tutorial) Build a Mule application that retrieves data from a database and transforms it to a new structure. ## Building Blocks of a Mule Application Mule applications use connectors, modules, and components to read, write, and process data. - [Connectors and Modules](https://docs.mulesoft.com/connectors/) Anypoint connectors provide components, such as listeners, that interact with external API endpoints and act on data in the Mule application. Modules, such as the Validation, Java, Spring, and OAuth, provide modules that act on data in a Mule application without providing a direct connection to an endpoint. - [Core Components](https://docs.mulesoft.com/mule-runtime/4.11/about-components) Core components support flow control, error handling, logging, batch, and other programmatic operations on data that flows through your application. ## DataWeave Language DataWeave is the primary language used for formulating expressions in Mule. Connectors, modules, and components support the use of DataWeave to access, manipulate, and transform data structures and output formats, and to extract data that is processed within the Mule application. At runtime, Mule evaluates DataWeave expressions while executing a flow to: - Extract data needed to process the current message - Set or manipulate a value in the message ## Mule Flows Understanding basic flow architecture is key to understanding a Mule application. Essentially, every Mule flow contains a series of Mule components that receive or process messages: ![A flow including an HTTP Listener, data transformation, database connection, and logging process](/mulesoft/current/en-us/mule-runtime/4.11/_images/flow-example.png) Figure 1. Simple Flow in Design Center At the simplest level, flows are sequences of processors. A message that enters a flow can pass through a variety of processors. In a typical flow, a Mule application receives a message through a source (such as an HTTP Listener component), transforms that message into a new format, and processes any business logic before writing the processed message to an external system in a format that the system can read. To separate processing into more manageable units, Mule applications often contain multiple, interrelated flows instead of just a single flow. One flow can call another flow as a direct reference. For more information about this topic, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.11/about-flows) and [Mule Components](https://docs.mulesoft.com/mule-runtime/4.11/mule-components). ### Sources A source component (or trigger) is the first component in a flow. It receives a triggering event, creates a corresponding Mule event, and forwards that event for processing by the next component in the flow. External clients can trigger processing in a Mule flow through several communication protocols and methods, such as JMS, HTTP, FTP, JDBC, or File. Mule translates these communication protocols and methods into a standard message format, which passes through the flow’s processors. Sources in Mule can connect to specific external sources, either through a standard protocol or a third-party API. It is also possible to set a Scheduler component. Some schedulers can poll for specific changes to external resources, such as new files or table rows in an external resource. Examples of listeners and connector operations that can trigger a flow include: - HTTP, JMS, and VM listeners in their associated connectors - On Table Row operation in the Database connector - On New or Updated File operation in the File and FTP connectors - Scheduler You can also create your own source using the [Mule SDK sources](https://docs.mulesoft.com/mule-sdk/latest/sources). Message sources don’t support expressions in configuration parameters that are evaluated before the flow executes because sources are initialized before the flow runs. The exception is [callback parameters](https://docs.mulesoft.com/mule-sdk/latest/sources-response#callback-parameters), which operate on the response generated by the flow and can use expressions. ### Processors After a flow is triggered through the source component, subsequent components process the data as it travels through the flow. By default, each processor that receives a Mule event returns a new Mule message, typically with a set of attributes and the message payload that the processor returns. The processor forwards the new message as output to the next processor in the flow. Processors available to Mule applications include: - Components from modules and connectors Examples include operations that read from and write to an external resource and that validate data in the Mule application. Some operations can make client requests to external resources and services (including external databases and systems, such as Salesforce, Workday, ServiceNow, and many others) and to other Mule applications. Others can run your custom code, support OAuth configurations, and manage communication through asynchronous queues, for example. Many other operations are available. - Core components Core components can route data, perform data transformations, handle errors that might occur when processing the event, and perform other tasks in a Mule application. Transformers (such as the Transform Message, Set Variable, and others) are key to exchanging data between nodes. Transformers enable Mule to convert message data in the Mule event to a format that another application or service can read. Mule also enables content enrichment of messages (through [Target Variables](https://docs.mulesoft.com/mule-runtime/4.11/target-variables)) so that you can retrieve additional data and attach it to the message. Note that you can also create your own event processors using the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## Security You can provide security to your Mule applications by encrypting properties, configuring secure communications over TLS, setting up authentication over OAuth 2.0, and providing cryptographic and other capabilities, such as FIPS compliance. - [Security](https://docs.mulesoft.com/mule-runtime/4.11/securing) ## Development Environments You can develop a Mule application using [Anypoint Studio](https://docs.mulesoft.com/studio/) (an Eclipse-based IDE), or, if you are an advanced developer, in your own IDE. For example, in Studio, you build and design a Mule application in a project that contains one or more XML-based files. A Mule project supports all the dependencies required for development. The [Package Explorer](https://docs.mulesoft.com/studio/#package-explorer) view in Studio provides access to the project folders and files that make up a Mule project. Studio provides a design-time environment in which you can also build, run, and test your Mule application. ## Mule Versioning The Mule version you use determines what your Mule application, domain, or policy can do and what features and products are compatible with Mule. For example, [Core components](https://docs.mulesoft.com/mule-runtime/4.11/about-components), which process the Mule event as it travels through flows in a Mule application, are part of a Core module that is bundled with and shares the same version as Mule. [Modules, connectors](https://docs.mulesoft.com/connectors/), the DataWeave language, and several MuleSoft products have their own versioning system but are compatible with specific versions of Mule. For example, DataWeave 2.0 and Studio 7.x are compatible with Mule 4.x runtime engines. Make sure the connector or module you use in a Mule application is compatible with your Mule version. ## See Also - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-message) - [Variables in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-variables) - [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-configuration) - [APIkit Overview](https://docs.mulesoft.com/apikit/latest/) --- product: Mule Runtime version: 4.12 --- # Developing Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Develop Mule applications to integrate systems, process data, and automate workflows. Mule applications read data from internal or external sources, transform it, and send the processed output to other systems. Mule applications run in Mule runtime engine (Mule). Requests to an application generate Mule events that move through flows for processing. Mule encodes the request and data in the event and passes them to single or multiple threads. ## Getting Started with Mule Application Development To get started with Mule application development, you can follow the steps in these tutorials: - [Create a "Hello World" Mule app](https://docs.mulesoft.com/mule-runtime/4.12/mule-app-dev-hellomule) Build a Mule application that interacts with a user in a simple HTTP request-response flow. - [Create a Mule app that uses the Database Connector and DataWeave](https://docs.mulesoft.com/mule-runtime/4.12/mule-app-tutorial) Build a Mule application that retrieves data from a database and transforms it to a new structure. ## Building Blocks of a Mule Application Mule applications use connectors, modules, and components to read, write, and process data. - [Connectors and Modules](https://docs.mulesoft.com/connectors/) Anypoint connectors provide components, such as listeners, that interact with external API endpoints and act on data in the Mule application. Modules, such as the Validation, Java, Spring, and OAuth, provide modules that act on data in a Mule application without providing a direct connection to an endpoint. - [Core Components](https://docs.mulesoft.com/mule-runtime/4.12/about-components) Core components support flow control, error handling, logging, batch, and other programmatic operations on data that flows through your application. ## DataWeave Language DataWeave is the primary language used for formulating expressions in Mule. Connectors, modules, and components support the use of DataWeave to access, manipulate, and transform data structures and output formats, and to extract data that is processed within the Mule application. At runtime, Mule evaluates DataWeave expressions while executing a flow to: - Extract data needed to process the current message - Set or manipulate a value in the message ## Mule Flows Understanding basic flow architecture is key to understanding a Mule application. Essentially, every Mule flow contains a series of Mule components that receive or process messages: ![A flow including an HTTP Listener, data transformation, database connection, and logging process](/mulesoft/current/en-us/mule-runtime/4.12/_images/flow-example.png) Figure 1. Simple Flow in Design Center At the simplest level, flows are sequences of processors. A message that enters a flow can pass through a variety of processors. In a typical flow, a Mule application receives a message through a source (such as an HTTP Listener component), transforms that message into a new format, and processes any business logic before writing the processed message to an external system in a format that the system can read. To separate processing into more manageable units, Mule applications often contain multiple, interrelated flows instead of just a single flow. One flow can call another flow as a direct reference. For more information about this topic, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.12/about-flows) and [Mule Components](https://docs.mulesoft.com/mule-runtime/4.12/mule-components). ### Sources A source component (or trigger) is the first component in a flow. It receives a triggering event, creates a corresponding Mule event, and forwards that event for processing by the next component in the flow. External clients can trigger processing in a Mule flow through several communication protocols and methods, such as JMS, HTTP, FTP, JDBC, or File. Mule translates these communication protocols and methods into a standard message format, which passes through the flow’s processors. Sources in Mule can connect to specific external sources, either through a standard protocol or a third-party API. It is also possible to set a Scheduler component. Some schedulers can poll for specific changes to external resources, such as new files or table rows in an external resource. Examples of listeners and connector operations that can trigger a flow include: - HTTP, JMS, and VM listeners in their associated connectors - On Table Row operation in the Database connector - On New or Updated File operation in the File and FTP connectors - Scheduler You can also create your own source using the [Mule SDK sources](https://docs.mulesoft.com/mule-sdk/latest/sources). Message sources don’t support expressions in configuration parameters that are evaluated before the flow executes because sources are initialized before the flow runs. The exception is [callback parameters](https://docs.mulesoft.com/mule-sdk/latest/sources-response#callback-parameters), which operate on the response generated by the flow and can use expressions. ### Processors After a flow is triggered through the source component, subsequent components process the data as it travels through the flow. By default, each processor that receives a Mule event returns a new Mule message, typically with a set of attributes and the message payload that the processor returns. The processor forwards the new message as output to the next processor in the flow. Processors available to Mule applications include: - Components from modules and connectors Examples include operations that read from and write to an external resource and that validate data in the Mule application. Some operations can make client requests to external resources and services (including external databases and systems, such as Salesforce, Workday, ServiceNow, and many others) and to other Mule applications. Others can run your custom code, support OAuth configurations, and manage communication through asynchronous queues, for example. Many other operations are available. - Core components Core components can route data, perform data transformations, handle errors that might occur when processing the event, and perform other tasks in a Mule application. Transformers (such as the Transform Message, Set Variable, and others) are key to exchanging data between nodes. Transformers enable Mule to convert message data in the Mule event to a format that another application or service can read. Mule also enables content enrichment of messages (through [Target Variables](https://docs.mulesoft.com/mule-runtime/4.12/target-variables)) so that you can retrieve additional data and attach it to the message. Note that you can also create your own event processors using the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## Security You can provide security to your Mule applications by encrypting properties, configuring secure communications over TLS, setting up authentication over OAuth 2.0, and providing cryptographic and other capabilities, such as FIPS compliance. - [Security](https://docs.mulesoft.com/mule-runtime/4.12/securing) ## Development Environments You can develop a Mule application using [Anypoint Studio](https://docs.mulesoft.com/studio/) (an Eclipse-based IDE), or, if you are an advanced developer, in your own IDE. For example, in Studio, you build and design a Mule application in a project that contains one or more XML-based files. A Mule project supports all the dependencies required for development. The [Package Explorer](https://docs.mulesoft.com/studio/#package-explorer) view in Studio provides access to the project folders and files that make up a Mule project. Studio provides a design-time environment in which you can also build, run, and test your Mule application. ## Mule Versioning The Mule version you use determines what your Mule application, domain, or policy can do and what features and products are compatible with Mule. For example, [Core components](https://docs.mulesoft.com/mule-runtime/4.12/about-components), which process the Mule event as it travels through flows in a Mule application, are part of a Core module that is bundled with and shares the same version as Mule. [Modules, connectors](https://docs.mulesoft.com/connectors/), the DataWeave language, and several MuleSoft products have their own versioning system but are compatible with specific versions of Mule. For example, DataWeave 2.0 and Studio 7.x are compatible with Mule 4.x runtime engines. Make sure the connector or module you use in a Mule application is compatible with your Mule version. ## See Also - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-message) - [Variables in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-variables) - [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-configuration) - [APIkit Overview](https://docs.mulesoft.com/apikit/latest/) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Developing Mule Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Develop Mule applications to integrate systems, process data, and automate workflows. Mule applications read data from internal or external sources, transform it, and send the processed output to other systems. Mule applications run in Mule runtime engine (Mule). Requests to an application generate Mule events that move through flows for processing. Mule encodes the request and data in the event and passes them to single or multiple threads. ## Getting Started with Mule Application Development To get started with Mule application development, you can follow the steps in these tutorials: - [Create a "Hello World" Mule app](https://docs.mulesoft.com/mule-runtime/latest/mule-app-dev-hellomule) Build a Mule application that interacts with a user in a simple HTTP request-response flow. - [Create a Mule app that uses the Database Connector and DataWeave](https://docs.mulesoft.com/mule-runtime/latest/mule-app-tutorial) Build a Mule application that retrieves data from a database and transforms it to a new structure. ## Building Blocks of a Mule Application Mule applications use connectors, modules, and components to read, write, and process data. - [Connectors and Modules](https://docs.mulesoft.com/connectors/) Anypoint connectors provide components, such as listeners, that interact with external API endpoints and act on data in the Mule application. Modules, such as the Validation, Java, Spring, and OAuth, provide modules that act on data in a Mule application without providing a direct connection to an endpoint. - [Core Components](https://docs.mulesoft.com/mule-runtime/latest/about-components) Core components support flow control, error handling, logging, batch, and other programmatic operations on data that flows through your application. ## DataWeave Language DataWeave is the primary language used for formulating expressions in Mule. Connectors, modules, and components support the use of DataWeave to access, manipulate, and transform data structures and output formats, and to extract data that is processed within the Mule application. At runtime, Mule evaluates DataWeave expressions while executing a flow to: - Extract data needed to process the current message - Set or manipulate a value in the message ## Mule Flows Understanding basic flow architecture is key to understanding a Mule application. Essentially, every Mule flow contains a series of Mule components that receive or process messages: ![A flow including an HTTP Listener, data transformation, database connection, and logging process](/mulesoft/current/en-us/mule-runtime/latest/_images/flow-example.png) Figure 1. Simple Flow in Design Center At the simplest level, flows are sequences of processors. A message that enters a flow can pass through a variety of processors. In a typical flow, a Mule application receives a message through a source (such as an HTTP Listener component), transforms that message into a new format, and processes any business logic before writing the processed message to an external system in a format that the system can read. To separate processing into more manageable units, Mule applications often contain multiple, interrelated flows instead of just a single flow. One flow can call another flow as a direct reference. For more information about this topic, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/latest/about-flows) and [Mule Components](https://docs.mulesoft.com/mule-runtime/latest/mule-components). ### Sources A source component (or trigger) is the first component in a flow. It receives a triggering event, creates a corresponding Mule event, and forwards that event for processing by the next component in the flow. External clients can trigger processing in a Mule flow through several communication protocols and methods, such as JMS, HTTP, FTP, JDBC, or File. Mule translates these communication protocols and methods into a standard message format, which passes through the flow’s processors. Sources in Mule can connect to specific external sources, either through a standard protocol or a third-party API. It is also possible to set a Scheduler component. Some schedulers can poll for specific changes to external resources, such as new files or table rows in an external resource. Examples of listeners and connector operations that can trigger a flow include: - HTTP, JMS, and VM listeners in their associated connectors - On Table Row operation in the Database connector - On New or Updated File operation in the File and FTP connectors - Scheduler You can also create your own source using the [Mule SDK sources](https://docs.mulesoft.com/mule-sdk/latest/sources). Message sources don’t support expressions in configuration parameters that are evaluated before the flow executes because sources are initialized before the flow runs. The exception is [callback parameters](https://docs.mulesoft.com/mule-sdk/latest/sources-response#callback-parameters), which operate on the response generated by the flow and can use expressions. ### Processors After a flow is triggered through the source component, subsequent components process the data as it travels through the flow. By default, each processor that receives a Mule event returns a new Mule message, typically with a set of attributes and the message payload that the processor returns. The processor forwards the new message as output to the next processor in the flow. Processors available to Mule applications include: - Components from modules and connectors Examples include operations that read from and write to an external resource and that validate data in the Mule application. Some operations can make client requests to external resources and services (including external databases and systems, such as Salesforce, Workday, ServiceNow, and many others) and to other Mule applications. Others can run your custom code, support OAuth configurations, and manage communication through asynchronous queues, for example. Many other operations are available. - Core components Core components can route data, perform data transformations, handle errors that might occur when processing the event, and perform other tasks in a Mule application. Transformers (such as the Transform Message, Set Variable, and others) are key to exchanging data between nodes. Transformers enable Mule to convert message data in the Mule event to a format that another application or service can read. Mule also enables content enrichment of messages (through [Target Variables](https://docs.mulesoft.com/mule-runtime/latest/target-variables)) so that you can retrieve additional data and attach it to the message. Note that you can also create your own event processors using the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## Security You can provide security to your Mule applications by encrypting properties, configuring secure communications over TLS, setting up authentication over OAuth 2.0, and providing cryptographic and other capabilities, such as FIPS compliance. - [Security](https://docs.mulesoft.com/mule-runtime/latest/securing) ## Development Environments You can develop a Mule application using [Anypoint Studio](https://docs.mulesoft.com/studio/) (an Eclipse-based IDE), or, if you are an advanced developer, in your own IDE. For example, in Studio, you build and design a Mule application in a project that contains one or more XML-based files. A Mule project supports all the dependencies required for development. The [Package Explorer](https://docs.mulesoft.com/studio/#package-explorer) view in Studio provides access to the project folders and files that make up a Mule project. Studio provides a design-time environment in which you can also build, run, and test your Mule application. ## Mule Versioning The Mule version you use determines what your Mule application, domain, or policy can do and what features and products are compatible with Mule. For example, [Core components](https://docs.mulesoft.com/mule-runtime/latest/about-components), which process the Mule event as it travels through flows in a Mule application, are part of a Core module that is bundled with and shares the same version as Mule. [Modules, connectors](https://docs.mulesoft.com/connectors/), the DataWeave language, and several MuleSoft products have their own versioning system but are compatible with specific versions of Mule. For example, DataWeave 2.0 and Studio 7.x are compatible with Mule 4.x runtime engines. Make sure the connector or module you use in a Mule application is compatible with your Mule version. ## See Also - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/latest/about-mule-message) - [Variables in Mule Apps](https://docs.mulesoft.com/mule-runtime/latest/about-mule-variables) - [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/latest/about-mule-configuration) - [APIkit Overview](https://docs.mulesoft.com/apikit/latest/) --- product: Mule Runtime version: 4.11 keywords: file polling, cluster --- # Distributed File Polling > For the full documentation index, see: https://docs.mulesoft.com/llms.txt **_Enterprise Edition_** Some connectors, such as the File connector or FTP connector, poll directories and read certain files as they are created in the directories polled. These files can reside on a remote file system, including file systems of nodes belonging to a Mule High Availability (HA) Cluster. In Mule 4, distributed file polling makes it possible to poll files in all cluster nodes. Enabled by default, this feature is used by the following connectors: - [File Connector](https://docs.mulesoft.com/file-connector/latest/) - [FTP Connector](https://docs.mulesoft.com/ftp-connector/latest/) - [SFTP Connector](https://docs.mulesoft.com/sftp-connector/latest/) You can configure connectors to only poll from the primary node, `@PrimaryNodeOnly`, which ignores the default setting set by the Mule runtime engine. This feature is only available in Mule 4.x ## See Also - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Mule High Availability (HA) Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.12 keywords: file polling, cluster --- # Distributed File Polling > For the full documentation index, see: https://docs.mulesoft.com/llms.txt **_Enterprise Edition_** Some connectors, such as the File connector or FTP connector, poll directories and read certain files as they are created in the directories polled. These files can reside on a remote file system, including file systems of nodes belonging to a Mule High Availability (HA) Cluster. In Mule 4, distributed file polling makes it possible to poll files in all cluster nodes. Enabled by default, this feature is used by the following connectors: - [File Connector](https://docs.mulesoft.com/file-connector/latest/) - [FTP Connector](https://docs.mulesoft.com/ftp-connector/latest/) - [SFTP Connector](https://docs.mulesoft.com/sftp-connector/latest/) You can configure connectors to only poll from the primary node, `@PrimaryNodeOnly`, which ignores the default setting set by the Mule runtime engine. This feature is only available in Mule 4.x ## See Also - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Mule High Availability (HA) Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.3 keywords: file polling, cluster --- # Distributed File Polling > For the full documentation index, see: https://docs.mulesoft.com/llms.txt **_Enterprise Edition_** Some connectors, such as the File connector or FTP connector, poll directories and read certain files as they are created in the directories polled. These files can reside on a remote file system, including file systems of nodes belonging to a Mule High Availability (HA) Cluster. In Mule 4, distributed file polling makes it possible to poll files in all cluster nodes. Enabled by default, this feature is used by the following connectors: - [File Connector](https://docs.mulesoft.com/file-connector/latest/) - [FTP Connector](https://docs.mulesoft.com/ftp-connector/latest/) - [SFTP Connector](https://docs.mulesoft.com/sftp-connector/latest/) You can configure connectors to only poll from the primary node, `@PrimaryNodeOnly`, which ignores the default setting set by the Mule runtime engine. This feature is only available in Mule 4.x ## See Also - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Mule High Availability (HA) Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) - [Migrating File Connector](https://docs.mulesoft.com/mule-runtime/4.3/migration-connectors-file) - [Migrating FTP and SFTP Connectors](https://docs.mulesoft.com/mule-runtime/4.3/migration-connectors-ftp-sftp) --- product: Mule Runtime version: 4.4 keywords: file polling, cluster --- # Distributed File Polling > For the full documentation index, see: https://docs.mulesoft.com/llms.txt **_Enterprise Edition_** Some connectors, such as the File connector or FTP connector, poll directories and read certain files as they are created in the directories polled. These files can reside on a remote file system, including file systems of nodes belonging to a Mule High Availability (HA) Cluster. In Mule 4, distributed file polling makes it possible to poll files in all cluster nodes. Enabled by default, this feature is used by the following connectors: - [File Connector](https://docs.mulesoft.com/file-connector/latest/) - [FTP Connector](https://docs.mulesoft.com/ftp-connector/latest/) - [SFTP Connector](https://docs.mulesoft.com/sftp-connector/latest/) You can configure connectors to only poll from the primary node, `@PrimaryNodeOnly`, which ignores the default setting set by the Mule runtime engine. This feature is only available in Mule 4.x ## See Also - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Mule High Availability (HA) Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) - [Migrating File Connector](https://docs.mulesoft.com/mule-runtime/4.4/migration-connectors-file) - [Migrating FTP and SFTP Connectors](https://docs.mulesoft.com/mule-runtime/4.4/migration-connectors-ftp-sftp) --- product: Mule Runtime version: 4.6 keywords: file polling, cluster --- # Distributed File Polling > For the full documentation index, see: https://docs.mulesoft.com/llms.txt **_Enterprise Edition_** Some connectors, such as the File connector or FTP connector, poll directories and read certain files as they are created in the directories polled. These files can reside on a remote file system, including file systems of nodes belonging to a Mule High Availability (HA) Cluster. In Mule 4, distributed file polling makes it possible to poll files in all cluster nodes. Enabled by default, this feature is used by the following connectors: - [File Connector](https://docs.mulesoft.com/file-connector/latest/) - [FTP Connector](https://docs.mulesoft.com/ftp-connector/latest/) - [SFTP Connector](https://docs.mulesoft.com/sftp-connector/latest/) You can configure connectors to only poll from the primary node, `@PrimaryNodeOnly`, which ignores the default setting set by the Mule runtime engine. This feature is only available in Mule 4.x ## See Also - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Mule High Availability (HA) Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.9 keywords: file polling, cluster --- # Distributed File Polling > For the full documentation index, see: https://docs.mulesoft.com/llms.txt **_Enterprise Edition_** Some connectors, such as the File connector or FTP connector, poll directories and read certain files as they are created in the directories polled. These files can reside on a remote file system, including file systems of nodes belonging to a Mule High Availability (HA) Cluster. In Mule 4, distributed file polling makes it possible to poll files in all cluster nodes. Enabled by default, this feature is used by the following connectors: - [File Connector](https://docs.mulesoft.com/file-connector/latest/) - [FTP Connector](https://docs.mulesoft.com/ftp-connector/latest/) - [SFTP Connector](https://docs.mulesoft.com/sftp-connector/latest/) You can configure connectors to only poll from the primary node, `@PrimaryNodeOnly`, which ignores the default setting set by the Mule runtime engine. This feature is only available in Mule 4.x ## See Also - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Mule High Availability (HA) Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: file polling, cluster --- # Distributed File Polling > For the full documentation index, see: https://docs.mulesoft.com/llms.txt **_Enterprise Edition_** Some connectors, such as the File connector or FTP connector, poll directories and read certain files as they are created in the directories polled. These files can reside on a remote file system, including file systems of nodes belonging to a Mule High Availability (HA) Cluster. In Mule 4, distributed file polling makes it possible to poll files in all cluster nodes. Enabled by default, this feature is used by the following connectors: - [File Connector](https://docs.mulesoft.com/file-connector/latest/) - [FTP Connector](https://docs.mulesoft.com/ftp-connector/latest/) - [SFTP Connector](https://docs.mulesoft.com/sftp-connector/latest/) You can configure connectors to only poll from the primary node, `@PrimaryNodeOnly`, which ignores the default setting set by the Mule runtime engine. This feature is only available in Mule 4.x ## See Also - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Mule High Availability (HA) Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.11 keywords: distributed locking, cluster --- # Distributed Locking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine provides the ability to create locks for synchronizing access to resources within Mule components. To manage concurrent access to resources, Mule provides a lock factory that you can access programmatically by scripts or in custom extensions built with the [Java SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started). Any locks you create with the Mule lock factory work seamlessly on deployment models that use either a single server or a cluster of servers. This means that if you have a server running the same flow in multiple threads, or a cluster environment running the same app, you can guarantee resource synchronization with Mule locks. Additionally, the Mule locking system offers a simple API to access shared locks. > [!WARNING] `LockFactory` creates a `Lock` that implements `java.util.concurrent.Lock` but does not > support the method `newCondition()`. Using `newCondition()` causes Mule to throw an > `UnsupportedOperationException`. Mule does support other methods of interfacing with a lock, such > as `lockInterruptibly()` and `tryLock()`. ## Create a Lock To create a lock, perform these steps: 1. Gain access to a `LockFactory` through injection. If you are building an extension with the Java SDK and need locking for one of your operations, you inject `LockFactory` into your class. 2. Use `LockFactory` to start creating locks. See the following sample code that declares an extension operation that manages code access through Mule locks and thus prevents synchronization issues when the operation is executing in parallel (like in a scatter gather scope or in different cluster nodes). 3. Use an identifier for the lock you create. An identifier allows you to access one lock from different threads without having to explicitly share the same lock instance between them. This lock implements the `java.util.concurrent.Lock` interface, so calling the method `lock()` makes the thread wait until it acquires the lock. After you create the lock, the critical code section can be executed and you must also create a lock release mechanism to prevent deadlocks on other threads waiting for this lock. You accomplish this by enclosing the `lock.unlock` call in a `finally` block: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperation() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## Create a Lock Using Scripting If you are using the scripting extension, you must first access the registry to obtain the `LockFactory` and then create locks through scripting code. The following example uses Groovy to achieve the same result as the previous example: obtain the `LockFactory` (this time through the `Registry`), create a new `Lock` for the given ID, wait until obtaining the lock to execute critical code and after that release the lock. ```groovy lockFactory = registry.lookupByName("_muleLockFactory").get() lock = lockFactory.createLock("sharedResourceId") lock.lock() try { // Lock acquired, execute critical code. } finally { lock.unlock() } ``` ## Share a Lock Between Operations Locking is useful not only to create locks for many threads running the same operation, but also can be used for different operations that may be running in parallel. Using the same lock ID to create a lock in different operations allows those operations to obtain access to the same lock. The following code sample illustrates two custom operations that create locks using the same lock ID: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperationA() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } public void sharedResourceOperationB() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## See Also - [Mule High Availability (HA) Clustering](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Distributed File Polling](https://docs.mulesoft.com/mule-runtime/4.11/distributed-file-polling) --- product: Mule Runtime version: 4.12 keywords: distributed locking, cluster --- # Distributed Locking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine provides the ability to create locks for synchronizing access to resources within Mule components. To manage concurrent access to resources, Mule provides a lock factory that you can access programmatically by scripts or in custom extensions built with the [Java SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started). Any locks you create with the Mule lock factory work seamlessly on deployment models that use either a single server or a cluster of servers. This means that if you have a server running the same flow in multiple threads, or a cluster environment running the same app, you can guarantee resource synchronization with Mule locks. Additionally, the Mule locking system offers a simple API to access shared locks. > [!WARNING] `LockFactory` creates a `Lock` that implements `java.util.concurrent.Lock` but does not > support the method `newCondition()`. Using `newCondition()` causes Mule to throw an > `UnsupportedOperationException`. Mule does support other methods of interfacing with a lock, such > as `lockInterruptibly()` and `tryLock()`. ## Create a Lock To create a lock, perform these steps: 1. Gain access to a `LockFactory` through injection. If you are building an extension with the Java SDK and need locking for one of your operations, you inject `LockFactory` into your class. 2. Use `LockFactory` to start creating locks. See the following sample code that declares an extension operation that manages code access through Mule locks and thus prevents synchronization issues when the operation is executing in parallel (like in a scatter gather scope or in different cluster nodes). 3. Use an identifier for the lock you create. An identifier allows you to access one lock from different threads without having to explicitly share the same lock instance between them. This lock implements the `java.util.concurrent.Lock` interface, so calling the method `lock()` makes the thread wait until it acquires the lock. After you create the lock, the critical code section can be executed and you must also create a lock release mechanism to prevent deadlocks on other threads waiting for this lock. You accomplish this by enclosing the `lock.unlock` call in a `finally` block: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperation() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## Create a Lock Using Scripting If you are using the scripting extension, you must first access the registry to obtain the `LockFactory` and then create locks through scripting code. The following example uses Groovy to achieve the same result as the previous example: obtain the `LockFactory` (this time through the `Registry`), create a new `Lock` for the given ID, wait until obtaining the lock to execute critical code and after that release the lock. ```groovy lockFactory = registry.lookupByName("_muleLockFactory").get() lock = lockFactory.createLock("sharedResourceId") lock.lock() try { // Lock acquired, execute critical code. } finally { lock.unlock() } ``` ## Share a Lock Between Operations Locking is useful not only to create locks for many threads running the same operation, but also can be used for different operations that may be running in parallel. Using the same lock ID to create a lock in different operations allows those operations to obtain access to the same lock. The following code sample illustrates two custom operations that create locks using the same lock ID: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperationA() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } public void sharedResourceOperationB() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## See Also - [Mule High Availability (HA) Clustering](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Distributed File Polling](https://docs.mulesoft.com/mule-runtime/4.12/distributed-file-polling) --- product: Mule Runtime version: 4.3 keywords: distributed locking, cluster --- # Distributed Locking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine provides the ability to create locks for synchronizing access to resources within Mule components. To manage concurrent access to resources, Mule provides a lock factory that you can access programmatically by scripts or in custom extensions built with the [Java SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started). Any locks you create with the Mule lock factory work seamlessly on deployment models that use either a single server or a cluster of servers. This means that if you have a server running the same flow in multiple threads, or a cluster environment running the same app, you can guarantee resource synchronization with Mule locks. Additionally, the Mule locking system offers a simple API to access shared locks. > [!WARNING] `LockFactory` creates a `Lock` that implements `java.util.concurrent.Lock` but does not > support the method `newCondition()`. Using `newCondition()` causes Mule to throw an > `UnsupportedOperationException`. Mule does support other methods of interfacing with a lock, such > as `lockInterruptibly()` and `tryLock()`. ## Create a Lock To create a lock, perform these steps: 1. Gain access to a `LockFactory` through injection. If you are building an extension with the Java SDK and need locking for one of your operations, you inject `LockFactory` into your class. 2. Use `LockFactory` to start creating locks. See the following sample code that declares an extension operation that manages code access through Mule locks and thus prevents synchronization issues when the operation is executing in parallel (like in a scatter gather scope or in different cluster nodes). 3. Use an identifier for the lock you create. An identifier allows you to access one lock from different threads without having to explicitly share the same lock instance between them. This lock implements the `java.util.concurrent.Lock` interface, so calling the method `lock()` makes the thread wait until it acquires the lock. After you create the lock, the critical code section can be executed and you must also create a lock release mechanism to prevent deadlocks on other threads waiting for this lock. You accomplish this by enclosing the `lock.unlock` call in a `finally` block: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperation() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## Create a Lock Using Scripting If you are using the scripting extension, you must first access the registry to obtain the `LockFactory` and then create locks through scripting code. The following example uses Groovy to achieve the same result as the previous example: obtain the `LockFactory` (this time through the `Registry`), create a new `Lock` for the given ID, wait until obtaining the lock to execute critical code and after that release the lock. ```groovy lockFactory = registry.lookupByName("_muleLockFactory").get() lock = lockFactory.createLock("sharedResourceId") lock.lock() try { // Lock acquired, execute critical code. } finally { lock.unlock() } ``` ## Share a Lock Between Operations Locking is useful not only to create locks for many threads running the same operation, but also can be used for different operations that may be running in parallel. Using the same lock ID to create a lock in different operations allows those operations to obtain access to the same lock. The following code sample illustrates two custom operations that create locks using the same lock ID: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperationA() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } public void sharedResourceOperationB() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## See Also - [Mule High Availability (HA) Clustering](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Distributed File Polling](https://docs.mulesoft.com/mule-runtime/4.3/distributed-file-polling) --- product: Mule Runtime version: 4.4 keywords: distributed locking, cluster --- # Distributed Locking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine provides the ability to create locks for synchronizing access to resources within Mule components. To manage concurrent access to resources, Mule provides a lock factory that you can access programmatically by scripts or in custom extensions built with the [Java SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started). Any locks you create with the Mule lock factory work seamlessly on deployment models that use either a single server or a cluster of servers. This means that if you have a server running the same flow in multiple threads, or a cluster environment running the same app, you can guarantee resource synchronization with Mule locks. Additionally, the Mule locking system offers a simple API to access shared locks. > [!WARNING] `LockFactory` creates a `Lock` that implements `java.util.concurrent.Lock` but does not > support the method `newCondition()`. Using `newCondition()` causes Mule to throw an > `UnsupportedOperationException`. Mule does support other methods of interfacing with a lock, such > as `lockInterruptibly()` and `tryLock()`. ## Create a Lock To create a lock, perform these steps: 1. Gain access to a `LockFactory` through injection. If you are building an extension with the Java SDK and need locking for one of your operations, you inject `LockFactory` into your class. 2. Use `LockFactory` to start creating locks. See the following sample code that declares an extension operation that manages code access through Mule locks and thus prevents synchronization issues when the operation is executing in parallel (like in a scatter gather scope or in different cluster nodes). 3. Use an identifier for the lock you create. An identifier allows you to access one lock from different threads without having to explicitly share the same lock instance between them. This lock implements the `java.util.concurrent.Lock` interface, so calling the method `lock()` makes the thread wait until it acquires the lock. After you create the lock, the critical code section can be executed and you must also create a lock release mechanism to prevent deadlocks on other threads waiting for this lock. You accomplish this by enclosing the `lock.unlock` call in a `finally` block: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperation() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## Create a Lock Using Scripting If you are using the scripting extension, you must first access the registry to obtain the `LockFactory` and then create locks through scripting code. The following example uses Groovy to achieve the same result as the previous example: obtain the `LockFactory` (this time through the `Registry`), create a new `Lock` for the given ID, wait until obtaining the lock to execute critical code and after that release the lock. ```groovy lockFactory = registry.lookupByName("_muleLockFactory").get() lock = lockFactory.createLock("sharedResourceId") lock.lock() try { // Lock acquired, execute critical code. } finally { lock.unlock() } ``` ## Share a Lock Between Operations Locking is useful not only to create locks for many threads running the same operation, but also can be used for different operations that may be running in parallel. Using the same lock ID to create a lock in different operations allows those operations to obtain access to the same lock. The following code sample illustrates two custom operations that create locks using the same lock ID: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperationA() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } public void sharedResourceOperationB() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## See Also - [Mule High Availability (HA) Clustering](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Distributed File Polling](https://docs.mulesoft.com/mule-runtime/4.4/distributed-file-polling) --- product: Mule Runtime version: 4.6 keywords: distributed locking, cluster --- # Distributed Locking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine provides the ability to create locks for synchronizing access to resources within Mule components. To manage concurrent access to resources, Mule provides a lock factory that you can access programmatically by scripts or in custom extensions built with the [Java SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started). Any locks you create with the Mule lock factory work seamlessly on deployment models that use either a single server or a cluster of servers. This means that if you have a server running the same flow in multiple threads, or a cluster environment running the same app, you can guarantee resource synchronization with Mule locks. Additionally, the Mule locking system offers a simple API to access shared locks. > [!WARNING] `LockFactory` creates a `Lock` that implements `java.util.concurrent.Lock` but does not > support the method `newCondition()`. Using `newCondition()` causes Mule to throw an > `UnsupportedOperationException`. Mule does support other methods of interfacing with a lock, such > as `lockInterruptibly()` and `tryLock()`. ## Create a Lock To create a lock, perform these steps: 1. Gain access to a `LockFactory` through injection. If you are building an extension with the Java SDK and need locking for one of your operations, you inject `LockFactory` into your class. 2. Use `LockFactory` to start creating locks. See the following sample code that declares an extension operation that manages code access through Mule locks and thus prevents synchronization issues when the operation is executing in parallel (like in a scatter gather scope or in different cluster nodes). 3. Use an identifier for the lock you create. An identifier allows you to access one lock from different threads without having to explicitly share the same lock instance between them. This lock implements the `java.util.concurrent.Lock` interface, so calling the method `lock()` makes the thread wait until it acquires the lock. After you create the lock, the critical code section can be executed and you must also create a lock release mechanism to prevent deadlocks on other threads waiting for this lock. You accomplish this by enclosing the `lock.unlock` call in a `finally` block: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperation() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## Create a Lock Using Scripting If you are using the scripting extension, you must first access the registry to obtain the `LockFactory` and then create locks through scripting code. The following example uses Groovy to achieve the same result as the previous example: obtain the `LockFactory` (this time through the `Registry`), create a new `Lock` for the given ID, wait until obtaining the lock to execute critical code and after that release the lock. ```groovy lockFactory = registry.lookupByName("_muleLockFactory").get() lock = lockFactory.createLock("sharedResourceId") lock.lock() try { // Lock acquired, execute critical code. } finally { lock.unlock() } ``` ## Share a Lock Between Operations Locking is useful not only to create locks for many threads running the same operation, but also can be used for different operations that may be running in parallel. Using the same lock ID to create a lock in different operations allows those operations to obtain access to the same lock. The following code sample illustrates two custom operations that create locks using the same lock ID: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperationA() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } public void sharedResourceOperationB() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## See Also - [Mule High Availability (HA) Clustering](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Distributed File Polling](https://docs.mulesoft.com/mule-runtime/4.6/distributed-file-polling) --- product: Mule Runtime version: 4.9 keywords: distributed locking, cluster --- # Distributed Locking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine provides the ability to create locks for synchronizing access to resources within Mule components. To manage concurrent access to resources, Mule provides a lock factory that you can access programmatically by scripts or in custom extensions built with the [Java SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started). Any locks you create with the Mule lock factory work seamlessly on deployment models that use either a single server or a cluster of servers. This means that if you have a server running the same flow in multiple threads, or a cluster environment running the same app, you can guarantee resource synchronization with Mule locks. Additionally, the Mule locking system offers a simple API to access shared locks. > [!WARNING] `LockFactory` creates a `Lock` that implements `java.util.concurrent.Lock` but does not > support the method `newCondition()`. Using `newCondition()` causes Mule to throw an > `UnsupportedOperationException`. Mule does support other methods of interfacing with a lock, such > as `lockInterruptibly()` and `tryLock()`. ## Create a Lock To create a lock, perform these steps: 1. Gain access to a `LockFactory` through injection. If you are building an extension with the Java SDK and need locking for one of your operations, you inject `LockFactory` into your class. 2. Use `LockFactory` to start creating locks. See the following sample code that declares an extension operation that manages code access through Mule locks and thus prevents synchronization issues when the operation is executing in parallel (like in a scatter gather scope or in different cluster nodes). 3. Use an identifier for the lock you create. An identifier allows you to access one lock from different threads without having to explicitly share the same lock instance between them. This lock implements the `java.util.concurrent.Lock` interface, so calling the method `lock()` makes the thread wait until it acquires the lock. After you create the lock, the critical code section can be executed and you must also create a lock release mechanism to prevent deadlocks on other threads waiting for this lock. You accomplish this by enclosing the `lock.unlock` call in a `finally` block: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperation() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## Create a Lock Using Scripting If you are using the scripting extension, you must first access the registry to obtain the `LockFactory` and then create locks through scripting code. The following example uses Groovy to achieve the same result as the previous example: obtain the `LockFactory` (this time through the `Registry`), create a new `Lock` for the given ID, wait until obtaining the lock to execute critical code and after that release the lock. ```groovy lockFactory = registry.lookupByName("_muleLockFactory").get() lock = lockFactory.createLock("sharedResourceId") lock.lock() try { // Lock acquired, execute critical code. } finally { lock.unlock() } ``` ## Share a Lock Between Operations Locking is useful not only to create locks for many threads running the same operation, but also can be used for different operations that may be running in parallel. Using the same lock ID to create a lock in different operations allows those operations to obtain access to the same lock. The following code sample illustrates two custom operations that create locks using the same lock ID: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperationA() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } public void sharedResourceOperationB() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## See Also - [Mule High Availability (HA) Clustering](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Distributed File Polling](https://docs.mulesoft.com/mule-runtime/4.9/distributed-file-polling) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: distributed locking, cluster --- # Distributed Locking > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine provides the ability to create locks for synchronizing access to resources within Mule components. To manage concurrent access to resources, Mule provides a lock factory that you can access programmatically by scripts or in custom extensions built with the [Java SDK](https://docs.mulesoft.com/mule-sdk/latest/getting-started). Any locks you create with the Mule lock factory work seamlessly on deployment models that use either a single server or a cluster of servers. This means that if you have a server running the same flow in multiple threads, or a cluster environment running the same app, you can guarantee resource synchronization with Mule locks. Additionally, the Mule locking system offers a simple API to access shared locks. > [!WARNING] `LockFactory` creates a `Lock` that implements `java.util.concurrent.Lock` but does not > support the method `newCondition()`. Using `newCondition()` causes Mule to throw an > `UnsupportedOperationException`. Mule does support other methods of interfacing with a lock, such > as `lockInterruptibly()` and `tryLock()`. ## Create a Lock To create a lock, perform these steps: 1. Gain access to a `LockFactory` through injection. If you are building an extension with the Java SDK and need locking for one of your operations, you inject `LockFactory` into your class. 2. Use `LockFactory` to start creating locks. See the following sample code that declares an extension operation that manages code access through Mule locks and thus prevents synchronization issues when the operation is executing in parallel (like in a scatter gather scope or in different cluster nodes). 3. Use an identifier for the lock you create. An identifier allows you to access one lock from different threads without having to explicitly share the same lock instance between them. This lock implements the `java.util.concurrent.Lock` interface, so calling the method `lock()` makes the thread wait until it acquires the lock. After you create the lock, the critical code section can be executed and you must also create a lock release mechanism to prevent deadlocks on other threads waiting for this lock. You accomplish this by enclosing the `lock.unlock` call in a `finally` block: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperation() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## Create a Lock Using Scripting If you are using the scripting extension, you must first access the registry to obtain the `LockFactory` and then create locks through scripting code. The following example uses Groovy to achieve the same result as the previous example: obtain the `LockFactory` (this time through the `Registry`), create a new `Lock` for the given ID, wait until obtaining the lock to execute critical code and after that release the lock. ```groovy lockFactory = registry.lookupByName("_muleLockFactory").get() lock = lockFactory.createLock("sharedResourceId") lock.lock() try { // Lock acquired, execute critical code. } finally { lock.unlock() } ``` ## Share a Lock Between Operations Locking is useful not only to create locks for many threads running the same operation, but also can be used for different operations that may be running in parallel. Using the same lock ID to create a lock in different operations allows those operations to obtain access to the same lock. The following code sample illustrates two custom operations that create locks using the same lock ID: ```java public class ClusterOperations { @Inject private LockFactory lockFactory; public void sharedResourceOperationA() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } public void sharedResourceOperationB() { Lock lock = lockFactory.createLock("sharedResourceId"); lock.lock(); try { // Lock acquired, execute critical code. } finally { lock.unlock(); } } } ``` ## See Also - [Mule High Availability (HA) Clustering](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) - [Creating and Managing a Cluster Manually](https://docs.mulesoft.com/on-premises/latest/creating-and-managing-a-cluster-manually) - [Distributed File Polling](https://docs.mulesoft.com/mule-runtime/latest/distributed-file-polling) --- product: Mule Runtime version: 4.3 --- # Domains > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Using domains greatly enhance performance when you deploy multiple services on the same on-premises Mule runtime engine (Mule). By providing a centralized point for all the shared resources, domains make the class-loading process (and, therefore, metaspace memory usage) more efficient, especially because domain dependencies declared in the `pom.xml` file are also shared in the domain apps. ## Example of Increased Performance Using Domains Imagine that you have a set of HTTP Proxy applications that also apply one API Gateway policy, such as an IP whitelist. Each application interacts with the same backend. In a Mule instance configured to have 2 GB of heap memory and 256 MB of metaspace, deploying those applications independently without using a proper domain, results in a noticeable reduction in TPS (transactions per second) when deploying 60 or more applications due to saturated resources. At 80 applications, you see deployment issues due to out-of-memory exceptions. You can greatly improve this outcome by using a domain that shares the backend server configuration, increasing the number of applications to beyond 100 while also experiencing a balanced use of machine resources and consistent good performance. Note that despite the clear performance advantage in using domains, each deployed application adds its own unique complexity to the shared infrastructure resources. To avoid performance impact, before adding an application, identify the overhead by testing each application individually and then test it coexisting with other applications. ## See Also - [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.3/shared-resources) --- product: Mule Runtime version: 4.11 keywords: mule, ee, esb, studio, dynamic, evaluate, expression --- # Dynamic Evaluate Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Dynamic Evaluate component evaluates an expression to select a DataWeave script, and then executes the new script to generate a result. This behavior enables you to dynamically select the script, instead of hardcoding it into the [Transform Message component](https://docs.mulesoft.com/mule-runtime/4.11/transform-component-about). The script can use any of the usual [context variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), such as `message`, `payload`,`vars`, or `attributes`, but you can also add custom ones by providing a set of key-value pairs. ## Dynamic Evaluate Configuration
FieldValueDescriptionExample

Expression

DataWeave expression

Specifies an expression that selects a DataWeave script that Mule then executes.

expression="#[vars.generateOrderScript]"

Parameters

DataWeave expression

Specifies key-value pairs to set as parameters that the DataWeave script can evaluate.

#[{joiner: ' and ', id: payload.user.id}]

## Evaluate DataWeave Script from the File System Example The following example shows how the Dynamic Evaluate component selects and executes a DataWeave script stored locally in the file system. The application’s flow behavior is as follows: 1. An HTTP Listener source listens to a POST URL request that contains a `locale` query parameter and a payload. 2. A File Read operation uses the `locale` query parameter received in the HTTP request to search locally the DataWeave script that matches the parameter name. 3. The File Read operation stores the content of the script into a new variable. 4. A Dynamic Evaluate component executes the DataWeave expression stored in the variable. 5. A Logger component logs the payload result of the transformation. The locally stored DataWeave scripts can be stored in a database instead of locally, and the app can be modified to pick the files from the database instead of the file system. This enables you to replace any of the `.dwl` files while the app is deployed and running, changing the DataWeave script to execute without having to modify or redeploy the application. In this example, you create two DataWeave scripts and store them locally, create the Mule application, and run and test the application: ![A flow showing a dynamic evaluation component in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/dynamic-evaluate-flow-1.png) Figure 1. Dynamic Evaluate Flow example in Anypoint Studio ### Create and Store the DataWeave Scripts The first step in evaluating DataWeave scripts from the file system is to create and locally store the scripts: 1. Create a new Mule project in Studio. 2. In the **Package Explorer** window, under the name of your Mule project, right-click the **src/main/resources** folder and select **New > File**. 3. In the **File name** field, add the name `dw_en-US.dwl` to create the new DataWeave script file. 4. Click **Finish**. 5. In the **dw\_en-US.dwl** window, paste the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "First Name": payload.name, "Last Name": payload.last, "Country": payload.loc } ``` 6. Repeat the previous steps and create a new file named `dw_es-AR.dwl` that contains the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "Nombre": payload.name, "Apellido": payload.last, "País": payload.loc } ``` 7. Save your changes. ### Create the Mule Application After creating and locally saving your example scripts, create the Mule application in Studio: 1. In the **Package Explorer** window **src/main/mule (Flows)** folder, navigate to your flow’s `.xml` file. 2. In the **Mule Palette** view, select the **HTTP Listener** source and drag it onto the canvas. The source initiates the flow by listening for incoming HTTP requests. 3. Set the **Path** field to `/test`. 4. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the HTTP Listener in the app. 5. On the **General** tab, configure the following fields: - **Host**: `All Interfaces [0.0.0.0] (default)` - **Port**: `8081` 6. Click **OK**. 7. Drag the **File Read** operation to the right of **HTTP Listener**. 8. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the File Read operation in the app. 9. On the **General** tab, set the **Working Directory** field to the main resources folder that contains your Studio project and previous DataWeave scripts: `/Users/username/AnypointStudio/studio-workspace/dynamicevaluate/src/main/resources` 10. Click **OK**. 11. In the **File path** field, set the path `#["dw_" ++ attributes.queryParams.locale ++ ".dwl"]`. The connector reads the locally stored DataWeave script file names that start with `dw_` and contains the `locale` query parameter (`attributes.queryParams.locale`) received in the HTTP request. 12. In the **Advanced** tab, set the **Target Variable** field to `dwScript`. This variable stores the DataWeave script that matched the file search. 13. Drag the **Dynamic Evaluate** component to the right of **File Read**. 14. Set the **Expression** field to `#[vars."dwScript"]` to execute the matched DataWeave script saved in the variable `dwScript`. 15. Set the **Target value** field to `payload`. 16. Drag a **Logger** component to the right of **Dynamic Evaluate**. 17. Set the **Message** field to `#[payload]`. 18. Save your Mule application. ### Run and Test the Mule Application After you create your Mule application, run and test it: 1. Click the project name in **Package Explorer** and then click **Run > Run As > Mule Application**. 2. Send a POST request to `http://localhost:8081/test`, appending to the URL any of the following query parameters `locale=en-US` or `locale=es-AR`, for example: `http://localhost:8081/test?locale=en-US` Additionally in the POST request, send the following payload: ```JSON { "name": "Max", "last": "The Mule", "loc": "Argentina" } ``` 3. In the Studio Console, scroll through the logs to see the result message: ```console INFO 2021-01-19 11:18:25,559 [[MuleRuntime].uber.12: [dynamicevaluate].dynamicevaluateFlow.CPU_INTENSIVE @2588f400] [processor: dynamicevaluateFlow/processors/2; event: 319aacc0-5a61-11eb-bbb8-f01898ad2638] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "First Name": "Max", "Last Name": "The Mule", "Country": "Argentina" } ``` ### XML for Evaluating DataWeave Script from a File System Paste this code into your Studio XML editor to quickly load the flow for this example into your Mule app: ```xml ``` ## Evaluate DataWeave Script from a Database Example The following example selects a script from a database through a `userId` query parameter and stores that script in a `userScript` variable. The `dynamic-evaluate` component accesses the `userScript` variable to invoke the script using the provided parameter `name`, which contains the value of `attributes.queryParams.userName`. ```xml #["SELECT script FROM SCRIPTS WHERE ID = $(attributes.queryParams.userId)"] #[{name: attributes.queryParams.userName}] ``` Consider the following scripts stored in this example’s database for entries `lsalander` and `mblomkvist`, respectively: Example: lsalander script output application/json --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } Example: mblomkvist script output application/x-www-form-urlencoded --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } ### Example Application Behavior When this example Mule application receives `lsalander` as the `queryParams.userId` in the request, Mule executes the corresponding script, which results in a JSON response. If the application receives `mblomkvist` as the `queryParams.userId` value, Mule executes a different script that generates a `x-www-form-urlencoded` response. This example demonstrates how the response type can be parameterized based on the user, but the entire response can be parameterized to suit each users needs. --- product: Mule Runtime version: 4.12 keywords: mule, ee, esb, studio, dynamic, evaluate, expression --- # Dynamic Evaluate Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Dynamic Evaluate component evaluates an expression to select a DataWeave script, and then executes the new script to generate a result. This behavior enables you to dynamically select the script, instead of hardcoding it into the [Transform Message component](https://docs.mulesoft.com/mule-runtime/4.12/transform-component-about). The script can use any of the usual [context variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), such as `message`, `payload`,`vars`, or `attributes`, but you can also add custom ones by providing a set of key-value pairs. ## Dynamic Evaluate Configuration
FieldValueDescriptionExample

Expression

DataWeave expression

Specifies an expression that selects a DataWeave script that Mule then executes.

expression="#[vars.generateOrderScript]"

Parameters

DataWeave expression

Specifies key-value pairs to set as parameters that the DataWeave script can evaluate.

#[{joiner: ' and ', id: payload.user.id}]

## Evaluate DataWeave Script from the File System Example The following example shows how the Dynamic Evaluate component selects and executes a DataWeave script stored locally in the file system. The application’s flow behavior is as follows: 1. An HTTP Listener source listens to a POST URL request that contains a `locale` query parameter and a payload. 2. A File Read operation uses the `locale` query parameter received in the HTTP request to search locally the DataWeave script that matches the parameter name. 3. The File Read operation stores the content of the script into a new variable. 4. A Dynamic Evaluate component executes the DataWeave expression stored in the variable. 5. A Logger component logs the payload result of the transformation. The locally stored DataWeave scripts can be stored in a database instead of locally, and the app can be modified to pick the files from the database instead of the file system. This enables you to replace any of the `.dwl` files while the app is deployed and running, changing the DataWeave script to execute without having to modify or redeploy the application. In this example, you create two DataWeave scripts and store them locally, create the Mule application, and run and test the application: ![A flow showing a dynamic evaluation component in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/dynamic-evaluate-flow-1.png) Figure 1. Dynamic Evaluate Flow example in Anypoint Studio ### Create and Store the DataWeave Scripts The first step in evaluating DataWeave scripts from the file system is to create and locally store the scripts: 1. Create a new Mule project in Studio. 2. In the **Package Explorer** window, under the name of your Mule project, right-click the **src/main/resources** folder and select **New > File**. 3. In the **File name** field, add the name `dw_en-US.dwl` to create the new DataWeave script file. 4. Click **Finish**. 5. In the **dw\_en-US.dwl** window, paste the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "First Name": payload.name, "Last Name": payload.last, "Country": payload.loc } ``` 6. Repeat the previous steps and create a new file named `dw_es-AR.dwl` that contains the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "Nombre": payload.name, "Apellido": payload.last, "País": payload.loc } ``` 7. Save your changes. ### Create the Mule Application After creating and locally saving your example scripts, create the Mule application in Studio: 1. In the **Package Explorer** window **src/main/mule (Flows)** folder, navigate to your flow’s `.xml` file. 2. In the **Mule Palette** view, select the **HTTP Listener** source and drag it onto the canvas. The source initiates the flow by listening for incoming HTTP requests. 3. Set the **Path** field to `/test`. 4. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the HTTP Listener in the app. 5. On the **General** tab, configure the following fields: - **Host**: `All Interfaces [0.0.0.0] (default)` - **Port**: `8081` 6. Click **OK**. 7. Drag the **File Read** operation to the right of **HTTP Listener**. 8. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the File Read operation in the app. 9. On the **General** tab, set the **Working Directory** field to the main resources folder that contains your Studio project and previous DataWeave scripts: `/Users/username/AnypointStudio/studio-workspace/dynamicevaluate/src/main/resources` 10. Click **OK**. 11. In the **File path** field, set the path `#["dw_" ++ attributes.queryParams.locale ++ ".dwl"]`. The connector reads the locally stored DataWeave script file names that start with `dw_` and contains the `locale` query parameter (`attributes.queryParams.locale`) received in the HTTP request. 12. In the **Advanced** tab, set the **Target Variable** field to `dwScript`. This variable stores the DataWeave script that matched the file search. 13. Drag the **Dynamic Evaluate** component to the right of **File Read**. 14. Set the **Expression** field to `#[vars."dwScript"]` to execute the matched DataWeave script saved in the variable `dwScript`. 15. Set the **Target value** field to `payload`. 16. Drag a **Logger** component to the right of **Dynamic Evaluate**. 17. Set the **Message** field to `#[payload]`. 18. Save your Mule application. ### Run and Test the Mule Application After you create your Mule application, run and test it: 1. Click the project name in **Package Explorer** and then click **Run > Run As > Mule Application**. 2. Send a POST request to `http://localhost:8081/test`, appending to the URL any of the following query parameters `locale=en-US` or `locale=es-AR`, for example: `http://localhost:8081/test?locale=en-US` Additionally in the POST request, send the following payload: ```JSON { "name": "Max", "last": "The Mule", "loc": "Argentina" } ``` 3. In the Studio Console, scroll through the logs to see the result message: ```console INFO 2021-01-19 11:18:25,559 [[MuleRuntime].uber.12: [dynamicevaluate].dynamicevaluateFlow.CPU_INTENSIVE @2588f400] [processor: dynamicevaluateFlow/processors/2; event: 319aacc0-5a61-11eb-bbb8-f01898ad2638] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "First Name": "Max", "Last Name": "The Mule", "Country": "Argentina" } ``` ### XML for Evaluating DataWeave Script from a File System Paste this code into your Studio XML editor to quickly load the flow for this example into your Mule app: ```xml ``` ## Evaluate DataWeave Script from a Database Example The following example selects a script from a database through a `userId` query parameter and stores that script in a `userScript` variable. The `dynamic-evaluate` component accesses the `userScript` variable to invoke the script using the provided parameter `name`, which contains the value of `attributes.queryParams.userName`. ```xml #["SELECT script FROM SCRIPTS WHERE ID = $(attributes.queryParams.userId)"] #[{name: attributes.queryParams.userName}] ``` Consider the following scripts stored in this example’s database for entries `lsalander` and `mblomkvist`, respectively: Example: lsalander script output application/json --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } Example: mblomkvist script output application/x-www-form-urlencoded --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } ### Example Application Behavior When this example Mule application receives `lsalander` as the `queryParams.userId` in the request, Mule executes the corresponding script, which results in a JSON response. If the application receives `mblomkvist` as the `queryParams.userId` value, Mule executes a different script that generates a `x-www-form-urlencoded` response. This example demonstrates how the response type can be parameterized based on the user, but the entire response can be parameterized to suit each users needs. --- product: Mule Runtime version: 4.3 keywords: mule, ee, esb, studio, dynamic, evaluate, expression --- # Dynamic Evaluate Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Dynamic Evaluate component evaluates an expression to select a DataWeave script, and then executes the new script to generate a result. This behavior enables you to dynamically select the script, instead of hardcoding it into the [Transform Message component](https://docs.mulesoft.com/mule-runtime/4.3/transform-component-about). The script can use any of the usual [context variables](https://docs.mulesoft.com/dataweave/2.3/dataweave-variables-context), such as `message`, `payload`,`vars`, or `attributes`, but you can also add custom ones by providing a set of key-value pairs. ## Dynamic Evaluate Configuration
FieldValueDescriptionExample

Expression

DataWeave expression

Specifies an expression that selects a DataWeave script that Mule then executes.

expression="#[vars.generateOrderScript]"

Parameters

DataWeave expression

Specifies key-value pairs to set as parameters that the DataWeave script can evaluate.

#[{joiner: ' and ', id: payload.user.id}]

## Evaluate DataWeave Script from the File System Example The following example shows how the Dynamic Evaluate component selects and executes a DataWeave script stored locally in the file system. The application’s flow behavior is as follows: 1. An HTTP Listener source listens to a POST URL request that contains a `locale` query parameter and a payload. 2. A File Read operation uses the `locale` query parameter received in the HTTP request to search locally the DataWeave script that matches the parameter name. 3. The File Read operation stores the content of the script into a new variable. 4. A Dynamic Evaluate component executes the DataWeave expression stored in the variable. 5. A Logger component logs the payload result of the transformation. The locally stored DataWeave scripts can be stored in a database instead of locally, and the app can be modified to pick the files from the database instead of the file system. This enables you to replace any of the `.dwl` files while the app is deployed and running, changing the DataWeave script to execute without having to modify or redeploy the application. In this example, you create two DataWeave scripts and store them locally, create the Mule application, and run and test the application: ![Dynamic Evaluate Flow example in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.3/_images/dynamic-evaluate-flow-1.png) Figure 1. Dynamic Evaluate Flow example in Anypoint Studio ### Create and Store the DataWeave Scripts The first step in evaluating DataWeave scripts from the file system is to create and locally store the scripts: 1. Create a new Mule project in Studio. 2. In the **Package Explorer** window, under the name of your Mule project, right-click the **src/main/resources** folder and select **New > File**. 3. In the **File name** field, add the name `dw_en-US.dwl` to create the new DataWeave script file. 4. Click **Finish**. 5. In the **dw\_en-US.dwl** window, paste the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "First Name": payload.name, "Last Name": payload.last, "Country": payload.loc } ``` 6. Repeat the previous steps and create a new file named `dw_es-AR.dwl` that contains the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "Nombre": payload.name, "Apellido": payload.last, "País": payload.loc } ``` 7. Save your changes. ### Create the Mule Application After creating and locally saving your example scripts, create the Mule application in Studio: 1. In the **Package Explorer** window **src/main/mule (Flows)** folder, navigate to your flow’s `.xml` file. 2. In the **Mule Palette** view, select the **HTTP Listener** source and drag it onto the canvas. The source initiates the flow by listening for incoming HTTP requests. 3. Set the **Path** field to `/test`. 4. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the HTTP Listener in the app. 5. On the **General** tab, configure the following fields: - **Host**: `All Interfaces [0.0.0.0] (default)` - **Port**: `8081` 6. Click **OK**. 7. Drag the **File Read** operation to the right of **HTTP Listener**. 8. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the File Read operation in the app. 9. On the **General** tab, set the **Working Directory** field to the main resources folder that contains your Studio project and previous DataWeave scripts: `/Users/username/AnypointStudio/studio-workspace/dynamicevaluate/src/main/resources` 10. Click **OK**. 11. In the **File path** field, set the path `#["dw_" ++ attributes.queryParams.locale ++ ".dwl"]`. The connector reads the locally stored DataWeave script file names that start with `dw_` and contains the `locale` query parameter (`attributes.queryParams.locale`) received in the HTTP request. 12. In the **Advanced** tab, set the **Target Variable** field to `dwScript`. This variable stores the DataWeave script that matched the file search. 13. Drag the **Dynamic Evaluate** component to the right of **File Read**. 14. Set the **Expression** field to `#[vars."dwScript"]` to execute the matched DataWeave script saved in the variable `dwScript`. 15. Set the **Target value** field to `payload`. 16. Drag a **Logger** component to the right of **Dynamic Evaluate**. 17. Set the **Message** field to `#[payload]`. 18. Save your Mule application. ### Run and Test the Mule Application After you create your Mule application, run and test it: 1. Click the project name in **Package Explorer** and then click **Run > Run As > Mule Application**. 2. Send a POST request to `http://localhost:8081/test`, appending to the URL any of the following query parameters `locale=en-US` or `locale=es-AR`, for example: `http://localhost:8081/test?locale=en-US` Additionally in the POST request, send the following payload: ```JSON { "name": "Max", "last": "The Mule", "loc": "Argentina" } ``` 3. In the Studio Console, scroll through the logs to see the result message: ```console INFO 2021-01-19 11:18:25,559 [[MuleRuntime].uber.12: [dynamicevaluate].dynamicevaluateFlow.CPU_INTENSIVE @2588f400] [processor: dynamicevaluateFlow/processors/2; event: 319aacc0-5a61-11eb-bbb8-f01898ad2638] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "First Name": "Max", "Last Name": "The Mule", "Country": "Argentina" } ``` ### XML for Evaluating DataWeave Script from a File System Paste this code into your Studio XML editor to quickly load the flow for this example into your Mule app: ```xml ``` ## Evaluate DataWeave Script from a Database Example The following example selects a script from a database through a `userId` query parameter and stores that script in a `userScript` variable. The `dynamic-evaluate` component accesses the `userScript` variable to invoke the script using the provided parameter `name`, which contains the value of `attributes.queryParams.userName`. ```xml #["SELECT script FROM SCRIPTS WHERE ID = $(attributes.queryParams.userId)"] #[{name: attributes.queryParams.userName}] ``` Consider the following scripts stored in this example’s database for entries `lsalander` and `mblomkvist`, respectively: Example: lsalander script output application/json --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } Example: mblomkvist script output application/x-www-form-urlencoded --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } ### Example Application Behavior When this example Mule application receives `lsalander` as the `queryParams.userId` in the request, Mule executes the corresponding script, which results in a JSON response. If the application receives `mblomkvist` as the `queryParams.userId` value, Mule executes a different script that generates a `x-www-form-urlencoded` response. This example demonstrates how the response type can be parameterized based on the user, but the entire response can be parameterized to suit each users needs. --- product: Mule Runtime version: 4.4 keywords: mule, ee, esb, studio, dynamic, evaluate, expression --- # Dynamic Evaluate Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Dynamic Evaluate component evaluates an expression to select a DataWeave script, and then executes the new script to generate a result. This behavior enables you to dynamically select the script, instead of hardcoding it into the [Transform Message component](https://docs.mulesoft.com/mule-runtime/4.4/transform-component-about). The script can use any of the usual [context variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), such as `message`, `payload`,`vars`, or `attributes`, but you can also add custom ones by providing a set of key-value pairs. ## Dynamic Evaluate Configuration
FieldValueDescriptionExample

Expression

DataWeave expression

Specifies an expression that selects a DataWeave script that Mule then executes.

expression="#[vars.generateOrderScript]"

Parameters

DataWeave expression

Specifies key-value pairs to set as parameters that the DataWeave script can evaluate.

#[{joiner: ' and ', id: payload.user.id}]

## Evaluate DataWeave Script from the File System Example The following example shows how the Dynamic Evaluate component selects and executes a DataWeave script stored locally in the file system. The application’s flow behavior is as follows: 1. An HTTP Listener source listens to a POST URL request that contains a `locale` query parameter and a payload. 2. A File Read operation uses the `locale` query parameter received in the HTTP request to search locally the DataWeave script that matches the parameter name. 3. The File Read operation stores the content of the script into a new variable. 4. A Dynamic Evaluate component executes the DataWeave expression stored in the variable. 5. A Logger component logs the payload result of the transformation. The locally stored DataWeave scripts can be stored in a database instead of locally, and the app can be modified to pick the files from the database instead of the file system. This enables you to replace any of the `.dwl` files while the app is deployed and running, changing the DataWeave script to execute without having to modify or redeploy the application. In this example, you create two DataWeave scripts and store them locally, create the Mule application, and run and test the application: ![Dynamic Evaluate Flow example in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.4/_images/dynamic-evaluate-flow-1.png) Figure 1. Dynamic Evaluate Flow example in Anypoint Studio ### Create and Store the DataWeave Scripts The first step in evaluating DataWeave scripts from the file system is to create and locally store the scripts: 1. Create a new Mule project in Studio. 2. In the **Package Explorer** window, under the name of your Mule project, right-click the **src/main/resources** folder and select **New > File**. 3. In the **File name** field, add the name `dw_en-US.dwl` to create the new DataWeave script file. 4. Click **Finish**. 5. In the **dw\_en-US.dwl** window, paste the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "First Name": payload.name, "Last Name": payload.last, "Country": payload.loc } ``` 6. Repeat the previous steps and create a new file named `dw_es-AR.dwl` that contains the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "Nombre": payload.name, "Apellido": payload.last, "País": payload.loc } ``` 7. Save your changes. ### Create the Mule Application After creating and locally saving your example scripts, create the Mule application in Studio: 1. In the **Package Explorer** window **src/main/mule (Flows)** folder, navigate to your flow’s `.xml` file. 2. In the **Mule Palette** view, select the **HTTP Listener** source and drag it onto the canvas. The source initiates the flow by listening for incoming HTTP requests. 3. Set the **Path** field to `/test`. 4. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the HTTP Listener in the app. 5. On the **General** tab, configure the following fields: - **Host**: `All Interfaces [0.0.0.0] (default)` - **Port**: `8081` 6. Click **OK**. 7. Drag the **File Read** operation to the right of **HTTP Listener**. 8. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the File Read operation in the app. 9. On the **General** tab, set the **Working Directory** field to the main resources folder that contains your Studio project and previous DataWeave scripts: `/Users/username/AnypointStudio/studio-workspace/dynamicevaluate/src/main/resources` 10. Click **OK**. 11. In the **File path** field, set the path `#["dw_" ++ attributes.queryParams.locale ++ ".dwl"]`. The connector reads the locally stored DataWeave script file names that start with `dw_` and contains the `locale` query parameter (`attributes.queryParams.locale`) received in the HTTP request. 12. In the **Advanced** tab, set the **Target Variable** field to `dwScript`. This variable stores the DataWeave script that matched the file search. 13. Drag the **Dynamic Evaluate** component to the right of **File Read**. 14. Set the **Expression** field to `#[vars."dwScript"]` to execute the matched DataWeave script saved in the variable `dwScript`. 15. Set the **Target value** field to `payload`. 16. Drag a **Logger** component to the right of **Dynamic Evaluate**. 17. Set the **Message** field to `#[payload]`. 18. Save your Mule application. ### Run and Test the Mule Application After you create your Mule application, run and test it: 1. Click the project name in **Package Explorer** and then click **Run > Run As > Mule Application**. 2. Send a POST request to `http://localhost:8081/test`, appending to the URL any of the following query parameters `locale=en-US` or `locale=es-AR`, for example: `http://localhost:8081/test?locale=en-US` Additionally in the POST request, send the following payload: ```JSON { "name": "Max", "last": "The Mule", "loc": "Argentina" } ``` 3. In the Studio Console, scroll through the logs to see the result message: ```console INFO 2021-01-19 11:18:25,559 [[MuleRuntime].uber.12: [dynamicevaluate].dynamicevaluateFlow.CPU_INTENSIVE @2588f400] [processor: dynamicevaluateFlow/processors/2; event: 319aacc0-5a61-11eb-bbb8-f01898ad2638] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "First Name": "Max", "Last Name": "The Mule", "Country": "Argentina" } ``` ### XML for Evaluating DataWeave Script from a File System Paste this code into your Studio XML editor to quickly load the flow for this example into your Mule app: ```xml ``` ## Evaluate DataWeave Script from a Database Example The following example selects a script from a database through a `userId` query parameter and stores that script in a `userScript` variable. The `dynamic-evaluate` component accesses the `userScript` variable to invoke the script using the provided parameter `name`, which contains the value of `attributes.queryParams.userName`. ```xml #["SELECT script FROM SCRIPTS WHERE ID = $(attributes.queryParams.userId)"] #[{name: attributes.queryParams.userName}] ``` Consider the following scripts stored in this example’s database for entries `lsalander` and `mblomkvist`, respectively: Example: lsalander script output application/json --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } Example: mblomkvist script output application/x-www-form-urlencoded --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } ### Example Application Behavior When this example Mule application receives `lsalander` as the `queryParams.userId` in the request, Mule executes the corresponding script, which results in a JSON response. If the application receives `mblomkvist` as the `queryParams.userId` value, Mule executes a different script that generates a `x-www-form-urlencoded` response. This example demonstrates how the response type can be parameterized based on the user, but the entire response can be parameterized to suit each users needs. --- product: Mule Runtime version: 4.6 keywords: mule, ee, esb, studio, dynamic, evaluate, expression --- # Dynamic Evaluate Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Dynamic Evaluate component evaluates an expression to select a DataWeave script, and then executes the new script to generate a result. This behavior enables you to dynamically select the script, instead of hardcoding it into the [Transform Message component](https://docs.mulesoft.com/mule-runtime/4.6/transform-component-about). The script can use any of the usual [context variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), such as `message`, `payload`,`vars`, or `attributes`, but you can also add custom ones by providing a set of key-value pairs. ## Dynamic Evaluate Configuration
FieldValueDescriptionExample

Expression

DataWeave expression

Specifies an expression that selects a DataWeave script that Mule then executes.

expression="#[vars.generateOrderScript]"

Parameters

DataWeave expression

Specifies key-value pairs to set as parameters that the DataWeave script can evaluate.

#[{joiner: ' and ', id: payload.user.id}]

## Evaluate DataWeave Script from the File System Example The following example shows how the Dynamic Evaluate component selects and executes a DataWeave script stored locally in the file system. The application’s flow behavior is as follows: 1. An HTTP Listener source listens to a POST URL request that contains a `locale` query parameter and a payload. 2. A File Read operation uses the `locale` query parameter received in the HTTP request to search locally the DataWeave script that matches the parameter name. 3. The File Read operation stores the content of the script into a new variable. 4. A Dynamic Evaluate component executes the DataWeave expression stored in the variable. 5. A Logger component logs the payload result of the transformation. The locally stored DataWeave scripts can be stored in a database instead of locally, and the app can be modified to pick the files from the database instead of the file system. This enables you to replace any of the `.dwl` files while the app is deployed and running, changing the DataWeave script to execute without having to modify or redeploy the application. In this example, you create two DataWeave scripts and store them locally, create the Mule application, and run and test the application: ![Dynamic Evaluate Flow example in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.6/_images/dynamic-evaluate-flow-1.png) Figure 1. Dynamic Evaluate Flow example in Anypoint Studio ### Create and Store the DataWeave Scripts The first step in evaluating DataWeave scripts from the file system is to create and locally store the scripts: 1. Create a new Mule project in Studio. 2. In the **Package Explorer** window, under the name of your Mule project, right-click the **src/main/resources** folder and select **New > File**. 3. In the **File name** field, add the name `dw_en-US.dwl` to create the new DataWeave script file. 4. Click **Finish**. 5. In the **dw\_en-US.dwl** window, paste the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "First Name": payload.name, "Last Name": payload.last, "Country": payload.loc } ``` 6. Repeat the previous steps and create a new file named `dw_es-AR.dwl` that contains the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "Nombre": payload.name, "Apellido": payload.last, "País": payload.loc } ``` 7. Save your changes. ### Create the Mule Application After creating and locally saving your example scripts, create the Mule application in Studio: 1. In the **Package Explorer** window **src/main/mule (Flows)** folder, navigate to your flow’s `.xml` file. 2. In the **Mule Palette** view, select the **HTTP Listener** source and drag it onto the canvas. The source initiates the flow by listening for incoming HTTP requests. 3. Set the **Path** field to `/test`. 4. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the HTTP Listener in the app. 5. On the **General** tab, configure the following fields: - **Host**: `All Interfaces [0.0.0.0] (default)` - **Port**: `8081` 6. Click **OK**. 7. Drag the **File Read** operation to the right of **HTTP Listener**. 8. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the File Read operation in the app. 9. On the **General** tab, set the **Working Directory** field to the main resources folder that contains your Studio project and previous DataWeave scripts: `/Users/username/AnypointStudio/studio-workspace/dynamicevaluate/src/main/resources` 10. Click **OK**. 11. In the **File path** field, set the path `#["dw_" ++ attributes.queryParams.locale ++ ".dwl"]`. The connector reads the locally stored DataWeave script file names that start with `dw_` and contains the `locale` query parameter (`attributes.queryParams.locale`) received in the HTTP request. 12. In the **Advanced** tab, set the **Target Variable** field to `dwScript`. This variable stores the DataWeave script that matched the file search. 13. Drag the **Dynamic Evaluate** component to the right of **File Read**. 14. Set the **Expression** field to `#[vars."dwScript"]` to execute the matched DataWeave script saved in the variable `dwScript`. 15. Set the **Target value** field to `payload`. 16. Drag a **Logger** component to the right of **Dynamic Evaluate**. 17. Set the **Message** field to `#[payload]`. 18. Save your Mule application. ### Run and Test the Mule Application After you create your Mule application, run and test it: 1. Click the project name in **Package Explorer** and then click **Run > Run As > Mule Application**. 2. Send a POST request to `http://localhost:8081/test`, appending to the URL any of the following query parameters `locale=en-US` or `locale=es-AR`, for example: `http://localhost:8081/test?locale=en-US` Additionally in the POST request, send the following payload: ```JSON { "name": "Max", "last": "The Mule", "loc": "Argentina" } ``` 3. In the Studio Console, scroll through the logs to see the result message: ```console INFO 2021-01-19 11:18:25,559 [[MuleRuntime].uber.12: [dynamicevaluate].dynamicevaluateFlow.CPU_INTENSIVE @2588f400] [processor: dynamicevaluateFlow/processors/2; event: 319aacc0-5a61-11eb-bbb8-f01898ad2638] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "First Name": "Max", "Last Name": "The Mule", "Country": "Argentina" } ``` ### XML for Evaluating DataWeave Script from a File System Paste this code into your Studio XML editor to quickly load the flow for this example into your Mule app: ```xml ``` ## Evaluate DataWeave Script from a Database Example The following example selects a script from a database through a `userId` query parameter and stores that script in a `userScript` variable. The `dynamic-evaluate` component accesses the `userScript` variable to invoke the script using the provided parameter `name`, which contains the value of `attributes.queryParams.userName`. ```xml #["SELECT script FROM SCRIPTS WHERE ID = $(attributes.queryParams.userId)"] #[{name: attributes.queryParams.userName}] ``` Consider the following scripts stored in this example’s database for entries `lsalander` and `mblomkvist`, respectively: Example: lsalander script output application/json --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } Example: mblomkvist script output application/x-www-form-urlencoded --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } ### Example Application Behavior When this example Mule application receives `lsalander` as the `queryParams.userId` in the request, Mule executes the corresponding script, which results in a JSON response. If the application receives `mblomkvist` as the `queryParams.userId` value, Mule executes a different script that generates a `x-www-form-urlencoded` response. This example demonstrates how the response type can be parameterized based on the user, but the entire response can be parameterized to suit each users needs. --- product: Mule Runtime version: 4.9 keywords: mule, ee, esb, studio, dynamic, evaluate, expression --- # Dynamic Evaluate Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Dynamic Evaluate component evaluates an expression to select a DataWeave script, and then executes the new script to generate a result. This behavior enables you to dynamically select the script, instead of hardcoding it into the [Transform Message component](https://docs.mulesoft.com/mule-runtime/4.9/transform-component-about). The script can use any of the usual [context variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), such as `message`, `payload`,`vars`, or `attributes`, but you can also add custom ones by providing a set of key-value pairs. ## Dynamic Evaluate Configuration
FieldValueDescriptionExample

Expression

DataWeave expression

Specifies an expression that selects a DataWeave script that Mule then executes.

expression="#[vars.generateOrderScript]"

Parameters

DataWeave expression

Specifies key-value pairs to set as parameters that the DataWeave script can evaluate.

#[{joiner: ' and ', id: payload.user.id}]

## Evaluate DataWeave Script from the File System Example The following example shows how the Dynamic Evaluate component selects and executes a DataWeave script stored locally in the file system. The application’s flow behavior is as follows: 1. An HTTP Listener source listens to a POST URL request that contains a `locale` query parameter and a payload. 2. A File Read operation uses the `locale` query parameter received in the HTTP request to search locally the DataWeave script that matches the parameter name. 3. The File Read operation stores the content of the script into a new variable. 4. A Dynamic Evaluate component executes the DataWeave expression stored in the variable. 5. A Logger component logs the payload result of the transformation. The locally stored DataWeave scripts can be stored in a database instead of locally, and the app can be modified to pick the files from the database instead of the file system. This enables you to replace any of the `.dwl` files while the app is deployed and running, changing the DataWeave script to execute without having to modify or redeploy the application. In this example, you create two DataWeave scripts and store them locally, create the Mule application, and run and test the application: ![A flow showing a dynamic evaluation component in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/dynamic-evaluate-flow-1.png) Figure 1. Dynamic Evaluate Flow example in Anypoint Studio ### Create and Store the DataWeave Scripts The first step in evaluating DataWeave scripts from the file system is to create and locally store the scripts: 1. Create a new Mule project in Studio. 2. In the **Package Explorer** window, under the name of your Mule project, right-click the **src/main/resources** folder and select **New > File**. 3. In the **File name** field, add the name `dw_en-US.dwl` to create the new DataWeave script file. 4. Click **Finish**. 5. In the **dw\_en-US.dwl** window, paste the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "First Name": payload.name, "Last Name": payload.last, "Country": payload.loc } ``` 6. Repeat the previous steps and create a new file named `dw_es-AR.dwl` that contains the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "Nombre": payload.name, "Apellido": payload.last, "País": payload.loc } ``` 7. Save your changes. ### Create the Mule Application After creating and locally saving your example scripts, create the Mule application in Studio: 1. In the **Package Explorer** window **src/main/mule (Flows)** folder, navigate to your flow’s `.xml` file. 2. In the **Mule Palette** view, select the **HTTP Listener** source and drag it onto the canvas. The source initiates the flow by listening for incoming HTTP requests. 3. Set the **Path** field to `/test`. 4. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the HTTP Listener in the app. 5. On the **General** tab, configure the following fields: - **Host**: `All Interfaces [0.0.0.0] (default)` - **Port**: `8081` 6. Click **OK**. 7. Drag the **File Read** operation to the right of **HTTP Listener**. 8. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the File Read operation in the app. 9. On the **General** tab, set the **Working Directory** field to the main resources folder that contains your Studio project and previous DataWeave scripts: `/Users/username/AnypointStudio/studio-workspace/dynamicevaluate/src/main/resources` 10. Click **OK**. 11. In the **File path** field, set the path `#["dw_" ++ attributes.queryParams.locale ++ ".dwl"]`. The connector reads the locally stored DataWeave script file names that start with `dw_` and contains the `locale` query parameter (`attributes.queryParams.locale`) received in the HTTP request. 12. In the **Advanced** tab, set the **Target Variable** field to `dwScript`. This variable stores the DataWeave script that matched the file search. 13. Drag the **Dynamic Evaluate** component to the right of **File Read**. 14. Set the **Expression** field to `#[vars."dwScript"]` to execute the matched DataWeave script saved in the variable `dwScript`. 15. Set the **Target value** field to `payload`. 16. Drag a **Logger** component to the right of **Dynamic Evaluate**. 17. Set the **Message** field to `#[payload]`. 18. Save your Mule application. ### Run and Test the Mule Application After you create your Mule application, run and test it: 1. Click the project name in **Package Explorer** and then click **Run > Run As > Mule Application**. 2. Send a POST request to `http://localhost:8081/test`, appending to the URL any of the following query parameters `locale=en-US` or `locale=es-AR`, for example: `http://localhost:8081/test?locale=en-US` Additionally in the POST request, send the following payload: ```JSON { "name": "Max", "last": "The Mule", "loc": "Argentina" } ``` 3. In the Studio Console, scroll through the logs to see the result message: ```console INFO 2021-01-19 11:18:25,559 [[MuleRuntime].uber.12: [dynamicevaluate].dynamicevaluateFlow.CPU_INTENSIVE @2588f400] [processor: dynamicevaluateFlow/processors/2; event: 319aacc0-5a61-11eb-bbb8-f01898ad2638] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "First Name": "Max", "Last Name": "The Mule", "Country": "Argentina" } ``` ### XML for Evaluating DataWeave Script from a File System Paste this code into your Studio XML editor to quickly load the flow for this example into your Mule app: ```xml ``` ## Evaluate DataWeave Script from a Database Example The following example selects a script from a database through a `userId` query parameter and stores that script in a `userScript` variable. The `dynamic-evaluate` component accesses the `userScript` variable to invoke the script using the provided parameter `name`, which contains the value of `attributes.queryParams.userName`. ```xml #["SELECT script FROM SCRIPTS WHERE ID = $(attributes.queryParams.userId)"] #[{name: attributes.queryParams.userName}] ``` Consider the following scripts stored in this example’s database for entries `lsalander` and `mblomkvist`, respectively: Example: lsalander script output application/json --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } Example: mblomkvist script output application/x-www-form-urlencoded --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } ### Example Application Behavior When this example Mule application receives `lsalander` as the `queryParams.userId` in the request, Mule executes the corresponding script, which results in a JSON response. If the application receives `mblomkvist` as the `queryParams.userId` value, Mule executes a different script that generates a `x-www-form-urlencoded` response. This example demonstrates how the response type can be parameterized based on the user, but the entire response can be parameterized to suit each users needs. --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: mule, ee, esb, studio, dynamic, evaluate, expression --- # Dynamic Evaluate Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Dynamic Evaluate component evaluates an expression to select a DataWeave script, and then executes the new script to generate a result. This behavior enables you to dynamically select the script, instead of hardcoding it into the [Transform Message component](https://docs.mulesoft.com/mule-runtime/latest/transform-component-about). The script can use any of the usual [context variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), such as `message`, `payload`,`vars`, or `attributes`, but you can also add custom ones by providing a set of key-value pairs. ## Dynamic Evaluate Configuration
FieldValueDescriptionExample

Expression

DataWeave expression

Specifies an expression that selects a DataWeave script that Mule then executes.

expression="#[vars.generateOrderScript]"

Parameters

DataWeave expression

Specifies key-value pairs to set as parameters that the DataWeave script can evaluate.

#[{joiner: ' and ', id: payload.user.id}]

## Evaluate DataWeave Script from the File System Example The following example shows how the Dynamic Evaluate component selects and executes a DataWeave script stored locally in the file system. The application’s flow behavior is as follows: 1. An HTTP Listener source listens to a POST URL request that contains a `locale` query parameter and a payload. 2. A File Read operation uses the `locale` query parameter received in the HTTP request to search locally the DataWeave script that matches the parameter name. 3. The File Read operation stores the content of the script into a new variable. 4. A Dynamic Evaluate component executes the DataWeave expression stored in the variable. 5. A Logger component logs the payload result of the transformation. The locally stored DataWeave scripts can be stored in a database instead of locally, and the app can be modified to pick the files from the database instead of the file system. This enables you to replace any of the `.dwl` files while the app is deployed and running, changing the DataWeave script to execute without having to modify or redeploy the application. In this example, you create two DataWeave scripts and store them locally, create the Mule application, and run and test the application: ![A flow showing a dynamic evaluation component in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/dynamic-evaluate-flow-1.png) Figure 1. Dynamic Evaluate Flow example in Anypoint Studio ### Create and Store the DataWeave Scripts The first step in evaluating DataWeave scripts from the file system is to create and locally store the scripts: 1. Create a new Mule project in Studio. 2. In the **Package Explorer** window, under the name of your Mule project, right-click the **src/main/resources** folder and select **New > File**. 3. In the **File name** field, add the name `dw_en-US.dwl` to create the new DataWeave script file. 4. Click **Finish**. 5. In the **dw\_en-US.dwl** window, paste the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "First Name": payload.name, "Last Name": payload.last, "Country": payload.loc } ``` 6. Repeat the previous steps and create a new file named `dw_es-AR.dwl` that contains the following DataWeave expression: ```dataweave %dw 2.0 output application/json --- { "Nombre": payload.name, "Apellido": payload.last, "País": payload.loc } ``` 7. Save your changes. ### Create the Mule Application After creating and locally saving your example scripts, create the Mule application in Studio: 1. In the **Package Explorer** window **src/main/mule (Flows)** folder, navigate to your flow’s `.xml` file. 2. In the **Mule Palette** view, select the **HTTP Listener** source and drag it onto the canvas. The source initiates the flow by listening for incoming HTTP requests. 3. Set the **Path** field to `/test`. 4. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the HTTP Listener in the app. 5. On the **General** tab, configure the following fields: - **Host**: `All Interfaces [0.0.0.0] (default)` - **Port**: `8081` 6. Click **OK**. 7. Drag the **File Read** operation to the right of **HTTP Listener**. 8. Click the plus sign (**+**) next to the **Connector configuration** field to configure a global element that can be used by all instances of the File Read operation in the app. 9. On the **General** tab, set the **Working Directory** field to the main resources folder that contains your Studio project and previous DataWeave scripts: `/Users/username/AnypointStudio/studio-workspace/dynamicevaluate/src/main/resources` 10. Click **OK**. 11. In the **File path** field, set the path `#["dw_" ++ attributes.queryParams.locale ++ ".dwl"]`. The connector reads the locally stored DataWeave script file names that start with `dw_` and contains the `locale` query parameter (`attributes.queryParams.locale`) received in the HTTP request. 12. In the **Advanced** tab, set the **Target Variable** field to `dwScript`. This variable stores the DataWeave script that matched the file search. 13. Drag the **Dynamic Evaluate** component to the right of **File Read**. 14. Set the **Expression** field to `#[vars."dwScript"]` to execute the matched DataWeave script saved in the variable `dwScript`. 15. Set the **Target value** field to `payload`. 16. Drag a **Logger** component to the right of **Dynamic Evaluate**. 17. Set the **Message** field to `#[payload]`. 18. Save your Mule application. ### Run and Test the Mule Application After you create your Mule application, run and test it: 1. Click the project name in **Package Explorer** and then click **Run > Run As > Mule Application**. 2. Send a POST request to `http://localhost:8081/test`, appending to the URL any of the following query parameters `locale=en-US` or `locale=es-AR`, for example: `http://localhost:8081/test?locale=en-US` Additionally in the POST request, send the following payload: ```JSON { "name": "Max", "last": "The Mule", "loc": "Argentina" } ``` 3. In the Studio Console, scroll through the logs to see the result message: ```console INFO 2021-01-19 11:18:25,559 [[MuleRuntime].uber.12: [dynamicevaluate].dynamicevaluateFlow.CPU_INTENSIVE @2588f400] [processor: dynamicevaluateFlow/processors/2; event: 319aacc0-5a61-11eb-bbb8-f01898ad2638] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "First Name": "Max", "Last Name": "The Mule", "Country": "Argentina" } ``` ### XML for Evaluating DataWeave Script from a File System Paste this code into your Studio XML editor to quickly load the flow for this example into your Mule app: ```xml ``` ## Evaluate DataWeave Script from a Database Example The following example selects a script from a database through a `userId` query parameter and stores that script in a `userScript` variable. The `dynamic-evaluate` component accesses the `userScript` variable to invoke the script using the provided parameter `name`, which contains the value of `attributes.queryParams.userName`. ```xml #["SELECT script FROM SCRIPTS WHERE ID = $(attributes.queryParams.userId)"] #[{name: attributes.queryParams.userName}] ``` Consider the following scripts stored in this example’s database for entries `lsalander` and `mblomkvist`, respectively: Example: lsalander script output application/json --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } Example: mblomkvist script output application/x-www-form-urlencoded --- { message: "Order " ++ attributes.queryParams.orderId ++ " has been received from " ++ name, items: payload.items } ### Example Application Behavior When this example Mule application receives `lsalander` as the `queryParams.userId` in the request, Mule executes the corresponding script, which results in a JSON response. If the application receives `mblomkvist` as the `queryParams.userId` value, Mule executes a different script that generates a `x-www-form-urlencoded` response. This example demonstrates how the response type can be parameterized based on the user, but the entire response can be parameterized to suit each users needs. --- product: Mule Runtime version: 4.11 --- # Enable Verbose Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can enable verbose logging for different modules and connectors. Because of the high impact to application performance, limit verbose logging to testing and troubleshooting operations. ## Configure Verbose Logging To configure verbose logging, add an entry to your `log4j2.xml` file, indicating the package names of the connectors or modules you want to log, and set the log level to `DEBUG`. The following example shows how to find the package names for Anypoint Connector JMS (JMS Connector) and configure verbose logging: 1. In the **Package Explorer** view, open the JMS Connector package library. 2. Inside the `.jar` file, locate all Mule-related packages. ![A package Explorer view listing various Java packages and libraries in a development environment](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-verbose-log-package.png) 3. Add an entry to your `log4j2.xml` file, indicating the package name and log level = `DEBUG`: ```xml ... ... ``` ## Common Connector Package Names The following table shows some common Anypoint Connectors and their package names so you don’t have to search for them:
Connector NamePackage Names

Anypoint Connector for HTTP

org.mule.service.http.impl.service.HttpMessageLogger

Anypoint Connector for Salesforce

org.mule.extension.salesforce

Anypoint Connector for FTP

org.mule.extension.ftp

Anypoint Connector for SFTP

  • org.mule.extension.sftp

  • com.jcraft

Anypoint Connector for FTPS

com.mulesoft.extension.ftps

Anypoint Connector for NetSuite

  • httpclient.wire.header

  • httpclient.wire.content

  • httpclient.wire

  • org.apache.commons.httpclient

  • org.apache.http

  • org.mule.module.netsuite

  • com.netsuite.webservices

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.mule.module.netsuite.extension.internal.connection.provider.soap.JavaWSDispatcher

Anypoint Connector for Amazon SQS

  • org.mule.extension.sqs

  • org.apache.http

Anypoint Connector for Microsoft Dynamics 365

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.apache.http

  • org.mule.extension.microsoftdynamics365

Anypoint Connector for MuleSoft SAP

org.mule.modules.sap

Anypoint Connector for Anypoint MQ

  • com.mulesoft.extension.mq

  • com.mulesoft.mq

Anypoint Connector for Database

org.mule.extension.db

Anypoint Connector for Microsoft SharePoint (version 3.x)

  • org.apache.http.wire

  • org.apache.http

--- product: Mule Runtime version: 4.12 --- # Enable Verbose Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can enable verbose logging for different modules and connectors. Because of the high impact to application performance, limit verbose logging to testing and troubleshooting operations. ## Configure Verbose Logging To configure verbose logging, add an entry to your `log4j2.xml` file, indicating the package names of the connectors or modules you want to log, and set the log level to `DEBUG`. The following example shows how to find the package names for Anypoint Connector JMS (JMS Connector) and configure verbose logging: 1. In the **Package Explorer** view, open the JMS Connector package library. 2. Inside the `.jar` file, locate all Mule-related packages. ![A package Explorer view listing various Java packages and libraries in a development environment](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-verbose-log-package.png) 3. Add an entry to your `log4j2.xml` file, indicating the package name and log level = `DEBUG`: ```xml ... ... ``` ## Common Connector Package Names The following table shows some common Anypoint Connectors and their package names so you don’t have to search for them:
Connector NamePackage Names

Anypoint Connector for HTTP

org.mule.service.http.impl.service.HttpMessageLogger

Anypoint Connector for Salesforce

org.mule.extension.salesforce

Anypoint Connector for FTP

org.mule.extension.ftp

Anypoint Connector for SFTP

  • org.mule.extension.sftp

  • com.jcraft

Anypoint Connector for FTPS

com.mulesoft.extension.ftps

Anypoint Connector for NetSuite

  • httpclient.wire.header

  • httpclient.wire.content

  • httpclient.wire

  • org.apache.commons.httpclient

  • org.apache.http

  • org.mule.module.netsuite

  • com.netsuite.webservices

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.mule.module.netsuite.extension.internal.connection.provider.soap.JavaWSDispatcher

Anypoint Connector for Amazon SQS

  • org.mule.extension.sqs

  • org.apache.http

Anypoint Connector for Microsoft Dynamics 365

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.apache.http

  • org.mule.extension.microsoftdynamics365

Anypoint Connector for MuleSoft SAP

org.mule.modules.sap

Anypoint Connector for Anypoint MQ

  • com.mulesoft.extension.mq

  • com.mulesoft.mq

Anypoint Connector for Database

org.mule.extension.db

Anypoint Connector for Microsoft SharePoint (version 3.x)

  • org.apache.http.wire

  • org.apache.http

--- product: Mule Runtime version: 4.3 --- # Enable Verbose Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can enable verbose logging for different modules and connectors. Because of the high impact to application performance, limit verbose logging to testing and troubleshooting operations. ## Configure Verbose Logging To configure verbose logging, add an entry to your `log4j2.xml` file, indicating the package names of the connectors or modules you want to log, and set the log level to `DEBUG`. The following example shows how to find the package names for Anypoint Connector JMS (JMS Connector) and configure verbose logging: 1. In the **Package Explorer** view, open the JMS Connector package library. 2. Inside the `.jar` file, locate all Mule-related packages. ![verbose-logging-package](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-verbose-log-package.png) 3. Add an entry to your `log4j2.xml` file, indicating the package name and log level = `DEBUG`: ```xml ... ... ``` ## Common Connector Package Names The following table shows some common Anypoint Connectors and their package names so you don’t have to search for them:
Connector NamePackage Names

Anypoint Connector for HTTP

org.mule.service.http.impl.service.HttpMessageLogger

Anypoint Connector for Salesforce

org.mule.extension.salesforce

Anypoint Connector for FTP

org.mule.extension.ftp

Anypoint Connector for SFTP

  • org.mule.extension.sftp

  • com.jcraft

Anypoint Connector for FTPS

com.mulesoft.extension.ftps

Anypoint Connector for NetSuite

  • httpclient.wire.header

  • httpclient.wire.content

  • httpclient.wire

  • org.apache.commons.httpclient

  • org.apache.http

  • org.mule.module.netsuite

  • com.netsuite.webservices

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.mule.module.netsuite.extension.internal.connection.provider.soap.JavaWSDispatcher

Anypoint Connector for Amazon SQS

  • org.mule.extension.sqs

  • org.apache.http

Anypoint Connector for Microsoft Dynamics 365

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.apache.http

  • org.mule.extension.microsoftdynamics365

Anypoint Connector for MuleSoft SAP

org.mule.modules.sap

Anypoint Connector for Anypoint MQ

  • com.mulesoft.extension.mq

  • com.mulesoft.mq

Anypoint Connector for Database

org.mule.extension.db

Anypoint Connector for Microsoft SharePoint (version 3.x)

  • org.apache.http.wire

  • org.apache.http

--- product: Mule Runtime version: 4.4 --- # Enable Verbose Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can enable verbose logging for different modules and connectors. Because of the high impact to application performance, limit verbose logging to testing and troubleshooting operations. ## Configure Verbose Logging To configure verbose logging, add an entry to your `log4j2.xml` file, indicating the package names of the connectors or modules you want to log, and set the log level to `DEBUG`. The following example shows how to find the package names for Anypoint Connector JMS (JMS Connector) and configure verbose logging: 1. In the **Package Explorer** view, open the JMS Connector package library. 2. Inside the `.jar` file, locate all Mule-related packages. ![verbose-logging-package](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-verbose-log-package.png) 3. Add an entry to your `log4j2.xml` file, indicating the package name and log level = `DEBUG`: ```xml ... ... ``` ## Common Connector Package Names The following table shows some common Anypoint Connectors and their package names so you don’t have to search for them:
Connector NamePackage Names

Anypoint Connector for HTTP

org.mule.service.http.impl.service.HttpMessageLogger

Anypoint Connector for Salesforce

org.mule.extension.salesforce

Anypoint Connector for FTP

org.mule.extension.ftp

Anypoint Connector for SFTP

  • org.mule.extension.sftp

  • com.jcraft

Anypoint Connector for FTPS

com.mulesoft.extension.ftps

Anypoint Connector for NetSuite

  • httpclient.wire.header

  • httpclient.wire.content

  • httpclient.wire

  • org.apache.commons.httpclient

  • org.apache.http

  • org.mule.module.netsuite

  • com.netsuite.webservices

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.mule.module.netsuite.extension.internal.connection.provider.soap.JavaWSDispatcher

Anypoint Connector for Amazon SQS

  • org.mule.extension.sqs

  • org.apache.http

Anypoint Connector for Microsoft Dynamics 365

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.apache.http

  • org.mule.extension.microsoftdynamics365

Anypoint Connector for MuleSoft SAP

org.mule.modules.sap

Anypoint Connector for Anypoint MQ

  • com.mulesoft.extension.mq

  • com.mulesoft.mq

Anypoint Connector for Database

org.mule.extension.db

Anypoint Connector for Microsoft SharePoint (version 3.x)

  • org.apache.http.wire

  • org.apache.http

--- product: Mule Runtime version: 4.6 --- # Enable Verbose Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can enable verbose logging for different modules and connectors. Because of the high impact to application performance, limit verbose logging to testing and troubleshooting operations. ## Configure Verbose Logging To configure verbose logging, add an entry to your `log4j2.xml` file, indicating the package names of the connectors or modules you want to log, and set the log level to `DEBUG`. The following example shows how to find the package names for Anypoint Connector JMS (JMS Connector) and configure verbose logging: 1. In the **Package Explorer** view, open the JMS Connector package library. 2. Inside the `.jar` file, locate all Mule-related packages. ![verbose-logging-package](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-verbose-log-package.png) 3. Add an entry to your `log4j2.xml` file, indicating the package name and log level = `DEBUG`: ```xml ... ... ``` ## Common Connector Package Names The following table shows some common Anypoint Connectors and their package names so you don’t have to search for them:
Connector NamePackage Names

Anypoint Connector for HTTP

org.mule.service.http.impl.service.HttpMessageLogger

Anypoint Connector for Salesforce

org.mule.extension.salesforce

Anypoint Connector for FTP

org.mule.extension.ftp

Anypoint Connector for SFTP

  • org.mule.extension.sftp

  • com.jcraft

Anypoint Connector for FTPS

com.mulesoft.extension.ftps

Anypoint Connector for NetSuite

  • httpclient.wire.header

  • httpclient.wire.content

  • httpclient.wire

  • org.apache.commons.httpclient

  • org.apache.http

  • org.mule.module.netsuite

  • com.netsuite.webservices

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.mule.module.netsuite.extension.internal.connection.provider.soap.JavaWSDispatcher

Anypoint Connector for Amazon SQS

  • org.mule.extension.sqs

  • org.apache.http

Anypoint Connector for Microsoft Dynamics 365

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.apache.http

  • org.mule.extension.microsoftdynamics365

Anypoint Connector for MuleSoft SAP

org.mule.modules.sap

Anypoint Connector for Anypoint MQ

  • com.mulesoft.extension.mq

  • com.mulesoft.mq

Anypoint Connector for Database

org.mule.extension.db

Anypoint Connector for Microsoft SharePoint (version 3.x)

  • org.apache.http.wire

  • org.apache.http

--- product: Mule Runtime version: 4.9 --- # Enable Verbose Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can enable verbose logging for different modules and connectors. Because of the high impact to application performance, limit verbose logging to testing and troubleshooting operations. ## Configure Verbose Logging To configure verbose logging, add an entry to your `log4j2.xml` file, indicating the package names of the connectors or modules you want to log, and set the log level to `DEBUG`. The following example shows how to find the package names for Anypoint Connector JMS (JMS Connector) and configure verbose logging: 1. In the **Package Explorer** view, open the JMS Connector package library. 2. Inside the `.jar` file, locate all Mule-related packages. ![A package Explorer view listing various Java packages and libraries in a development environment](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-verbose-log-package.png) 3. Add an entry to your `log4j2.xml` file, indicating the package name and log level = `DEBUG`: ```xml ... ... ``` ## Common Connector Package Names The following table shows some common Anypoint Connectors and their package names so you don’t have to search for them:
Connector NamePackage Names

Anypoint Connector for HTTP

org.mule.service.http.impl.service.HttpMessageLogger

Anypoint Connector for Salesforce

org.mule.extension.salesforce

Anypoint Connector for FTP

org.mule.extension.ftp

Anypoint Connector for SFTP

  • org.mule.extension.sftp

  • com.jcraft

Anypoint Connector for FTPS

com.mulesoft.extension.ftps

Anypoint Connector for NetSuite

  • httpclient.wire.header

  • httpclient.wire.content

  • httpclient.wire

  • org.apache.commons.httpclient

  • org.apache.http

  • org.mule.module.netsuite

  • com.netsuite.webservices

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.mule.module.netsuite.extension.internal.connection.provider.soap.JavaWSDispatcher

Anypoint Connector for Amazon SQS

  • org.mule.extension.sqs

  • org.apache.http

Anypoint Connector for Microsoft Dynamics 365

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.apache.http

  • org.mule.extension.microsoftdynamics365

Anypoint Connector for MuleSoft SAP

org.mule.modules.sap

Anypoint Connector for Anypoint MQ

  • com.mulesoft.extension.mq

  • com.mulesoft.mq

Anypoint Connector for Database

org.mule.extension.db

Anypoint Connector for Microsoft SharePoint (version 3.x)

  • org.apache.http.wire

  • org.apache.http

--- product: Mule Runtime version: 4.13 is-latest-version: true --- # Enable Verbose Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You can enable verbose logging for different modules and connectors. Because of the high impact to application performance, limit verbose logging to testing and troubleshooting operations. ## Configure Verbose Logging To configure verbose logging, add an entry to your `log4j2.xml` file, indicating the package names of the connectors or modules you want to log, and set the log level to `DEBUG`. The following example shows how to find the package names for Anypoint Connector JMS (JMS Connector) and configure verbose logging: 1. In the **Package Explorer** view, open the JMS Connector package library. 2. Inside the `.jar` file, locate all Mule-related packages. ![A package Explorer view listing various Java packages and libraries in a development environment](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-verbose-log-package.png) 3. Add an entry to your `log4j2.xml` file, indicating the package name and log level = `DEBUG`: ```xml ... ... ``` ## Common Connector Package Names The following table shows some common Anypoint Connectors and their package names so you don’t have to search for them:
Connector NamePackage Names

Anypoint Connector for HTTP

org.mule.service.http.impl.service.HttpMessageLogger

Anypoint Connector for Salesforce

org.mule.extension.salesforce

Anypoint Connector for FTP

org.mule.extension.ftp

Anypoint Connector for SFTP

  • org.mule.extension.sftp

  • com.jcraft

Anypoint Connector for FTPS

com.mulesoft.extension.ftps

Anypoint Connector for NetSuite

  • httpclient.wire.header

  • httpclient.wire.content

  • httpclient.wire

  • org.apache.commons.httpclient

  • org.apache.http

  • org.mule.module.netsuite

  • com.netsuite.webservices

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.mule.module.netsuite.extension.internal.connection.provider.soap.JavaWSDispatcher

Anypoint Connector for Amazon SQS

  • org.mule.extension.sqs

  • org.apache.http

Anypoint Connector for Microsoft Dynamics 365

  • org.mule.service.http.impl.service.HttpMessageLogger

  • org.apache.http

  • org.mule.extension.microsoftdynamics365

Anypoint Connector for MuleSoft SAP

org.mule.modules.sap

Anypoint Connector for Anypoint MQ

  • com.mulesoft.extension.mq

  • com.mulesoft.mq

Anypoint Connector for Database

org.mule.extension.db

Anypoint Connector for Microsoft SharePoint (version 3.x)

  • org.apache.http.wire

  • org.apache.http

--- product: Mule Runtime version: 4.11 --- # Enrich Data with Target Variables > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When creating a flow in a Mule app, you might need to store data in a variable so that any component in the flow can use it. Non-void operations (such as the Read operation to the File connector) can store the message data that they return in a variable. Once defined, variables created with the Target (`target`) parameter are available for use within the flow, and you can access them like you access any other variable. You often define variables through these parameters: - Target (`target`): Name of the variable in which you want to store message data. Names can only include numbers, characters, and underscores. For example, hyphens are not allowed in the name. - Target Value (`targetValue`): Value of the data to store in the target variable. By default, the value is the message payload (`payload`). The field accepts any value that a variable accepts: any supported data type, DataWeave expressions, the keywords `payload`, `attributes`, and `message`, but _not_ the keyword `vars`. ## Considerations - Setting a target variable changes the typical course of the message through the flow. Normally, an operation outputs a different message than it receives as input: ![A message flow standard behavior](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-payload-flow.png) However, when you set a variable from an operation, the operation outputs to the _next_ component in the flow the same message that it received as input. For example, assume you have a flow consisting of component A, followed by component B with a target value of `myMessage`, and then component C. In this case, component C receives the same message that B received from A: ![A message flow with target variable](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-payload-flow-target-variable.png) - Configuring target variables affects the behavior of existing variables. Existing variables retain their original values after an operation with a target variable finishes processing. For example, consider a flow where you set variables 1 and 2, and then an operation modifies variables 1 and 2 and also outputs a target variable A. In this case, after the execution of the operation, variables 1 and 2 return to their previous values: ![A message flow with target variable and additional variables](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-payload-flow-target-variable-2.png)
1Because the component sets a target variable, variable 1 and 2 revert to their previous values after the execution of the component.
- Target variables are not set when an error occurs. Because the execution of the flow stops and does not end successfully when an error occurs, target variables are not set in this scenario. ## Target Variable Configuration Examples The following example configures a Read operation that stores the payload of `readme.txt` in `myVar`: ```xml ``` Note that the target variable `myVar` stores the complete payload by default. You only need to specify a Target Value (`targetValue`) if you want to store a value different than the payload. In this example, the entire message is stored in `myVar`: ```xml ``` In this case, the variable `myVar` contains the content of the file and also all the metadata related. - Expression to access the file content: `#[myVar.payload]` - Expression to access the file metadata: `#[myVar.attributes]` In this example, only the file size is stored in `myVar`: ```xml ``` The following scenarios describe some cases where you might use target variables. ## Scenario: Setting a Target Variable from within an Operation Assume that you want to log the entire message (payload and attributes) returned by a Database connector operation, such as Insert. Instead of using a Set Variable component after the operation, you can instead capture the message data by adding a target variable directly to the operation: ```xml INSERT INTO PLANET(POSITION, NAME, DESCRIPTION) VALUES (777, 'Pluto', :description) #[{'description' : payload}] ``` - Target Variable for the Insert operation: `result` - Target Value: `message` in Design Center, `#[message]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `Payload is: #[vars.result.payload] and attributes are: #[vars.result.attributes]` Assume that you want to log the name of the first entry in a planet database. You can define a target variable like this one through the Select operation of the Database connector: ```xml select * from PLANET order by ID ``` - Target Variable for the Select operation: `planetName` - Target Value: `payload[0].name` in Design Center, `#[payload[0].name]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `'Planet name is: ' ++ vars.planetName` ## Scenario: Using the Stored Value as Input to an Operation Assume that you want to access all planets discovered after a given planet was discovered. You might create a target variable called `discoveryDate` within a select operation to capture the a planet’s discovery date. ```xml select discoveryDate from PLANET where name = :name #[{'name' : 'pluto'}] ``` - Target Variable for the Retrieve operation: `discoveryDate` Then you can use the Input parameter of another operation in your flow (such as the Select operation to the Database connector) to make the variable available for use in your query, for example: ```xml select * from PLANET where discoveryDate > :discoveryDate #[{'discoveryDate' : vars.discoveryDate}] ``` - Input Parameter definition for the Select operation: - Key: `discoveryDate` - Value: `vars.discoveryDate` in Design Center, `#[vars.discoveryDate]` in Anypoint Studio. ## Scenario: Bypassing the Normal Message Flow Assume that you want to insert a number of records into a database that are located in the messages’s payload, then pass those same records on for further processing by the next component in your flow. Though you want to use the Bulk Insert operation to the Database connector to insert the records, the operation returns a success message that replaces the current payload, which makes the records inaccessible. So, to pass on the records to the next component instead of replacing the payload with the Bulk Insert result, you can store the success message in a target variable, for example: - Target Variable: `bulkInsertResult` Then the next operation in your flow can process the records located in the payload. ## See Also - [Testing a Processor That Stores Data in a Target Variable](https://docs.mulesoft.com/munit/latest/test-processor-that-uses-target-variable) - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-event) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-variables) --- product: Mule Runtime version: 4.12 --- # Enrich Data with Target Variables > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When creating a flow in a Mule app, you might need to store data in a variable so that any component in the flow can use it. Non-void operations (such as the Read operation to the File connector) can store the message data that they return in a variable. Once defined, variables created with the Target (`target`) parameter are available for use within the flow, and you can access them like you access any other variable. You often define variables through these parameters: - Target (`target`): Name of the variable in which you want to store message data. Names can only include numbers, characters, and underscores. For example, hyphens are not allowed in the name. - Target Value (`targetValue`): Value of the data to store in the target variable. By default, the value is the message payload (`payload`). The field accepts any value that a variable accepts: any supported data type, DataWeave expressions, the keywords `payload`, `attributes`, and `message`, but _not_ the keyword `vars`. ## Considerations - Setting a target variable changes the typical course of the message through the flow. Normally, an operation outputs a different message than it receives as input: ![A message flow standard behavior](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-payload-flow.png) However, when you set a variable from an operation, the operation outputs to the _next_ component in the flow the same message that it received as input. For example, assume you have a flow consisting of component A, followed by component B with a target value of `myMessage`, and then component C. In this case, component C receives the same message that B received from A: ![A message flow with target variable](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-payload-flow-target-variable.png) - Configuring target variables affects the behavior of existing variables. Existing variables retain their original values after an operation with a target variable finishes processing. For example, consider a flow where you set variables 1 and 2, and then an operation modifies variables 1 and 2 and also outputs a target variable A. In this case, after the execution of the operation, variables 1 and 2 return to their previous values: ![A message flow with target variable and additional variables](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-payload-flow-target-variable-2.png)
1Because the component sets a target variable, variable 1 and 2 revert to their previous values after the execution of the component.
- Target variables are not set when an error occurs. Because the execution of the flow stops and does not end successfully when an error occurs, target variables are not set in this scenario. ## Target Variable Configuration Examples The following example configures a Read operation that stores the payload of `readme.txt` in `myVar`: ```xml ``` Note that the target variable `myVar` stores the complete payload by default. You only need to specify a Target Value (`targetValue`) if you want to store a value different than the payload. In this example, the entire message is stored in `myVar`: ```xml ``` In this case, the variable `myVar` contains the content of the file and also all the metadata related. - Expression to access the file content: `#[myVar.payload]` - Expression to access the file metadata: `#[myVar.attributes]` In this example, only the file size is stored in `myVar`: ```xml ``` The following scenarios describe some cases where you might use target variables. ## Scenario: Setting a Target Variable from within an Operation Assume that you want to log the entire message (payload and attributes) returned by a Database connector operation, such as Insert. Instead of using a Set Variable component after the operation, you can instead capture the message data by adding a target variable directly to the operation: ```xml INSERT INTO PLANET(POSITION, NAME, DESCRIPTION) VALUES (777, 'Pluto', :description) #[{'description' : payload}] ``` - Target Variable for the Insert operation: `result` - Target Value: `message` in Design Center, `#[message]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `Payload is: #[vars.result.payload] and attributes are: #[vars.result.attributes]` Assume that you want to log the name of the first entry in a planet database. You can define a target variable like this one through the Select operation of the Database connector: ```xml select * from PLANET order by ID ``` - Target Variable for the Select operation: `planetName` - Target Value: `payload[0].name` in Design Center, `#[payload[0].name]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `'Planet name is: ' ++ vars.planetName` ## Scenario: Using the Stored Value as Input to an Operation Assume that you want to access all planets discovered after a given planet was discovered. You might create a target variable called `discoveryDate` within a select operation to capture the a planet’s discovery date. ```xml select discoveryDate from PLANET where name = :name #[{'name' : 'pluto'}] ``` - Target Variable for the Retrieve operation: `discoveryDate` Then you can use the Input parameter of another operation in your flow (such as the Select operation to the Database connector) to make the variable available for use in your query, for example: ```xml select * from PLANET where discoveryDate > :discoveryDate #[{'discoveryDate' : vars.discoveryDate}] ``` - Input Parameter definition for the Select operation: - Key: `discoveryDate` - Value: `vars.discoveryDate` in Design Center, `#[vars.discoveryDate]` in Anypoint Studio. ## Scenario: Bypassing the Normal Message Flow Assume that you want to insert a number of records into a database that are located in the messages’s payload, then pass those same records on for further processing by the next component in your flow. Though you want to use the Bulk Insert operation to the Database connector to insert the records, the operation returns a success message that replaces the current payload, which makes the records inaccessible. So, to pass on the records to the next component instead of replacing the payload with the Bulk Insert result, you can store the success message in a target variable, for example: - Target Variable: `bulkInsertResult` Then the next operation in your flow can process the records located in the payload. ## See Also - [Testing a Processor That Stores Data in a Target Variable](https://docs.mulesoft.com/munit/latest/test-processor-that-uses-target-variable) - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-event) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-variables) --- product: Mule Runtime version: 4.3 --- # Enrich Data with Target Variables > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When creating a flow in a Mule app, you might need to store data in a variable so that any component in the flow can use it. Non-void operations (such as the Read operation to the File connector) can store the message data that they return in a variable. Once defined, variables created with the Target (`target`) parameter are available for use within the flow, and you can access them like you access any other variable. You often define variables through these parameters: - Target (`target`): Name of the variable in which you want to store message data. Names can only include numbers, characters, and underscores. For example, hyphens are not allowed in the name. - Target Value (`targetValue`): Value of the data to store in the target variable. By default, the value is the message payload (`payload`). The field accepts any value that a variable accepts: any supported data type, DataWeave expressions, the keywords `payload`, `attributes`, and `message`, but _not_ the keyword `vars`. ## Considerations Setting a target variable changes the typical course of the message through the flow. Normally, an operation outputs a different message than it receives as input: ![Message flow standard behavior](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-payload-flow.png) However, when you set a variable from an operation, the operation outputs to the _next_ component in the flow the same message that it received as input. For example, assume you have a flow consisting of component A, followed by component B with a target value of `myMessage`, and then component C. In this case, component C receives the same message that B received from A: ![Message flow with target variable](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-payload-flow-target-variable.png) Configuring target variables also affects the behavior of existing variables, which retain their original values after an operation with a target variable finishes processing. For example, consider a flow where you set variables 1 and 2, and then an operation modifies variables 1 and 2 and also outputs a target variable A. In this case, after the execution of the operation, variables 1 and 2 return to their previous values: ![Message flow with target variable and additional variables](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-payload-flow-target-variable-2.png)
1Because the component sets a target variable, variable 1 and 2 revert to their previous values after the execution of the component.
## Target Variable Configuration Examples The following example configures a Read operation that stores the payload of `readme.txt` in `myVar`: ```xml ``` Note that the target variable `myVar` stores the complete payload by default. You only need to specify a Target Value (`targetValue`) if you want to store a value different than the payload. In this example, the entire message is stored in `myVar`: ```xml ``` In this case, the variable `myVar` contains the content of the file and also all the metadata related. - Expression to access the file content: `#[myVar.payload]` - Expression to access the file metadata: `#[myVar.attributes]` In this example, only the file size is stored in `myVar`: ```xml ``` The following scenarios describe some cases where you might use target variables. ## Scenario: Setting a Target Variable from within an Operation Assume that you want to log the entire message (payload and attributes) returned by a Database connector operation, such as Insert. Instead of using a Set Variable component after the operation, you can instead capture the message data by adding a target variable directly to the operation: ```xml INSERT INTO PLANET(POSITION, NAME, DESCRIPTION) VALUES (777, 'Pluto', :description) #[{'description' : payload}] ``` - Target Variable for the Insert operation: `result` - Target Value: `message` in Design Center, `#[message]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `Payload is: #[vars.result.payload] and attributes are: #[vars.result.attributes]` Assume that you want to log the name of the first entry in a planet database. You can define a target variable like this one through the Select operation of the Database connector: ```xml select * from PLANET order by ID ``` - Target Variable for the Select operation: `planetName` - Target Value: `payload[0].name` in Design Center, `#[payload[0].name]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `'Planet name is: ' ++ vars.planetName` ## Scenario: Using the Stored Value as Input to an Operation Assume that you want to access all planets discovered after a given planet was discovered. You might create a target variable called `discoveryDate` within a select operation to capture the a planet’s discovery date. ```xml select discoveryDate from PLANET where name = :name #[{'name' : 'pluto'}] ``` - Target Variable for the Retrieve operation: `discoveryDate` Then you can use the Input parameter of another operation in your flow (such as the Select operation to the Database connector) to make the variable available for use in your query, for example: ```xml select * from PLANET where discoveryDate > :discoveryDate #[{'discoveryDate' : vars.discoveryDate}] ``` - Input Parameter definition for the Select operation: - Key: `discoveryDate` - Value: `vars.discoveryDate` in Design Center, `#[vars.discoveryDate]` in Anypoint Studio. ## Scenario: Bypassing the Normal Message Flow Assume that you want to insert a number of records into a database that are located in the messages’s payload, then pass those same records on for further processing by the next component in your flow. Though you want to use the Bulk Insert operation to the Database connector to insert the records, the operation returns a success message that replaces the current payload, which makes the records inaccessible. So, to pass on the records to the next component instead of replacing the payload with the Bulk Insert result, you can store the success message in a target variable, for example: - Target Variable: `bulkInsertResult` Then the next operation in your flow can process the records located in the payload. ## See Also - [Testing a Processor That Stores Data in a Target Variable](https://docs.mulesoft.com/munit/latest/test-processor-that-uses-target-variable) - [Mule 4 Programming Model](https://docs.mulesoft.com/mule-runtime/4.3/intro-programming-model) - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-event) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-variables) --- product: Mule Runtime version: 4.4 --- # Enrich Data with Target Variables > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When creating a flow in a Mule app, you might need to store data in a variable so that any component in the flow can use it. Non-void operations (such as the Read operation to the File connector) can store the message data that they return in a variable. Once defined, variables created with the Target (`target`) parameter are available for use within the flow, and you can access them like you access any other variable. You often define variables through these parameters: - Target (`target`): Name of the variable in which you want to store message data. Names can only include numbers, characters, and underscores. For example, hyphens are not allowed in the name. - Target Value (`targetValue`): Value of the data to store in the target variable. By default, the value is the message payload (`payload`). The field accepts any value that a variable accepts: any supported data type, DataWeave expressions, the keywords `payload`, `attributes`, and `message`, but _not_ the keyword `vars`. ## Considerations - Setting a target variable changes the typical course of the message through the flow. Normally, an operation outputs a different message than it receives as input: ![Message flow standard behavior](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-payload-flow.png) However, when you set a variable from an operation, the operation outputs to the _next_ component in the flow the same message that it received as input. For example, assume you have a flow consisting of component A, followed by component B with a target value of `myMessage`, and then component C. In this case, component C receives the same message that B received from A: ![Message flow with target variable](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-payload-flow-target-variable.png) - Configuring target variables affects the behavior of existing variables. Existing variables retain their original values after an operation with a target variable finishes processing. For example, consider a flow where you set variables 1 and 2, and then an operation modifies variables 1 and 2 and also outputs a target variable A. In this case, after the execution of the operation, variables 1 and 2 return to their previous values: ![Message flow with target variable and additional variables](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-payload-flow-target-variable-2.png)
1Because the component sets a target variable, variable 1 and 2 revert to their previous values after the execution of the component.
- Target variables are not set when an error occurs. Because the execution of the flow stops and does not end successfully when an error occurs, target variables are not set in this scenario. ## Target Variable Configuration Examples The following example configures a Read operation that stores the payload of `readme.txt` in `myVar`: ```xml ``` Note that the target variable `myVar` stores the complete payload by default. You only need to specify a Target Value (`targetValue`) if you want to store a value different than the payload. In this example, the entire message is stored in `myVar`: ```xml ``` In this case, the variable `myVar` contains the content of the file and also all the metadata related. - Expression to access the file content: `#[myVar.payload]` - Expression to access the file metadata: `#[myVar.attributes]` In this example, only the file size is stored in `myVar`: ```xml ``` The following scenarios describe some cases where you might use target variables. ## Scenario: Setting a Target Variable from within an Operation Assume that you want to log the entire message (payload and attributes) returned by a Database connector operation, such as Insert. Instead of using a Set Variable component after the operation, you can instead capture the message data by adding a target variable directly to the operation: ```xml INSERT INTO PLANET(POSITION, NAME, DESCRIPTION) VALUES (777, 'Pluto', :description) #[{'description' : payload}] ``` - Target Variable for the Insert operation: `result` - Target Value: `message` in Design Center, `#[message]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `Payload is: #[vars.result.payload] and attributes are: #[vars.result.attributes]` Assume that you want to log the name of the first entry in a planet database. You can define a target variable like this one through the Select operation of the Database connector: ```xml select * from PLANET order by ID ``` - Target Variable for the Select operation: `planetName` - Target Value: `payload[0].name` in Design Center, `#[payload[0].name]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `'Planet name is: ' ++ vars.planetName` ## Scenario: Using the Stored Value as Input to an Operation Assume that you want to access all planets discovered after a given planet was discovered. You might create a target variable called `discoveryDate` within a select operation to capture the a planet’s discovery date. ```xml select discoveryDate from PLANET where name = :name #[{'name' : 'pluto'}] ``` - Target Variable for the Retrieve operation: `discoveryDate` Then you can use the Input parameter of another operation in your flow (such as the Select operation to the Database connector) to make the variable available for use in your query, for example: ```xml select * from PLANET where discoveryDate > :discoveryDate #[{'discoveryDate' : vars.discoveryDate}] ``` - Input Parameter definition for the Select operation: - Key: `discoveryDate` - Value: `vars.discoveryDate` in Design Center, `#[vars.discoveryDate]` in Anypoint Studio. ## Scenario: Bypassing the Normal Message Flow Assume that you want to insert a number of records into a database that are located in the messages’s payload, then pass those same records on for further processing by the next component in your flow. Though you want to use the Bulk Insert operation to the Database connector to insert the records, the operation returns a success message that replaces the current payload, which makes the records inaccessible. So, to pass on the records to the next component instead of replacing the payload with the Bulk Insert result, you can store the success message in a target variable, for example: - Target Variable: `bulkInsertResult` Then the next operation in your flow can process the records located in the payload. ## See Also - [Testing a Processor That Stores Data in a Target Variable](https://docs.mulesoft.com/munit/latest/test-processor-that-uses-target-variable) - [Mule 4 Programming Model](https://docs.mulesoft.com/mule-runtime/4.4/intro-programming-model) - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-event) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-variables) --- product: Mule Runtime version: 4.6 --- # Enrich Data with Target Variables > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When creating a flow in a Mule app, you might need to store data in a variable so that any component in the flow can use it. Non-void operations (such as the Read operation to the File connector) can store the message data that they return in a variable. Once defined, variables created with the Target (`target`) parameter are available for use within the flow, and you can access them like you access any other variable. You often define variables through these parameters: - Target (`target`): Name of the variable in which you want to store message data. Names can only include numbers, characters, and underscores. For example, hyphens are not allowed in the name. - Target Value (`targetValue`): Value of the data to store in the target variable. By default, the value is the message payload (`payload`). The field accepts any value that a variable accepts: any supported data type, DataWeave expressions, the keywords `payload`, `attributes`, and `message`, but _not_ the keyword `vars`. ## Considerations - Setting a target variable changes the typical course of the message through the flow. Normally, an operation outputs a different message than it receives as input: ![Message flow standard behavior](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-payload-flow.png) However, when you set a variable from an operation, the operation outputs to the _next_ component in the flow the same message that it received as input. For example, assume you have a flow consisting of component A, followed by component B with a target value of `myMessage`, and then component C. In this case, component C receives the same message that B received from A: ![Message flow with target variable](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-payload-flow-target-variable.png) - Configuring target variables affects the behavior of existing variables. Existing variables retain their original values after an operation with a target variable finishes processing. For example, consider a flow where you set variables 1 and 2, and then an operation modifies variables 1 and 2 and also outputs a target variable A. In this case, after the execution of the operation, variables 1 and 2 return to their previous values: ![Message flow with target variable and additional variables](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-payload-flow-target-variable-2.png)
1Because the component sets a target variable, variable 1 and 2 revert to their previous values after the execution of the component.
- Target variables are not set when an error occurs. Because the execution of the flow stops and does not end successfully when an error occurs, target variables are not set in this scenario. ## Target Variable Configuration Examples The following example configures a Read operation that stores the payload of `readme.txt` in `myVar`: ```xml ``` Note that the target variable `myVar` stores the complete payload by default. You only need to specify a Target Value (`targetValue`) if you want to store a value different than the payload. In this example, the entire message is stored in `myVar`: ```xml ``` In this case, the variable `myVar` contains the content of the file and also all the metadata related. - Expression to access the file content: `#[myVar.payload]` - Expression to access the file metadata: `#[myVar.attributes]` In this example, only the file size is stored in `myVar`: ```xml ``` The following scenarios describe some cases where you might use target variables. ## Scenario: Setting a Target Variable from within an Operation Assume that you want to log the entire message (payload and attributes) returned by a Database connector operation, such as Insert. Instead of using a Set Variable component after the operation, you can instead capture the message data by adding a target variable directly to the operation: ```xml INSERT INTO PLANET(POSITION, NAME, DESCRIPTION) VALUES (777, 'Pluto', :description) #[{'description' : payload}] ``` - Target Variable for the Insert operation: `result` - Target Value: `message` in Design Center, `#[message]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `Payload is: #[vars.result.payload] and attributes are: #[vars.result.attributes]` Assume that you want to log the name of the first entry in a planet database. You can define a target variable like this one through the Select operation of the Database connector: ```xml select * from PLANET order by ID ``` - Target Variable for the Select operation: `planetName` - Target Value: `payload[0].name` in Design Center, `#[payload[0].name]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `'Planet name is: ' ++ vars.planetName` ## Scenario: Using the Stored Value as Input to an Operation Assume that you want to access all planets discovered after a given planet was discovered. You might create a target variable called `discoveryDate` within a select operation to capture the a planet’s discovery date. ```xml select discoveryDate from PLANET where name = :name #[{'name' : 'pluto'}] ``` - Target Variable for the Retrieve operation: `discoveryDate` Then you can use the Input parameter of another operation in your flow (such as the Select operation to the Database connector) to make the variable available for use in your query, for example: ```xml select * from PLANET where discoveryDate > :discoveryDate #[{'discoveryDate' : vars.discoveryDate}] ``` - Input Parameter definition for the Select operation: - Key: `discoveryDate` - Value: `vars.discoveryDate` in Design Center, `#[vars.discoveryDate]` in Anypoint Studio. ## Scenario: Bypassing the Normal Message Flow Assume that you want to insert a number of records into a database that are located in the messages’s payload, then pass those same records on for further processing by the next component in your flow. Though you want to use the Bulk Insert operation to the Database connector to insert the records, the operation returns a success message that replaces the current payload, which makes the records inaccessible. So, to pass on the records to the next component instead of replacing the payload with the Bulk Insert result, you can store the success message in a target variable, for example: - Target Variable: `bulkInsertResult` Then the next operation in your flow can process the records located in the payload. ## See Also - [Testing a Processor That Stores Data in a Target Variable](https://docs.mulesoft.com/munit/latest/test-processor-that-uses-target-variable) - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-event) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-variables) --- product: Mule Runtime version: 4.9 --- # Enrich Data with Target Variables > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When creating a flow in a Mule app, you might need to store data in a variable so that any component in the flow can use it. Non-void operations (such as the Read operation to the File connector) can store the message data that they return in a variable. Once defined, variables created with the Target (`target`) parameter are available for use within the flow, and you can access them like you access any other variable. You often define variables through these parameters: - Target (`target`): Name of the variable in which you want to store message data. Names can only include numbers, characters, and underscores. For example, hyphens are not allowed in the name. - Target Value (`targetValue`): Value of the data to store in the target variable. By default, the value is the message payload (`payload`). The field accepts any value that a variable accepts: any supported data type, DataWeave expressions, the keywords `payload`, `attributes`, and `message`, but _not_ the keyword `vars`. ## Considerations - Setting a target variable changes the typical course of the message through the flow. Normally, an operation outputs a different message than it receives as input: ![A message flow standard behavior](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-payload-flow.png) However, when you set a variable from an operation, the operation outputs to the _next_ component in the flow the same message that it received as input. For example, assume you have a flow consisting of component A, followed by component B with a target value of `myMessage`, and then component C. In this case, component C receives the same message that B received from A: ![A message flow with target variable](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-payload-flow-target-variable.png) - Configuring target variables affects the behavior of existing variables. Existing variables retain their original values after an operation with a target variable finishes processing. For example, consider a flow where you set variables 1 and 2, and then an operation modifies variables 1 and 2 and also outputs a target variable A. In this case, after the execution of the operation, variables 1 and 2 return to their previous values: ![A message flow with target variable and additional variables](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-payload-flow-target-variable-2.png)
1Because the component sets a target variable, variable 1 and 2 revert to their previous values after the execution of the component.
- Target variables are not set when an error occurs. Because the execution of the flow stops and does not end successfully when an error occurs, target variables are not set in this scenario. ## Target Variable Configuration Examples The following example configures a Read operation that stores the payload of `readme.txt` in `myVar`: ```xml ``` Note that the target variable `myVar` stores the complete payload by default. You only need to specify a Target Value (`targetValue`) if you want to store a value different than the payload. In this example, the entire message is stored in `myVar`: ```xml ``` In this case, the variable `myVar` contains the content of the file and also all the metadata related. - Expression to access the file content: `#[myVar.payload]` - Expression to access the file metadata: `#[myVar.attributes]` In this example, only the file size is stored in `myVar`: ```xml ``` The following scenarios describe some cases where you might use target variables. ## Scenario: Setting a Target Variable from within an Operation Assume that you want to log the entire message (payload and attributes) returned by a Database connector operation, such as Insert. Instead of using a Set Variable component after the operation, you can instead capture the message data by adding a target variable directly to the operation: ```xml INSERT INTO PLANET(POSITION, NAME, DESCRIPTION) VALUES (777, 'Pluto', :description) #[{'description' : payload}] ``` - Target Variable for the Insert operation: `result` - Target Value: `message` in Design Center, `#[message]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `Payload is: #[vars.result.payload] and attributes are: #[vars.result.attributes]` Assume that you want to log the name of the first entry in a planet database. You can define a target variable like this one through the Select operation of the Database connector: ```xml select * from PLANET order by ID ``` - Target Variable for the Select operation: `planetName` - Target Value: `payload[0].name` in Design Center, `#[payload[0].name]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `'Planet name is: ' ++ vars.planetName` ## Scenario: Using the Stored Value as Input to an Operation Assume that you want to access all planets discovered after a given planet was discovered. You might create a target variable called `discoveryDate` within a select operation to capture the a planet’s discovery date. ```xml select discoveryDate from PLANET where name = :name #[{'name' : 'pluto'}] ``` - Target Variable for the Retrieve operation: `discoveryDate` Then you can use the Input parameter of another operation in your flow (such as the Select operation to the Database connector) to make the variable available for use in your query, for example: ```xml select * from PLANET where discoveryDate > :discoveryDate #[{'discoveryDate' : vars.discoveryDate}] ``` - Input Parameter definition for the Select operation: - Key: `discoveryDate` - Value: `vars.discoveryDate` in Design Center, `#[vars.discoveryDate]` in Anypoint Studio. ## Scenario: Bypassing the Normal Message Flow Assume that you want to insert a number of records into a database that are located in the messages’s payload, then pass those same records on for further processing by the next component in your flow. Though you want to use the Bulk Insert operation to the Database connector to insert the records, the operation returns a success message that replaces the current payload, which makes the records inaccessible. So, to pass on the records to the next component instead of replacing the payload with the Bulk Insert result, you can store the success message in a target variable, for example: - Target Variable: `bulkInsertResult` Then the next operation in your flow can process the records located in the payload. ## See Also - [Testing a Processor That Stores Data in a Target Variable](https://docs.mulesoft.com/munit/latest/test-processor-that-uses-target-variable) - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-event) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-variables) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Enrich Data with Target Variables > For the full documentation index, see: https://docs.mulesoft.com/llms.txt When creating a flow in a Mule app, you might need to store data in a variable so that any component in the flow can use it. Non-void operations (such as the Read operation to the File connector) can store the message data that they return in a variable. Once defined, variables created with the Target (`target`) parameter are available for use within the flow, and you can access them like you access any other variable. You often define variables through these parameters: - Target (`target`): Name of the variable in which you want to store message data. Names can only include numbers, characters, and underscores. For example, hyphens are not allowed in the name. - Target Value (`targetValue`): Value of the data to store in the target variable. By default, the value is the message payload (`payload`). The field accepts any value that a variable accepts: any supported data type, DataWeave expressions, the keywords `payload`, `attributes`, and `message`, but _not_ the keyword `vars`. ## Considerations - Setting a target variable changes the typical course of the message through the flow. Normally, an operation outputs a different message than it receives as input: ![A message flow standard behavior](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-payload-flow.png) However, when you set a variable from an operation, the operation outputs to the _next_ component in the flow the same message that it received as input. For example, assume you have a flow consisting of component A, followed by component B with a target value of `myMessage`, and then component C. In this case, component C receives the same message that B received from A: ![A message flow with target variable](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-payload-flow-target-variable.png) - Configuring target variables affects the behavior of existing variables. Existing variables retain their original values after an operation with a target variable finishes processing. For example, consider a flow where you set variables 1 and 2, and then an operation modifies variables 1 and 2 and also outputs a target variable A. In this case, after the execution of the operation, variables 1 and 2 return to their previous values: ![A message flow with target variable and additional variables](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-payload-flow-target-variable-2.png)
1Because the component sets a target variable, variable 1 and 2 revert to their previous values after the execution of the component.
- Target variables are not set when an error occurs. Because the execution of the flow stops and does not end successfully when an error occurs, target variables are not set in this scenario. ## Target Variable Configuration Examples The following example configures a Read operation that stores the payload of `readme.txt` in `myVar`: ```xml ``` Note that the target variable `myVar` stores the complete payload by default. You only need to specify a Target Value (`targetValue`) if you want to store a value different than the payload. In this example, the entire message is stored in `myVar`: ```xml ``` In this case, the variable `myVar` contains the content of the file and also all the metadata related. - Expression to access the file content: `#[myVar.payload]` - Expression to access the file metadata: `#[myVar.attributes]` In this example, only the file size is stored in `myVar`: ```xml ``` The following scenarios describe some cases where you might use target variables. ## Scenario: Setting a Target Variable from within an Operation Assume that you want to log the entire message (payload and attributes) returned by a Database connector operation, such as Insert. Instead of using a Set Variable component after the operation, you can instead capture the message data by adding a target variable directly to the operation: ```xml INSERT INTO PLANET(POSITION, NAME, DESCRIPTION) VALUES (777, 'Pluto', :description) #[{'description' : payload}] ``` - Target Variable for the Insert operation: `result` - Target Value: `message` in Design Center, `#[message]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `Payload is: #[vars.result.payload] and attributes are: #[vars.result.attributes]` Assume that you want to log the name of the first entry in a planet database. You can define a target variable like this one through the Select operation of the Database connector: ```xml select * from PLANET order by ID ``` - Target Variable for the Select operation: `planetName` - Target Value: `payload[0].name` in Design Center, `#[payload[0].name]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `'Planet name is: ' ++ vars.planetName` ## Scenario: Using the Stored Value as Input to an Operation Assume that you want to access all planets discovered after a given planet was discovered. You might create a target variable called `discoveryDate` within a select operation to capture the a planet’s discovery date. ```xml select discoveryDate from PLANET where name = :name #[{'name' : 'pluto'}] ``` - Target Variable for the Retrieve operation: `discoveryDate` Then you can use the Input parameter of another operation in your flow (such as the Select operation to the Database connector) to make the variable available for use in your query, for example: ```xml select * from PLANET where discoveryDate > :discoveryDate #[{'discoveryDate' : vars.discoveryDate}] ``` - Input Parameter definition for the Select operation: - Key: `discoveryDate` - Value: `vars.discoveryDate` in Design Center, `#[vars.discoveryDate]` in Anypoint Studio. ## Scenario: Bypassing the Normal Message Flow Assume that you want to insert a number of records into a database that are located in the messages’s payload, then pass those same records on for further processing by the next component in your flow. Though you want to use the Bulk Insert operation to the Database connector to insert the records, the operation returns a success message that replaces the current payload, which makes the records inaccessible. So, to pass on the records to the next component instead of replacing the payload with the Bulk Insert result, you can store the success message in a target variable, for example: - Target Variable: `bulkInsertResult` Then the next operation in your flow can process the records located in the payload. ## See Also - [Testing a Processor That Stores Data in a Target Variable](https://docs.mulesoft.com/munit/latest/test-processor-that-uses-target-variable) - [Mule Events](https://docs.mulesoft.com/mule-runtime/latest/about-mule-event) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/latest/about-mule-variables) --- product: Mule Runtime version: 4.11 --- # Enterprise Integration Patterns Using Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Enterprise Integration Patterns are accepted solutions to recurring problems within a given context. The patterns provide a framework for designing, building messaging and integration systems, as well as a common language for teams to use when architecting solutions. Mule supports most of the patterns shown in the Enterprise Integration Patterns book written by Gregor Hohpe and Bobby Woolf. Mule reduces the effort required when building integrations by implementing the patterns that you use to design solutions. You can then simply configure and use these same patterns in Mule. ## Mapping Enterprise Integration Patterns into Mule Objects Review the following list of Enterprise Integration Patterns that can be mapped directly to Mule objects: ### Integration Styles
PatternMapping to a Mule Object

File Transfer

File Connector

Shared Database

DataBase Connector

Remote Procedure Invocation

Mule APIs are meant to work like this procedure or even doing requests to external APIs.

Messaging

Mule is all about Messaging.

### Messaging Systems
PatternMapping to a Mule Object

Message Channel

Mule provides a message channel that connects the message processors in a flow.

Pipes and Filters

A flow implements a pipe and filter architecture.

Message Router

Message Routers.

Message Translator

Message Transformer.

Message Endpoint

Creating Message Sources with the Mule SDK and Operations.

### Messaging Channels
PatternMapping to a Mule Object

Point-to-Point Channel

The default channel within a flow.

Message Bus

Mule is a message bus.

Guaranteed Delivery

Using Reliability Patterns.

### Message Construction
PatternMapping to a Mule Object

Event Message

Mule transmits events from different Application or Processors.

Request Reply

Mule uses connectors that facilitate request-reply wise operations, or using Reliability Patterns.

### Message Routing
PatternMapping to a Mule Object

Content-Based Router

Choice Router.

Message Filter

Validation Module.

Dynamic Routing

Message Routers.

Scatter Gather

Scatter Gather Router.

Splitter

Foreach Scope, Parape and Batch.

Aggregator

Aggregator Module.

### Message Transformation
PatternMapping to a Mule Object

Content Enricher

Target Variables.

### Messaging Endpoints
PatternMapping to a Mule Object

Polling Consumer

Creating Message Sources with the Mule SDK.

Transactional Client

Transaction Management.

Idempotent Receiver

Redelivery Policy.

--- product: Mule Runtime version: 4.12 --- # Enterprise Integration Patterns Using Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Enterprise Integration Patterns are accepted solutions to recurring problems within a given context. The patterns provide a framework for designing, building messaging and integration systems, as well as a common language for teams to use when architecting solutions. Mule supports most of the patterns shown in the Enterprise Integration Patterns book written by Gregor Hohpe and Bobby Woolf. Mule reduces the effort required when building integrations by implementing the patterns that you use to design solutions. You can then simply configure and use these same patterns in Mule. ## Mapping Enterprise Integration Patterns into Mule Objects Review the following list of Enterprise Integration Patterns that can be mapped directly to Mule objects: ### Integration Styles
PatternMapping to a Mule Object

File Transfer

File Connector

Shared Database

DataBase Connector

Remote Procedure Invocation

Mule APIs are meant to work like this procedure or even doing requests to external APIs.

Messaging

Mule is all about Messaging.

### Messaging Systems
PatternMapping to a Mule Object

Message Channel

Mule provides a message channel that connects the message processors in a flow.

Pipes and Filters

A flow implements a pipe and filter architecture.

Message Router

Message Routers.

Message Translator

Message Transformer.

Message Endpoint

Creating Message Sources with the Mule SDK and Operations.

### Messaging Channels
PatternMapping to a Mule Object

Point-to-Point Channel

The default channel within a flow.

Message Bus

Mule is a message bus.

Guaranteed Delivery

Using Reliability Patterns.

### Message Construction
PatternMapping to a Mule Object

Event Message

Mule transmits events from different Application or Processors.

Request Reply

Mule uses connectors that facilitate request-reply wise operations, or using Reliability Patterns.

### Message Routing
PatternMapping to a Mule Object

Content-Based Router

Choice Router.

Message Filter

Validation Module.

Dynamic Routing

Message Routers.

Scatter Gather

Scatter Gather Router.

Splitter

Foreach Scope, Parape and Batch.

Aggregator

Aggregator Module.

### Message Transformation
PatternMapping to a Mule Object

Content Enricher

Target Variables.

### Messaging Endpoints
PatternMapping to a Mule Object

Polling Consumer

Creating Message Sources with the Mule SDK.

Transactional Client

Transaction Management.

Idempotent Receiver

Redelivery Policy.

--- product: Mule Runtime version: 4.3 --- # Enterprise Integration Patterns Using Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Enterprise Integration Patterns are accepted solutions to recurring problems within a given context. The patterns provide a framework for designing, building messaging and integration systems, as well as a common language for teams to use when architecting solutions. Mule supports most of the patterns shown in the Enterprise Integration Patterns book written by Gregor Hohpe and Bobby Woolf. Mule reduces the effort required when building integrations by implementing the patterns that you use to design solutions. You can then simply configure and use these same patterns in Mule. ## Mapping Enterprise Integration Patterns into Mule Objects Review the following list of Enterprise Integration Patterns that can be mapped directly to Mule objects: ### Integration Styles
PatternMapping to a Mule Object

File Transfer

File Connector

Shared Database

DataBase Connector

Remote Procedure Invocation

Mule APIs are meant to work like this procedure or even doing requests to external APIs.

Messaging

Mule is all about Messaging.

### Messaging Systems
PatternMapping to a Mule Object

Message Channel

Mule provides a message channel that connects the message processors in a flow.

Pipes and Filters

A flow implements a pipe and filter architecture.

Message Router

Message Routers.

Message Translator

Message Transformer.

Message Endpoint

Message Sources and Operations.

### Messaging Channels
PatternMapping to a Mule Object

Point-to-Point Channel

The default channel within a flow.

Message Bus

Mule is a message bus.

Guaranteed Delivery

Using Reliability Patterns.

### Message Construction
PatternMapping to a Mule Object

Event Message

Mule transmits events from different Application or Processors.

Request Reply

Mule uses connectors that facilitate request-reply wise operations, or using Reliability Patterns.

### Message Routing
PatternMapping to a Mule Object

Content-Based Router

Choice Router.

Message Filter

Validation Module.

Dynamic Routing

Message Routers.

Scatter Gather

Scatter Gather Router.

Splitter

Foreach Scope, Parape and Batch.

Aggregator

Aggregator Module.

### Message Transformation
PatternMapping to a Mule Object

Content Enricher

Target Variables.

### Messaging Endpoints
PatternMapping to a Mule Object

Polling Consumer

Message Sources.

Transactional Client

Transaction Management.

Idempotent Receiver

Redelivery Policy.

--- product: Mule Runtime version: 4.4 --- # Enterprise Integration Patterns Using Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Enterprise Integration Patterns are accepted solutions to recurring problems within a given context. The patterns provide a framework for designing, building messaging and integration systems, as well as a common language for teams to use when architecting solutions. Mule supports most of the patterns shown in the Enterprise Integration Patterns book written by Gregor Hohpe and Bobby Woolf. Mule reduces the effort required when building integrations by implementing the patterns that you use to design solutions. You can then simply configure and use these same patterns in Mule. ## Mapping Enterprise Integration Patterns into Mule Objects Review the following list of Enterprise Integration Patterns that can be mapped directly to Mule objects: ### Integration Styles
PatternMapping to a Mule Object

File Transfer

File Connector

Shared Database

DataBase Connector

Remote Procedure Invocation

Mule APIs are meant to work like this procedure or even doing requests to external APIs.

Messaging

Mule is all about Messaging.

### Messaging Systems
PatternMapping to a Mule Object

Message Channel

Mule provides a message channel that connects the message processors in a flow.

Pipes and Filters

A flow implements a pipe and filter architecture.

Message Router

Message Routers.

Message Translator

Message Transformer.

Message Endpoint

Creating Message Sources with the Mule SDK and Operations.

### Messaging Channels
PatternMapping to a Mule Object

Point-to-Point Channel

The default channel within a flow.

Message Bus

Mule is a message bus.

Guaranteed Delivery

Using Reliability Patterns.

### Message Construction
PatternMapping to a Mule Object

Event Message

Mule transmits events from different Application or Processors.

Request Reply

Mule uses connectors that facilitate request-reply wise operations, or using Reliability Patterns.

### Message Routing
PatternMapping to a Mule Object

Content-Based Router

Choice Router.

Message Filter

Validation Module.

Dynamic Routing

Message Routers.

Scatter Gather

Scatter Gather Router.

Splitter

Foreach Scope, Parape and Batch.

Aggregator

Aggregator Module.

### Message Transformation
PatternMapping to a Mule Object

Content Enricher

Target Variables.

### Messaging Endpoints
PatternMapping to a Mule Object

Polling Consumer

Creating Message Sources with the Mule SDK.

Transactional Client

Transaction Management.

Idempotent Receiver

Redelivery Policy.

--- product: Mule Runtime version: 4.6 --- # Enterprise Integration Patterns Using Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Enterprise Integration Patterns are accepted solutions to recurring problems within a given context. The patterns provide a framework for designing, building messaging and integration systems, as well as a common language for teams to use when architecting solutions. Mule supports most of the patterns shown in the Enterprise Integration Patterns book written by Gregor Hohpe and Bobby Woolf. Mule reduces the effort required when building integrations by implementing the patterns that you use to design solutions. You can then simply configure and use these same patterns in Mule. ## Mapping Enterprise Integration Patterns into Mule Objects Review the following list of Enterprise Integration Patterns that can be mapped directly to Mule objects: ### Integration Styles
PatternMapping to a Mule Object

File Transfer

File Connector

Shared Database

DataBase Connector

Remote Procedure Invocation

Mule APIs are meant to work like this procedure or even doing requests to external APIs.

Messaging

Mule is all about Messaging.

### Messaging Systems
PatternMapping to a Mule Object

Message Channel

Mule provides a message channel that connects the message processors in a flow.

Pipes and Filters

A flow implements a pipe and filter architecture.

Message Router

Message Routers.

Message Translator

Message Transformer.

Message Endpoint

Creating Message Sources with the Mule SDK and Operations.

### Messaging Channels
PatternMapping to a Mule Object

Point-to-Point Channel

The default channel within a flow.

Message Bus

Mule is a message bus.

Guaranteed Delivery

Using Reliability Patterns.

### Message Construction
PatternMapping to a Mule Object

Event Message

Mule transmits events from different Application or Processors.

Request Reply

Mule uses connectors that facilitate request-reply wise operations, or using Reliability Patterns.

### Message Routing
PatternMapping to a Mule Object

Content-Based Router

Choice Router.

Message Filter

Validation Module.

Dynamic Routing

Message Routers.

Scatter Gather

Scatter Gather Router.

Splitter

Foreach Scope, Parape and Batch.

Aggregator

Aggregator Module.

### Message Transformation
PatternMapping to a Mule Object

Content Enricher

Target Variables.

### Messaging Endpoints
PatternMapping to a Mule Object

Polling Consumer

Creating Message Sources with the Mule SDK.

Transactional Client

Transaction Management.

Idempotent Receiver

Redelivery Policy.

--- product: Mule Runtime version: 4.9 --- # Enterprise Integration Patterns Using Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Enterprise Integration Patterns are accepted solutions to recurring problems within a given context. The patterns provide a framework for designing, building messaging and integration systems, as well as a common language for teams to use when architecting solutions. Mule supports most of the patterns shown in the Enterprise Integration Patterns book written by Gregor Hohpe and Bobby Woolf. Mule reduces the effort required when building integrations by implementing the patterns that you use to design solutions. You can then simply configure and use these same patterns in Mule. ## Mapping Enterprise Integration Patterns into Mule Objects Review the following list of Enterprise Integration Patterns that can be mapped directly to Mule objects: ### Integration Styles
PatternMapping to a Mule Object

File Transfer

File Connector

Shared Database

DataBase Connector

Remote Procedure Invocation

Mule APIs are meant to work like this procedure or even doing requests to external APIs.

Messaging

Mule is all about Messaging.

### Messaging Systems
PatternMapping to a Mule Object

Message Channel

Mule provides a message channel that connects the message processors in a flow.

Pipes and Filters

A flow implements a pipe and filter architecture.

Message Router

Message Routers.

Message Translator

Message Transformer.

Message Endpoint

Creating Message Sources with the Mule SDK and Operations.

### Messaging Channels
PatternMapping to a Mule Object

Point-to-Point Channel

The default channel within a flow.

Message Bus

Mule is a message bus.

Guaranteed Delivery

Using Reliability Patterns.

### Message Construction
PatternMapping to a Mule Object

Event Message

Mule transmits events from different Application or Processors.

Request Reply

Mule uses connectors that facilitate request-reply wise operations, or using Reliability Patterns.

### Message Routing
PatternMapping to a Mule Object

Content-Based Router

Choice Router.

Message Filter

Validation Module.

Dynamic Routing

Message Routers.

Scatter Gather

Scatter Gather Router.

Splitter

Foreach Scope, Parape and Batch.

Aggregator

Aggregator Module.

### Message Transformation
PatternMapping to a Mule Object

Content Enricher

Target Variables.

### Messaging Endpoints
PatternMapping to a Mule Object

Polling Consumer

Creating Message Sources with the Mule SDK.

Transactional Client

Transaction Management.

Idempotent Receiver

Redelivery Policy.

--- product: Mule Runtime version: 4.13 is-latest-version: true --- # Enterprise Integration Patterns Using Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Enterprise Integration Patterns are accepted solutions to recurring problems within a given context. The patterns provide a framework for designing, building messaging and integration systems, as well as a common language for teams to use when architecting solutions. Mule supports most of the patterns shown in the Enterprise Integration Patterns book written by Gregor Hohpe and Bobby Woolf. Mule reduces the effort required when building integrations by implementing the patterns that you use to design solutions. You can then simply configure and use these same patterns in Mule. ## Mapping Enterprise Integration Patterns into Mule Objects Review the following list of Enterprise Integration Patterns that can be mapped directly to Mule objects: ### Integration Styles
PatternMapping to a Mule Object

File Transfer

File Connector

Shared Database

DataBase Connector

Remote Procedure Invocation

Mule APIs are meant to work like this procedure or even doing requests to external APIs.

Messaging

Mule is all about Messaging.

### Messaging Systems
PatternMapping to a Mule Object

Message Channel

Mule provides a message channel that connects the message processors in a flow.

Pipes and Filters

A flow implements a pipe and filter architecture.

Message Router

Message Routers.

Message Translator

Message Transformer.

Message Endpoint

Creating Message Sources with the Mule SDK and Operations.

### Messaging Channels
PatternMapping to a Mule Object

Point-to-Point Channel

The default channel within a flow.

Message Bus

Mule is a message bus.

Guaranteed Delivery

Using Reliability Patterns.

### Message Construction
PatternMapping to a Mule Object

Event Message

Mule transmits events from different Application or Processors.

Request Reply

Mule uses connectors that facilitate request-reply wise operations, or using Reliability Patterns.

### Message Routing
PatternMapping to a Mule Object

Content-Based Router

Choice Router.

Message Filter

Validation Module.

Dynamic Routing

Message Routers.

Scatter Gather

Scatter Gather Router.

Splitter

Foreach Scope, Parape and Batch.

Aggregator

Aggregator Module.

### Message Transformation
PatternMapping to a Mule Object

Content Enricher

Target Variables.

### Messaging Endpoints
PatternMapping to a Mule Object

Polling Consumer

Creating Message Sources with the Mule SDK.

Transactional Client

Transaction Management.

Idempotent Receiver

Redelivery Policy.

--- product: Mule Runtime version: 4.11 keywords: error handling, exceptions, exception catching, exceptions --- # Error Handlers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Errors that occur in Mule belong to one of two major categories: - [System Errors](#system_errors) - [Messaging Errors](#messaging_errors) ## System Errors Mule throws a system error when an exception occurs at the system level and no Mule event is involved. A system error handler manages exceptions that occur: - During application startup. - When a connection to an external system fails. When a system error occurs, Mule sends an error notification to registered listeners, logs the error, and if the error is caused by a connection failure, executes a reconnection strategy. System error handlers are not configurable in Mule. ## Messaging Errors Mule throws a messaging error (a [Mule error](https://docs.mulesoft.com/mule-runtime/4.11/mule-error-concept)) whenever a problem occurs within a flow of a Mule app, where Mule events and the messages they contain are processed. You can handle Mule messaging errors in more than one way: - You can rely on the [default error handling](#default_error_handling) mechanism. - Within a flow, you can set up [On-Error components](https://docs.mulesoft.com/mule-runtime/4.11/on-error-scope-concept) (On Error Continue and On Error Propagate) inside the flow’s built-in Error Handler component. These components can contain any number of components to process the error. The following figure shows what happens when an event processor, such as an HTTP request or database operation, throws an error: ![A flow showing multiple event processors and an Error Handling component](/mulesoft/current/en-us/mule-runtime/4.11/_images/error-handling-39be7.png) - Outside a flow, you can set up an [Error Handler](#global_error_handler) component and reference it from other Error Handler configurations. The global Error Handler can also contain On-Error components and their contents. - It is also possible to set up error handling from within a [Try scope](https://docs.mulesoft.com/mule-runtime/4.11/try-scope-concept) that resides in a flow. The scope contains a built-in Error Handler in which you can configure On-Error components and their contents. ### Using Default Error Handling for Messages By default, unhandled messaging errors are logged and propagated. When a flow is processing a Mule message that raises an error, the normal execution of the flow stops, and the process transfers to the flow’s default error handler, which propagates the error. The following example shows a simple Mule app configuration that relies on default error handling instead of using explicitly configured error handling components to manage the error. ![An error message display from an HTTP request failure in a Mule application](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-error-handling-default.png) The XML for the default error handling example looks like this: ```xml ``` After you start a Mule app with this configuration and trigger the HTTP listener by loading `[http://0.0.0.0:8081/users](http://0.0.0.0:8081/users)` (for example, into a browser), the flow makes an HTTP request (`http://jsonplaceholder.typicode.com:80/somebadrequest`) for a file that does not exist. As a result, the Anypoint Studio console logs and propagates the error to the web browser. - Anypoint Studio Console Log The Studio console prints an error message. The message indicates that the default handler, `OnErrorPropagateHandler`, propagates a 404 error returned from the HTTP GET request. Mule identifies this error as HTTP:NOT\_FOUND. ```txt ERROR 2021-01-19 18:48:50,392 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-example/processors/0; event: 1d3baf11-5aa0-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request) Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-example(error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request)) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ``` The error logs in the Studio console present the following information: - **Message**: Description of the error - **Element**: XML element that failed execution and caused the error - **Element DSL**: XML element that failed execution and caused the error, expressed in DSL - **Error type**: Type of Mule error raised by the Mule app - **Flowstack**: Flowstack trace error log This field lists an entry for each flow that processed the Mule event and the processor that sent the event to the next flow. The last entry shows the flow and the processor that failed during the processing of the event. Starting with Mule 4.3.0, the Flowstack entry is enabled by default. You can disable Flowstack logging by setting the `mule.flowTrace` configuration property to `false`. - Error Propagation to the Web Browser A description of the HTTP:NOT\_FOUND error appears in the browser tab you use to trigger the listener: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` This Mule error description appears in the browser for two reasons: - The default error handler uses an On Error Propagate process (`OnErrorPropagateHandler`). The On Error Propagate component causes the flow to fail and the HTTP listener to prepare an error response for the `404` error associated with the file not found. - The HTTP listener is using default error (`error.description`) and success (`payload`) responses to return the message body. Because no custom responses are configured, the browser shows the description of the error. ### Using On-Error Components to Handle Messaging Errors Instead of relying on the default error-handling mechanism, you can use [On-Error components](https://docs.mulesoft.com/mule-runtime/4.11/on-error-scope-concept) (On Error Continue and On Error Propagate) inside a built-in or external Error Handler component. The following example shows a simple flow that is configured in Studio to return the results of an HTTP request when the HTTP listener is triggered. Unlike the [default error-handling example](#default_error_handling), this example configures On Error Continue (`on-error-continue`) inside the flow’s built-in Error Handler (`error-handler`) component, and On Error Continue contains a Logger that writes a description of the error. ![A flow showing error handling configurations with components like Listener, Request, and Logger](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-on-error-continue.png) The XML for the example looks like this: ```xml ``` As in the default error-handling example, the requested page is not found, so the flow returns a 404 error that Mule identifies as an HTTP:NOT\_FOUND error. However, in this case, the tab of the browser used to trigger the HTTP listener is blank because the error is not propagated. With On Error Continue, the flow in the example is treated as though it ends successfully with a 200 for the GET request, even though the page is not found. The HTTP listener executes the behavior for the default success response (returning `payload` content as the message body). Because the page was not found, there is no content to display in the browser, so the browser tab is blank. The Studio console also prints an error message (the first ERROR message below) indicating that `OnErrorContinueHandler` is handling the error, and it prints an ERROR message from the logger (the second ERROR below) that describes the Mule error (an `error.description`, see [Selector Expressions for Mule Errors](https://docs.mulesoft.com/mule-runtime/4.11/mule-error-concept#selector_expressions)). ```txt ERROR 2021-01-19 18:42:04,583 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorContinueHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15 Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-normalFlow(error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ERROR 2021-01-19 18:42:04,586 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/errorHandler/0/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` If you instead create the same Mule app using On Error Propagate (`on-error-propagate`) instead of On Error Continue (`on-error-continue`), you receive the same error messages in the Studio console, but you also see the logged error message in your browser. This behavior is identical to the default error handling behavior because both use On Error Propagate. Note that within each On-Error component, the error path you define can incorporate any number of event processors to handle specific error types as precisely as you want. You can select specific Mule errors for the On-Error component to handle. The Error Handler component routes an error to the first On-Error component that matches the error. For more information about On Error Continue and On Error Propagate, see [On-Error components](https://docs.mulesoft.com/mule-runtime/4.11/on-error-scope-concept). ### Referencing a Global Error Handler A global error handler can be useful if you want more than one flow or Try scope to handle errors in the same way. You can create reuse configurations by providing a reference to an error handler: - [Setting a Global Error-Handling Configuration](#global_error_config_set) - [Referencing an Error-Handling Configuration from a Flow](#global_error_config_ref) #### Setting a Global Error-Handling Configuration The following XML configuration defines a default error-handling configuration that uses `` to reference the `` configuration. ```xml ``` In the Studio UI, the global error-handling example looks like this: ![A global error-handler configuration](/mulesoft/current/en-us/mule-runtime/4.11/_images/error-handlers-global.png) The example includes two main components for handling errors, an Error Handler (`error-handler`) with embedded components that are visible in the Studio canvas and a global error-handling configuration, which is not visible in the canvas. The flow (**someFlow**) in the UI example illustrates that the Error Handler component lies outside any flow in the Mule app. Because the request produces an HTTP:NOT\_FOUND error, the Studio console prints an error message indicating that `OnErrorContinueHandler` is handling the error. On Error Continue configurations do not propagate the errors they handle (see [Using On-Error Components to Handle Messaging Errors](#on_error_continue)). To set up the global error-handling example through the Studio UI instead of writing the configuration in XML markup: 1. Drag the Error Handler component from the **Mule Palette** to the Studio canvas, and name it **allErrorHandler**. Notice that the component is not part of any flow. 2. Drag the On Error Continue component into the Error Handler component. 3. Drag a Set Payload component into the On Error Continue component. Note that the Set Payload component is an example. You can use other components, such as a Logger, and you can write your own error message inside that component. The Set Payload example uses a Mule variable for the error description (see the `error` variable in [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) for details). 4. Create a global error-handling reference in Studio: 1. Click **Global Elements** to open **Global Configuration Elements**. **Global Elements** is located below the Studio canvas. 2. In **Global Configuration Elements**, click **Create** to open the **Choose Global Type** dialog. ![A configuration panel for choosing a global element type including configuration](/mulesoft/current/en-us/mule-runtime/4.11/_images/error-handling-global-type.png) 3. From the dialog, select **Global Configuration** -→ **Configuration**, and then click **OK** to open the **Configuration** dialog. ![A configuration dialog general fields including settings](/mulesoft/current/en-us/mule-runtime/4.11/_images/error-handling-global-config.png) 4. From the select **Configuration** dialog, select **allErrorHandler** for the **Default Error Handler** field, and click **OK**. 5. Set up the HTTP listener and HTTP request components using the values described in the XML. 6. Check that the XML configuration looks correct by clicking **Configuration XML** (located below the Studio canvas). ### Referencing an Error-Handling Configuration from a Flow > [!NOTE] The configuration of some elements in these examples is XML-only. A flow can reference a global error handler that resides outside the flow. The flow logs all its errors through a reference. Example: XML Configuration for the App ```xml ``` In this XML example, the global error handler is configured through an `` element named `loggingErrorHandler`. The flow references the error handler with ``. To reference a global error handler configuration from a flow in Studio: 1. From Studio, drag an **Error Handler** component from the **Mule Palette** to the canvas, and configure it components through the UI. 2. In the Mule app, click **Configuration XML** (located below the Studio canvas). 3. (XML-only configuration) Within your `` element, type the XML for the reference, for example, ``. The following example references a global On Error Continue element (``) using `` within an `` element. Both require manual configuration through the **Configuration XML**, rather than the UI. ```xml ``` ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.11/mule-error-concept) - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.11/on-error-scope-concept) - [Try Scope](https://docs.mulesoft.com/mule-runtime/4.11/try-scope-concept) - [Raise Error Component](https://docs.mulesoft.com/mule-runtime/4.11/raise-error-component-reference) --- product: Mule Runtime version: 4.12 keywords: error handling, exceptions, exception catching, exceptions --- # Error Handlers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Errors that occur in Mule belong to one of two major categories: - [System Errors](#system_errors) - [Messaging Errors](#messaging_errors) ## System Errors Mule throws a system error when an exception occurs at the system level and no Mule event is involved. A system error handler manages exceptions that occur: - During application startup. - When a connection to an external system fails. When a system error occurs, Mule sends an error notification to registered listeners, logs the error, and if the error is caused by a connection failure, executes a reconnection strategy. System error handlers are not configurable in Mule. ## Messaging Errors Mule throws a messaging error (a [Mule error](https://docs.mulesoft.com/mule-runtime/4.12/mule-error-concept)) whenever a problem occurs within a flow of a Mule app, where Mule events and the messages they contain are processed. You can handle Mule messaging errors in more than one way: - You can rely on the [default error handling](#default_error_handling) mechanism. - Within a flow, you can set up [On-Error components](https://docs.mulesoft.com/mule-runtime/4.12/on-error-scope-concept) (On Error Continue and On Error Propagate) inside the flow’s built-in Error Handler component. These components can contain any number of components to process the error. The following figure shows what happens when an event processor, such as an HTTP request or database operation, throws an error: ![A flow showing multiple event processors and an Error Handling component](/mulesoft/current/en-us/mule-runtime/4.12/_images/error-handling-39be7.png) - Outside a flow, you can set up an [Error Handler](#global_error_handler) component and reference it from other Error Handler configurations. The global Error Handler can also contain On-Error components and their contents. - It is also possible to set up error handling from within a [Try scope](https://docs.mulesoft.com/mule-runtime/4.12/try-scope-concept) that resides in a flow. The scope contains a built-in Error Handler in which you can configure On-Error components and their contents. ### Using Default Error Handling for Messages By default, unhandled messaging errors are logged and propagated. When a flow is processing a Mule message that raises an error, the normal execution of the flow stops, and the process transfers to the flow’s default error handler, which propagates the error. The following example shows a simple Mule app configuration that relies on default error handling instead of using explicitly configured error handling components to manage the error. ![An error message display from an HTTP request failure in a Mule application](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-error-handling-default.png) The XML for the default error handling example looks like this: ```xml ``` After you start a Mule app with this configuration and trigger the HTTP listener by loading `[http://0.0.0.0:8081/users](http://0.0.0.0:8081/users)` (for example, into a browser), the flow makes an HTTP request (`http://jsonplaceholder.typicode.com:80/somebadrequest`) for a file that does not exist. As a result, the Anypoint Studio console logs and propagates the error to the web browser. - Anypoint Studio Console Log The Studio console prints an error message. The message indicates that the default handler, `OnErrorPropagateHandler`, propagates a 404 error returned from the HTTP GET request. Mule identifies this error as HTTP:NOT\_FOUND. ```txt ERROR 2021-01-19 18:48:50,392 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-example/processors/0; event: 1d3baf11-5aa0-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request) Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-example(error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request)) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ``` The error logs in the Studio console present the following information: - **Message**: Description of the error - **Element**: XML element that failed execution and caused the error - **Element DSL**: XML element that failed execution and caused the error, expressed in DSL - **Error type**: Type of Mule error raised by the Mule app - **Flowstack**: Flowstack trace error log This field lists an entry for each flow that processed the Mule event and the processor that sent the event to the next flow. The last entry shows the flow and the processor that failed during the processing of the event. Starting with Mule 4.3.0, the Flowstack entry is enabled by default. You can disable Flowstack logging by setting the `mule.flowTrace` configuration property to `false`. - Error Propagation to the Web Browser A description of the HTTP:NOT\_FOUND error appears in the browser tab you use to trigger the listener: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` This Mule error description appears in the browser for two reasons: - The default error handler uses an On Error Propagate process (`OnErrorPropagateHandler`). The On Error Propagate component causes the flow to fail and the HTTP listener to prepare an error response for the `404` error associated with the file not found. - The HTTP listener is using default error (`error.description`) and success (`payload`) responses to return the message body. Because no custom responses are configured, the browser shows the description of the error. ### Using On-Error Components to Handle Messaging Errors Instead of relying on the default error-handling mechanism, you can use [On-Error components](https://docs.mulesoft.com/mule-runtime/4.12/on-error-scope-concept) (On Error Continue and On Error Propagate) inside a built-in or external Error Handler component. The following example shows a simple flow that is configured in Studio to return the results of an HTTP request when the HTTP listener is triggered. Unlike the [default error-handling example](#default_error_handling), this example configures On Error Continue (`on-error-continue`) inside the flow’s built-in Error Handler (`error-handler`) component, and On Error Continue contains a Logger that writes a description of the error. ![A flow showing error handling configurations with components like Listener, Request, and Logger](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-on-error-continue.png) The XML for the example looks like this: ```xml ``` As in the default error-handling example, the requested page is not found, so the flow returns a 404 error that Mule identifies as an HTTP:NOT\_FOUND error. However, in this case, the tab of the browser used to trigger the HTTP listener is blank because the error is not propagated. With On Error Continue, the flow in the example is treated as though it ends successfully with a 200 for the GET request, even though the page is not found. The HTTP listener executes the behavior for the default success response (returning `payload` content as the message body). Because the page was not found, there is no content to display in the browser, so the browser tab is blank. The Studio console also prints an error message (the first ERROR message below) indicating that `OnErrorContinueHandler` is handling the error, and it prints an ERROR message from the logger (the second ERROR below) that describes the Mule error (an `error.description`, see [Selector Expressions for Mule Errors](https://docs.mulesoft.com/mule-runtime/4.12/mule-error-concept#selector_expressions)). ```txt ERROR 2021-01-19 18:42:04,583 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorContinueHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15 Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-normalFlow(error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ERROR 2021-01-19 18:42:04,586 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/errorHandler/0/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` If you instead create the same Mule app using On Error Propagate (`on-error-propagate`) instead of On Error Continue (`on-error-continue`), you receive the same error messages in the Studio console, but you also see the logged error message in your browser. This behavior is identical to the default error handling behavior because both use On Error Propagate. Note that within each On-Error component, the error path you define can incorporate any number of event processors to handle specific error types as precisely as you want. You can select specific Mule errors for the On-Error component to handle. The Error Handler component routes an error to the first On-Error component that matches the error. For more information about On Error Continue and On Error Propagate, see [On-Error components](https://docs.mulesoft.com/mule-runtime/4.12/on-error-scope-concept). ### Referencing a Global Error Handler A global error handler can be useful if you want more than one flow or Try scope to handle errors in the same way. You can create reuse configurations by providing a reference to an error handler: - [Setting a Global Error-Handling Configuration](#global_error_config_set) - [Referencing an Error-Handling Configuration from a Flow](#global_error_config_ref) #### Setting a Global Error-Handling Configuration The following XML configuration defines a default error-handling configuration that uses `` to reference the `` configuration. ```xml ``` In the Studio UI, the global error-handling example looks like this: ![A global error-handler configuration](/mulesoft/current/en-us/mule-runtime/4.12/_images/error-handlers-global.png) The example includes two main components for handling errors, an Error Handler (`error-handler`) with embedded components that are visible in the Studio canvas and a global error-handling configuration, which is not visible in the canvas. The flow (**someFlow**) in the UI example illustrates that the Error Handler component lies outside any flow in the Mule app. Because the request produces an HTTP:NOT\_FOUND error, the Studio console prints an error message indicating that `OnErrorContinueHandler` is handling the error. On Error Continue configurations do not propagate the errors they handle (see [Using On-Error Components to Handle Messaging Errors](#on_error_continue)). To set up the global error-handling example through the Studio UI instead of writing the configuration in XML markup: 1. Drag the Error Handler component from the **Mule Palette** to the Studio canvas, and name it **allErrorHandler**. Notice that the component is not part of any flow. 2. Drag the On Error Continue component into the Error Handler component. 3. Drag a Set Payload component into the On Error Continue component. Note that the Set Payload component is an example. You can use other components, such as a Logger, and you can write your own error message inside that component. The Set Payload example uses a Mule variable for the error description (see the `error` variable in [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) for details). 4. Create a global error-handling reference in Studio: 1. Click **Global Elements** to open **Global Configuration Elements**. **Global Elements** is located below the Studio canvas. 2. In **Global Configuration Elements**, click **Create** to open the **Choose Global Type** dialog. ![A configuration panel for choosing a global element type including configuration](/mulesoft/current/en-us/mule-runtime/4.12/_images/error-handling-global-type.png) 3. From the dialog, select **Global Configuration** -→ **Configuration**, and then click **OK** to open the **Configuration** dialog. ![A configuration dialog general fields including settings](/mulesoft/current/en-us/mule-runtime/4.12/_images/error-handling-global-config.png) 4. From the select **Configuration** dialog, select **allErrorHandler** for the **Default Error Handler** field, and click **OK**. 5. Set up the HTTP listener and HTTP request components using the values described in the XML. 6. Check that the XML configuration looks correct by clicking **Configuration XML** (located below the Studio canvas). ### Referencing an Error-Handling Configuration from a Flow > [!NOTE] The configuration of some elements in these examples is XML-only. A flow can reference a global error handler that resides outside the flow. The flow logs all its errors through a reference. Example: XML Configuration for the App ```xml ``` In this XML example, the global error handler is configured through an `` element named `loggingErrorHandler`. The flow references the error handler with ``. To reference a global error handler configuration from a flow in Studio: 1. From Studio, drag an **Error Handler** component from the **Mule Palette** to the canvas, and configure it components through the UI. 2. In the Mule app, click **Configuration XML** (located below the Studio canvas). 3. (XML-only configuration) Within your `` element, type the XML for the reference, for example, ``. The following example references a global On Error Continue element (``) using `` within an `` element. Both require manual configuration through the **Configuration XML**, rather than the UI. ```xml ``` ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.12/mule-error-concept) - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.12/on-error-scope-concept) - [Try Scope](https://docs.mulesoft.com/mule-runtime/4.12/try-scope-concept) - [Raise Error Component](https://docs.mulesoft.com/mule-runtime/4.12/raise-error-component-reference) --- product: Mule Runtime version: 4.3 keywords: error handling, exceptions, exception catching, exceptions --- # Error Handlers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Errors that occur in Mule belong to one of two major categories: - [System Errors](#system_errors) - [Messaging Errors](#messaging_errors) ## System Errors Mule throws a system error when an exception occurs at the system level and no Mule event is involved. A system error handler manages exceptions that occur: - During application startup. - When a connection to an external system fails. When a system error occurs, Mule sends an error notification to registered listeners, logs the error, and if the error is caused by a connection failure, executes a reconnection strategy. System error handlers are not configurable in Mule. ## Messaging Errors Mule throws a messaging error (a [Mule error](https://docs.mulesoft.com/mule-runtime/4.3/mule-error-concept)) whenever a problem occurs within a flow of a Mule app, where Mule events and the messages they contain are processed. You can handle Mule messaging errors in more than one way: - You can rely on the [default error handling](#default_error_handling) mechanism. - Within a flow, you can set up [On-Error components](https://docs.mulesoft.com/mule-runtime/4.3/on-error-scope-concept) (On Error Continue and On Error Propagate) inside the flow’s built-in Error Handler component. These components can contain any number of components to process the error. The following figure shows what happens when an event processor, such as an HTTP request or database operation, throws an error: ![error handling 39be7](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-handling-39be7.png) - Outside a flow, you can set up an [Error Handler](#global_error_handler) component and reference it from other Error Handler configurations. The global Error Handler can also contain On-Error components and their contents. - It is also possible to set up error handling from within a [Try scope](https://docs.mulesoft.com/mule-runtime/4.3/try-scope-concept) that resides in a flow. The scope contains a built-in Error Handler in which you can configure On-Error components and their contents. ### Using Default Error Handling for Messages By default, unhandled messaging errors are logged and propagated. When a flow is processing a Mule message that raises an error, the normal execution of the flow stops, and the process transfers to the flow’s default error handler, which propagates the error. The following example shows a simple Mule app configuration that relies on default error handling instead of using explicitly configured error handling components to manage the error. ![Default error handling messages](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-error-handling-default.png) The XML for the default error handling example looks like this: ```xml ``` After you start a Mule app with this configuration and trigger the HTTP listener by loading `[http://0.0.0.0:8081/users](http://0.0.0.0:8081/users)` (for example, into a browser), the flow makes an HTTP request (`http://jsonplaceholder.typicode.com:80/somebadrequest`) for a file that does not exist. As a result, the Anypoint Studio console logs and propagates the error to the web browser. - Anypoint Studio Console Log The Studio console prints an error message. The message indicates that the default handler, `OnErrorPropagateHandler`, propagates a 404 error returned from the HTTP GET request. Mule identifies this error as HTTP:NOT\_FOUND. ```txt ERROR 2021-01-19 18:48:50,392 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-example/processors/0; event: 1d3baf11-5aa0-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request) Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-example(error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request)) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ``` The error logs in the Studio console present the following information: - **Message**: Description of the error - **Element**: XML element that failed execution and caused the error - **Element DSL**: XML element that failed execution and caused the error, expressed in DSL - **Error type**: Type of Mule error raised by the Mule app - **Flowstack**: Flowstack trace error log This field lists an entry for each flow that processed the Mule event and the processor that sent the event to the next flow. The last entry shows the flow and the processor that failed during the processing of the event. Starting with Mule 4.3.0, the Flowstack entry is enabled by default. You can disable Flowstack logging by setting the `mule.flowTrace` configuration property to `false`. - Error Propagation to the Web Browser A description of the HTTP:NOT\_FOUND error appears in the browser tab you use to trigger the listener: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` This Mule error description appears in the browser for two reasons: - The default error handler uses an On Error Propagate process (`OnErrorPropagateHandler`). The On Error Propagate component causes the flow to fail and the HTTP listener to prepare an error response for the `404` error associated with the file not found. - The HTTP listener is using default error (`error.description`) and success (`payload`) responses to return the message body. Because no custom responses are configured, the browser shows the description of the error. ### Using On-Error Components to Handle Messaging Errors Instead of relying on the default error-handling mechanism, you can use [On-Error components](https://docs.mulesoft.com/mule-runtime/4.3/on-error-scope-concept) (On Error Continue and On Error Propagate) inside a built-in or external Error Handler component. The following example shows a simple flow that is configured in Studio to return the results of an HTTP request when the HTTP listener is triggered. Unlike the [default error-handling example](#default_error_handling), this example configures On Error Continue (`on-error-continue`) inside the flow’s built-in Error Handler (`error-handler`) component, and On Error Continue contains a Logger that writes a description of the error. ![mruntime on error continue](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-on-error-continue.png) The XML for the example looks like this: ```xml ``` As in the default error-handling example, the requested page is not found, so the flow returns a 404 error that Mule identifies as an HTTP:NOT\_FOUND error. However, in this case, the tab of the browser used to trigger the HTTP listener is blank because the error is not propagated. With On Error Continue, the flow in the example is treated as though it ends successfully with a 200 for the GET request, even though the page is not found. The HTTP listener executes the behavior for the default success response (returning `payload` content as the message body). Because the page was not found, there is no content to display in the browser, so the browser tab is blank. The Studio console also prints an error message (the first ERROR message below) indicating that `OnErrorContinueHandler` is handling the error, and it prints an ERROR message from the logger (the second ERROR below) that describes the Mule error (an `error.description`, see [Selector Expressions for Mule Errors](https://docs.mulesoft.com/mule-runtime/4.3/mule-error-concept#selector_expressions)). ```txt ERROR 2021-01-19 18:42:04,583 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorContinueHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15 Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-normalFlow(error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ERROR 2021-01-19 18:42:04,586 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/errorHandler/0/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` If you instead create the same Mule app using On Error Propagate (`on-error-propagate`) instead of On Error Continue (`on-error-continue`), you receive the same error messages in the Studio console, but you also see the logged error message in your browser. This behavior is identical to the default error handling behavior because both use On Error Propagate. Note that within each On-Error component, the error path you define can incorporate any number of event processors to handle specific error types as precisely as you want. You can select specific Mule errors for the On-Error component to handle. The Error Handler component routes an error to the first On-Error component that matches the error. For more complex error handling configurations at the flow level, see [Introduction to Mule 4: Error Handlers](https://docs.mulesoft.com/mule-runtime/4.3/intro-error-handlers). For more information about On Error Continue and On Error Propagate, see [On-Error components](https://docs.mulesoft.com/mule-runtime/4.3/on-error-scope-concept). ### Referencing a Global Error Handler A global error handler can be useful if you want more than one flow or Try scope to handle errors in the same way. You can create reuse configurations by providing a reference to an error handler: - [Setting a Global Error-Handling Configuration](#global_error_config_set) - [Referencing an Error-Handling Configuration from a Flow](#global_error_config_ref) #### Setting a Global Error-Handling Configuration The following XML configuration defines a default error-handling configuration that uses `` to reference the `` configuration. ```xml ``` In the Studio UI, the global error-handling example looks like this: ![error handlers global](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-handlers-global.png) The example includes two main components for handling errors, an Error Handler (`error-handler`) with embedded components that are visible in the Studio canvas and a global error-handling configuration, which is not visible in the canvas. The flow (**someFlow**) in the UI example illustrates that the Error Handler component lies outside any flow in the Mule app. Because the request produces an HTTP:NOT\_FOUND error, the Studio console prints an error message indicating that `OnErrorContinueHandler` is handling the error. On Error Continue configurations do not propagate the errors they handle (see [Using On-Error Components to Handle Messaging Errors](#on_error_continue)). To set up the global error-handling example through the Studio UI instead of writing the configuration in XML markup: 1. Drag the Error Handler component from the **Mule Palette** to the Studio canvas, and name it **allErrorHandler**. Notice that the component is not part of any flow. 2. Drag the On Error Continue component into the Error Handler component. 3. Drag a Set Payload component into the On Error Continue component. Note that the Set Payload component is an example. You can use other components, such as a Logger, and you can write your own error message inside that component. The Set Payload example uses a Mule variable for the error description (see the `error` variable in [Predefined Variables](https://docs.mulesoft.com/dataweave/2.3/dataweave-variables-context) for details). 4. Create a global error-handling reference in Studio: 1. Click **Global Elements** to open **Global Configuration Elements**. **Global Elements** is located below the Studio canvas. 2. In **Global Configuration Elements**, click **Create** to open the **Choose Global Type** dialog. ![error handling global type](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-handling-global-type.png) 3. From the dialog, select **Global Configuration** -→ **Configuration**, and then click **OK** to open the **Configuration** dialog. ![error handling global config](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-handling-global-config.png) 4. From the select **Configuration** dialog, select **allErrorHandler** for the **Default Error Handler** field, and click **OK**. 5. Set up the HTTP listener and HTTP request components using the values described in the XML. 6. Check that the XML configuration looks correct by clicking **Configuration XML** (located below the Studio canvas). ### Referencing an Error-Handling Configuration from a Flow > [!NOTE] The configuration of some elements in these examples is XML-only. A flow can reference a global error handler that resides outside the flow. The flow logs all its errors through a reference. Example: XML Configuration for the App ```xml ``` In this XML example, the global error handler is configured through an `` element named `loggingErrorHandler`. The flow references the error handler with ``. To reference a global error handler configuration from a flow in Studio: 1. From Studio, drag an **Error Handler** component from the **Mule Palette** to the canvas, and configure it components through the UI. 2. In the Mule app, click **Configuration XML** (located below the Studio canvas). 3. (XML-only configuration) Within your `` element, type the XML for the reference, for example, ``. The following example references a global On Error Continue element (``) using `` within an `` element. Both require manual configuration through the **Configuration XML**, rather than the UI. ```xml ``` ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.3/mule-error-concept) - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.3/on-error-scope-concept) - [Try Scope](https://docs.mulesoft.com/mule-runtime/4.3/try-scope-concept) - [Raise Error Component](https://docs.mulesoft.com/mule-runtime/4.3/raise-error-component-reference) - [Introduction to Mule 4: Error Handlers](https://docs.mulesoft.com/mule-runtime/4.3/intro-error-handlers) - [Migrating Exception Strategies to Mule Error Handlers](https://docs.mulesoft.com/mule-runtime/4.3/migration-core-exception-strategies) --- product: Mule Runtime version: 4.4 keywords: error handling, exceptions, exception catching, exceptions --- # Error Handlers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Errors that occur in Mule belong to one of two major categories: - [System Errors](#system_errors) - [Messaging Errors](#messaging_errors) ## System Errors Mule throws a system error when an exception occurs at the system level and no Mule event is involved. A system error handler manages exceptions that occur: - During application startup. - When a connection to an external system fails. When a system error occurs, Mule sends an error notification to registered listeners, logs the error, and if the error is caused by a connection failure, executes a reconnection strategy. System error handlers are not configurable in Mule. ## Messaging Errors Mule throws a messaging error (a [Mule error](https://docs.mulesoft.com/mule-runtime/4.4/mule-error-concept)) whenever a problem occurs within a flow of a Mule app, where Mule events and the messages they contain are processed. You can handle Mule messaging errors in more than one way: - You can rely on the [default error handling](#default_error_handling) mechanism. - Within a flow, you can set up [On-Error components](https://docs.mulesoft.com/mule-runtime/4.4/on-error-scope-concept) (On Error Continue and On Error Propagate) inside the flow’s built-in Error Handler component. These components can contain any number of components to process the error. The following figure shows what happens when an event processor, such as an HTTP request or database operation, throws an error: ![error handling 39be7](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-handling-39be7.png) - Outside a flow, you can set up an [Error Handler](#global_error_handler) component and reference it from other Error Handler configurations. The global Error Handler can also contain On-Error components and their contents. - It is also possible to set up error handling from within a [Try scope](https://docs.mulesoft.com/mule-runtime/4.4/try-scope-concept) that resides in a flow. The scope contains a built-in Error Handler in which you can configure On-Error components and their contents. ### Using Default Error Handling for Messages By default, unhandled messaging errors are logged and propagated. When a flow is processing a Mule message that raises an error, the normal execution of the flow stops, and the process transfers to the flow’s default error handler, which propagates the error. The following example shows a simple Mule app configuration that relies on default error handling instead of using explicitly configured error handling components to manage the error. ![Default error handling messages](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-error-handling-default.png) The XML for the default error handling example looks like this: ```xml ``` After you start a Mule app with this configuration and trigger the HTTP listener by loading `[http://0.0.0.0:8081/users](http://0.0.0.0:8081/users)` (for example, into a browser), the flow makes an HTTP request (`http://jsonplaceholder.typicode.com:80/somebadrequest`) for a file that does not exist. As a result, the Anypoint Studio console logs and propagates the error to the web browser. - Anypoint Studio Console Log The Studio console prints an error message. The message indicates that the default handler, `OnErrorPropagateHandler`, propagates a 404 error returned from the HTTP GET request. Mule identifies this error as HTTP:NOT\_FOUND. ```txt ERROR 2021-01-19 18:48:50,392 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-example/processors/0; event: 1d3baf11-5aa0-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request) Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-example(error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request)) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ``` The error logs in the Studio console present the following information: - **Message**: Description of the error - **Element**: XML element that failed execution and caused the error - **Element DSL**: XML element that failed execution and caused the error, expressed in DSL - **Error type**: Type of Mule error raised by the Mule app - **Flowstack**: Flowstack trace error log This field lists an entry for each flow that processed the Mule event and the processor that sent the event to the next flow. The last entry shows the flow and the processor that failed during the processing of the event. Starting with Mule 4.3.0, the Flowstack entry is enabled by default. You can disable Flowstack logging by setting the `mule.flowTrace` configuration property to `false`. - Error Propagation to the Web Browser A description of the HTTP:NOT\_FOUND error appears in the browser tab you use to trigger the listener: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` This Mule error description appears in the browser for two reasons: - The default error handler uses an On Error Propagate process (`OnErrorPropagateHandler`). The On Error Propagate component causes the flow to fail and the HTTP listener to prepare an error response for the `404` error associated with the file not found. - The HTTP listener is using default error (`error.description`) and success (`payload`) responses to return the message body. Because no custom responses are configured, the browser shows the description of the error. ### Using On-Error Components to Handle Messaging Errors Instead of relying on the default error-handling mechanism, you can use [On-Error components](https://docs.mulesoft.com/mule-runtime/4.4/on-error-scope-concept) (On Error Continue and On Error Propagate) inside a built-in or external Error Handler component. The following example shows a simple flow that is configured in Studio to return the results of an HTTP request when the HTTP listener is triggered. Unlike the [default error-handling example](#default_error_handling), this example configures On Error Continue (`on-error-continue`) inside the flow’s built-in Error Handler (`error-handler`) component, and On Error Continue contains a Logger that writes a description of the error. ![mruntime on error continue](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-on-error-continue.png) The XML for the example looks like this: ```xml ``` As in the default error-handling example, the requested page is not found, so the flow returns a 404 error that Mule identifies as an HTTP:NOT\_FOUND error. However, in this case, the tab of the browser used to trigger the HTTP listener is blank because the error is not propagated. With On Error Continue, the flow in the example is treated as though it ends successfully with a 200 for the GET request, even though the page is not found. The HTTP listener executes the behavior for the default success response (returning `payload` content as the message body). Because the page was not found, there is no content to display in the browser, so the browser tab is blank. The Studio console also prints an error message (the first ERROR message below) indicating that `OnErrorContinueHandler` is handling the error, and it prints an ERROR message from the logger (the second ERROR below) that describes the Mule error (an `error.description`, see [Selector Expressions for Mule Errors](https://docs.mulesoft.com/mule-runtime/4.4/mule-error-concept#selector_expressions)). ```txt ERROR 2021-01-19 18:42:04,583 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorContinueHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15 Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-normalFlow(error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ERROR 2021-01-19 18:42:04,586 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/errorHandler/0/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` If you instead create the same Mule app using On Error Propagate (`on-error-propagate`) instead of On Error Continue (`on-error-continue`), you receive the same error messages in the Studio console, but you also see the logged error message in your browser. This behavior is identical to the default error handling behavior because both use On Error Propagate. Note that within each On-Error component, the error path you define can incorporate any number of event processors to handle specific error types as precisely as you want. You can select specific Mule errors for the On-Error component to handle. The Error Handler component routes an error to the first On-Error component that matches the error. For more complex error handling configurations at the flow level, see [Introduction to Mule 4: Error Handlers](https://docs.mulesoft.com/mule-runtime/4.4/intro-error-handlers). For more information about On Error Continue and On Error Propagate, see [On-Error components](https://docs.mulesoft.com/mule-runtime/4.4/on-error-scope-concept). ### Referencing a Global Error Handler A global error handler can be useful if you want more than one flow or Try scope to handle errors in the same way. You can create reuse configurations by providing a reference to an error handler: - [Setting a Global Error-Handling Configuration](#global_error_config_set) - [Referencing an Error-Handling Configuration from a Flow](#global_error_config_ref) #### Setting a Global Error-Handling Configuration The following XML configuration defines a default error-handling configuration that uses `` to reference the `` configuration. ```xml ``` In the Studio UI, the global error-handling example looks like this: ![error handlers global](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-handlers-global.png) The example includes two main components for handling errors, an Error Handler (`error-handler`) with embedded components that are visible in the Studio canvas and a global error-handling configuration, which is not visible in the canvas. The flow (**someFlow**) in the UI example illustrates that the Error Handler component lies outside any flow in the Mule app. Because the request produces an HTTP:NOT\_FOUND error, the Studio console prints an error message indicating that `OnErrorContinueHandler` is handling the error. On Error Continue configurations do not propagate the errors they handle (see [Using On-Error Components to Handle Messaging Errors](#on_error_continue)). To set up the global error-handling example through the Studio UI instead of writing the configuration in XML markup: 1. Drag the Error Handler component from the **Mule Palette** to the Studio canvas, and name it **allErrorHandler**. Notice that the component is not part of any flow. 2. Drag the On Error Continue component into the Error Handler component. 3. Drag a Set Payload component into the On Error Continue component. Note that the Set Payload component is an example. You can use other components, such as a Logger, and you can write your own error message inside that component. The Set Payload example uses a Mule variable for the error description (see the `error` variable in [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) for details). 4. Create a global error-handling reference in Studio: 1. Click **Global Elements** to open **Global Configuration Elements**. **Global Elements** is located below the Studio canvas. 2. In **Global Configuration Elements**, click **Create** to open the **Choose Global Type** dialog. ![error handling global type](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-handling-global-type.png) 3. From the dialog, select **Global Configuration** -→ **Configuration**, and then click **OK** to open the **Configuration** dialog. ![error handling global config](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-handling-global-config.png) 4. From the select **Configuration** dialog, select **allErrorHandler** for the **Default Error Handler** field, and click **OK**. 5. Set up the HTTP listener and HTTP request components using the values described in the XML. 6. Check that the XML configuration looks correct by clicking **Configuration XML** (located below the Studio canvas). ### Referencing an Error-Handling Configuration from a Flow > [!NOTE] The configuration of some elements in these examples is XML-only. A flow can reference a global error handler that resides outside the flow. The flow logs all its errors through a reference. Example: XML Configuration for the App ```xml ``` In this XML example, the global error handler is configured through an `` element named `loggingErrorHandler`. The flow references the error handler with ``. To reference a global error handler configuration from a flow in Studio: 1. From Studio, drag an **Error Handler** component from the **Mule Palette** to the canvas, and configure it components through the UI. 2. In the Mule app, click **Configuration XML** (located below the Studio canvas). 3. (XML-only configuration) Within your `` element, type the XML for the reference, for example, ``. The following example references a global On Error Continue element (``) using `` within an `` element. Both require manual configuration through the **Configuration XML**, rather than the UI. ```xml ``` ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.4/mule-error-concept) - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.4/on-error-scope-concept) - [Try Scope](https://docs.mulesoft.com/mule-runtime/4.4/try-scope-concept) - [Raise Error Component](https://docs.mulesoft.com/mule-runtime/4.4/raise-error-component-reference) - [Introduction to Mule 4: Error Handlers](https://docs.mulesoft.com/mule-runtime/4.4/intro-error-handlers) - [Migrating Exception Strategies to Mule Error Handlers](https://docs.mulesoft.com/mule-runtime/4.4/migration-core-exception-strategies) --- product: Mule Runtime version: 4.6 keywords: error handling, exceptions, exception catching, exceptions --- # Error Handlers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Errors that occur in Mule belong to one of two major categories: - [System Errors](#system_errors) - [Messaging Errors](#messaging_errors) ## System Errors Mule throws a system error when an exception occurs at the system level and no Mule event is involved. A system error handler manages exceptions that occur: - During application startup. - When a connection to an external system fails. When a system error occurs, Mule sends an error notification to registered listeners, logs the error, and if the error is caused by a connection failure, executes a reconnection strategy. System error handlers are not configurable in Mule. ## Messaging Errors Mule throws a messaging error (a [Mule error](https://docs.mulesoft.com/mule-runtime/4.6/mule-error-concept)) whenever a problem occurs within a flow of a Mule app, where Mule events and the messages they contain are processed. You can handle Mule messaging errors in more than one way: - You can rely on the [default error handling](#default_error_handling) mechanism. - Within a flow, you can set up [On-Error components](https://docs.mulesoft.com/mule-runtime/4.6/on-error-scope-concept) (On Error Continue and On Error Propagate) inside the flow’s built-in Error Handler component. These components can contain any number of components to process the error. The following figure shows what happens when an event processor, such as an HTTP request or database operation, throws an error: ![error handling 39be7](/mulesoft/current/en-us/mule-runtime/4.6/_images/error-handling-39be7.png) - Outside a flow, you can set up an [Error Handler](#global_error_handler) component and reference it from other Error Handler configurations. The global Error Handler can also contain On-Error components and their contents. - It is also possible to set up error handling from within a [Try scope](https://docs.mulesoft.com/mule-runtime/4.6/try-scope-concept) that resides in a flow. The scope contains a built-in Error Handler in which you can configure On-Error components and their contents. ### Using Default Error Handling for Messages By default, unhandled messaging errors are logged and propagated. When a flow is processing a Mule message that raises an error, the normal execution of the flow stops, and the process transfers to the flow’s default error handler, which propagates the error. The following example shows a simple Mule app configuration that relies on default error handling instead of using explicitly configured error handling components to manage the error. ![Default error handling messages](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-error-handling-default.png) The XML for the default error handling example looks like this: ```xml ``` After you start a Mule app with this configuration and trigger the HTTP listener by loading `[http://0.0.0.0:8081/users](http://0.0.0.0:8081/users)` (for example, into a browser), the flow makes an HTTP request (`http://jsonplaceholder.typicode.com:80/somebadrequest`) for a file that does not exist. As a result, the Anypoint Studio console logs and propagates the error to the web browser. - Anypoint Studio Console Log The Studio console prints an error message. The message indicates that the default handler, `OnErrorPropagateHandler`, propagates a 404 error returned from the HTTP GET request. Mule identifies this error as HTTP:NOT\_FOUND. ```txt ERROR 2021-01-19 18:48:50,392 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-example/processors/0; event: 1d3baf11-5aa0-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request) Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-example(error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request)) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ``` The error logs in the Studio console present the following information: - **Message**: Description of the error - **Element**: XML element that failed execution and caused the error - **Element DSL**: XML element that failed execution and caused the error, expressed in DSL - **Error type**: Type of Mule error raised by the Mule app - **Flowstack**: Flowstack trace error log This field lists an entry for each flow that processed the Mule event and the processor that sent the event to the next flow. The last entry shows the flow and the processor that failed during the processing of the event. Starting with Mule 4.3.0, the Flowstack entry is enabled by default. You can disable Flowstack logging by setting the `mule.flowTrace` configuration property to `false`. - Error Propagation to the Web Browser A description of the HTTP:NOT\_FOUND error appears in the browser tab you use to trigger the listener: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` This Mule error description appears in the browser for two reasons: - The default error handler uses an On Error Propagate process (`OnErrorPropagateHandler`). The On Error Propagate component causes the flow to fail and the HTTP listener to prepare an error response for the `404` error associated with the file not found. - The HTTP listener is using default error (`error.description`) and success (`payload`) responses to return the message body. Because no custom responses are configured, the browser shows the description of the error. ### Using On-Error Components to Handle Messaging Errors Instead of relying on the default error-handling mechanism, you can use [On-Error components](https://docs.mulesoft.com/mule-runtime/4.6/on-error-scope-concept) (On Error Continue and On Error Propagate) inside a built-in or external Error Handler component. The following example shows a simple flow that is configured in Studio to return the results of an HTTP request when the HTTP listener is triggered. Unlike the [default error-handling example](#default_error_handling), this example configures On Error Continue (`on-error-continue`) inside the flow’s built-in Error Handler (`error-handler`) component, and On Error Continue contains a Logger that writes a description of the error. ![mruntime on error continue](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-on-error-continue.png) The XML for the example looks like this: ```xml ``` As in the default error-handling example, the requested page is not found, so the flow returns a 404 error that Mule identifies as an HTTP:NOT\_FOUND error. However, in this case, the tab of the browser used to trigger the HTTP listener is blank because the error is not propagated. With On Error Continue, the flow in the example is treated as though it ends successfully with a 200 for the GET request, even though the page is not found. The HTTP listener executes the behavior for the default success response (returning `payload` content as the message body). Because the page was not found, there is no content to display in the browser, so the browser tab is blank. The Studio console also prints an error message (the first ERROR message below) indicating that `OnErrorContinueHandler` is handling the error, and it prints an ERROR message from the logger (the second ERROR below) that describes the Mule error (an `error.description`, see [Selector Expressions for Mule Errors](https://docs.mulesoft.com/mule-runtime/4.6/mule-error-concept#selector_expressions)). ```txt ERROR 2021-01-19 18:42:04,583 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorContinueHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15 Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-normalFlow(error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ERROR 2021-01-19 18:42:04,586 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/errorHandler/0/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` If you instead create the same Mule app using On Error Propagate (`on-error-propagate`) instead of On Error Continue (`on-error-continue`), you receive the same error messages in the Studio console, but you also see the logged error message in your browser. This behavior is identical to the default error handling behavior because both use On Error Propagate. Note that within each On-Error component, the error path you define can incorporate any number of event processors to handle specific error types as precisely as you want. You can select specific Mule errors for the On-Error component to handle. The Error Handler component routes an error to the first On-Error component that matches the error. For more information about On Error Continue and On Error Propagate, see [On-Error components](https://docs.mulesoft.com/mule-runtime/4.6/on-error-scope-concept). ### Referencing a Global Error Handler A global error handler can be useful if you want more than one flow or Try scope to handle errors in the same way. You can create reuse configurations by providing a reference to an error handler: - [Setting a Global Error-Handling Configuration](#global_error_config_set) - [Referencing an Error-Handling Configuration from a Flow](#global_error_config_ref) #### Setting a Global Error-Handling Configuration The following XML configuration defines a default error-handling configuration that uses `` to reference the `` configuration. ```xml ``` In the Studio UI, the global error-handling example looks like this: ![error handlers global](/mulesoft/current/en-us/mule-runtime/4.6/_images/error-handlers-global.png) The example includes two main components for handling errors, an Error Handler (`error-handler`) with embedded components that are visible in the Studio canvas and a global error-handling configuration, which is not visible in the canvas. The flow (**someFlow**) in the UI example illustrates that the Error Handler component lies outside any flow in the Mule app. Because the request produces an HTTP:NOT\_FOUND error, the Studio console prints an error message indicating that `OnErrorContinueHandler` is handling the error. On Error Continue configurations do not propagate the errors they handle (see [Using On-Error Components to Handle Messaging Errors](#on_error_continue)). To set up the global error-handling example through the Studio UI instead of writing the configuration in XML markup: 1. Drag the Error Handler component from the **Mule Palette** to the Studio canvas, and name it **allErrorHandler**. Notice that the component is not part of any flow. 2. Drag the On Error Continue component into the Error Handler component. 3. Drag a Set Payload component into the On Error Continue component. Note that the Set Payload component is an example. You can use other components, such as a Logger, and you can write your own error message inside that component. The Set Payload example uses a Mule variable for the error description (see the `error` variable in [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) for details). 4. Create a global error-handling reference in Studio: 1. Click **Global Elements** to open **Global Configuration Elements**. **Global Elements** is located below the Studio canvas. 2. In **Global Configuration Elements**, click **Create** to open the **Choose Global Type** dialog. ![error handling global type](/mulesoft/current/en-us/mule-runtime/4.6/_images/error-handling-global-type.png) 3. From the dialog, select **Global Configuration** -→ **Configuration**, and then click **OK** to open the **Configuration** dialog. ![error handling global config](/mulesoft/current/en-us/mule-runtime/4.6/_images/error-handling-global-config.png) 4. From the select **Configuration** dialog, select **allErrorHandler** for the **Default Error Handler** field, and click **OK**. 5. Set up the HTTP listener and HTTP request components using the values described in the XML. 6. Check that the XML configuration looks correct by clicking **Configuration XML** (located below the Studio canvas). ### Referencing an Error-Handling Configuration from a Flow > [!NOTE] The configuration of some elements in these examples is XML-only. A flow can reference a global error handler that resides outside the flow. The flow logs all its errors through a reference. Example: XML Configuration for the App ```xml ``` In this XML example, the global error handler is configured through an `` element named `loggingErrorHandler`. The flow references the error handler with ``. To reference a global error handler configuration from a flow in Studio: 1. From Studio, drag an **Error Handler** component from the **Mule Palette** to the canvas, and configure it components through the UI. 2. In the Mule app, click **Configuration XML** (located below the Studio canvas). 3. (XML-only configuration) Within your `` element, type the XML for the reference, for example, ``. The following example references a global On Error Continue element (``) using `` within an `` element. Both require manual configuration through the **Configuration XML**, rather than the UI. ```xml ``` ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.6/mule-error-concept) - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.6/on-error-scope-concept) - [Try Scope](https://docs.mulesoft.com/mule-runtime/4.6/try-scope-concept) - [Raise Error Component](https://docs.mulesoft.com/mule-runtime/4.6/raise-error-component-reference) --- product: Mule Runtime version: 4.9 keywords: error handling, exceptions, exception catching, exceptions --- # Error Handlers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Errors that occur in Mule belong to one of two major categories: - [System Errors](#system_errors) - [Messaging Errors](#messaging_errors) ## System Errors Mule throws a system error when an exception occurs at the system level and no Mule event is involved. A system error handler manages exceptions that occur: - During application startup. - When a connection to an external system fails. When a system error occurs, Mule sends an error notification to registered listeners, logs the error, and if the error is caused by a connection failure, executes a reconnection strategy. System error handlers are not configurable in Mule. ## Messaging Errors Mule throws a messaging error (a [Mule error](https://docs.mulesoft.com/mule-runtime/4.9/mule-error-concept)) whenever a problem occurs within a flow of a Mule app, where Mule events and the messages they contain are processed. You can handle Mule messaging errors in more than one way: - You can rely on the [default error handling](#default_error_handling) mechanism. - Within a flow, you can set up [On-Error components](https://docs.mulesoft.com/mule-runtime/4.9/on-error-scope-concept) (On Error Continue and On Error Propagate) inside the flow’s built-in Error Handler component. These components can contain any number of components to process the error. The following figure shows what happens when an event processor, such as an HTTP request or database operation, throws an error: ![A flow showing multiple event processors and an Error Handling component](/mulesoft/current/en-us/mule-runtime/4.9/_images/error-handling-39be7.png) - Outside a flow, you can set up an [Error Handler](#global_error_handler) component and reference it from other Error Handler configurations. The global Error Handler can also contain On-Error components and their contents. - It is also possible to set up error handling from within a [Try scope](https://docs.mulesoft.com/mule-runtime/4.9/try-scope-concept) that resides in a flow. The scope contains a built-in Error Handler in which you can configure On-Error components and their contents. ### Using Default Error Handling for Messages By default, unhandled messaging errors are logged and propagated. When a flow is processing a Mule message that raises an error, the normal execution of the flow stops, and the process transfers to the flow’s default error handler, which propagates the error. The following example shows a simple Mule app configuration that relies on default error handling instead of using explicitly configured error handling components to manage the error. ![An error message display from an HTTP request failure in a Mule application](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-error-handling-default.png) The XML for the default error handling example looks like this: ```xml ``` After you start a Mule app with this configuration and trigger the HTTP listener by loading `[http://0.0.0.0:8081/users](http://0.0.0.0:8081/users)` (for example, into a browser), the flow makes an HTTP request (`http://jsonplaceholder.typicode.com:80/somebadrequest`) for a file that does not exist. As a result, the Anypoint Studio console logs and propagates the error to the web browser. - Anypoint Studio Console Log The Studio console prints an error message. The message indicates that the default handler, `OnErrorPropagateHandler`, propagates a 404 error returned from the HTTP GET request. Mule identifies this error as HTTP:NOT\_FOUND. ```txt ERROR 2021-01-19 18:48:50,392 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-example/processors/0; event: 1d3baf11-5aa0-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request) Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-example(error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request)) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ``` The error logs in the Studio console present the following information: - **Message**: Description of the error - **Element**: XML element that failed execution and caused the error - **Element DSL**: XML element that failed execution and caused the error, expressed in DSL - **Error type**: Type of Mule error raised by the Mule app - **Flowstack**: Flowstack trace error log This field lists an entry for each flow that processed the Mule event and the processor that sent the event to the next flow. The last entry shows the flow and the processor that failed during the processing of the event. Starting with Mule 4.3.0, the Flowstack entry is enabled by default. You can disable Flowstack logging by setting the `mule.flowTrace` configuration property to `false`. - Error Propagation to the Web Browser A description of the HTTP:NOT\_FOUND error appears in the browser tab you use to trigger the listener: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` This Mule error description appears in the browser for two reasons: - The default error handler uses an On Error Propagate process (`OnErrorPropagateHandler`). The On Error Propagate component causes the flow to fail and the HTTP listener to prepare an error response for the `404` error associated with the file not found. - The HTTP listener is using default error (`error.description`) and success (`payload`) responses to return the message body. Because no custom responses are configured, the browser shows the description of the error. ### Using On-Error Components to Handle Messaging Errors Instead of relying on the default error-handling mechanism, you can use [On-Error components](https://docs.mulesoft.com/mule-runtime/4.9/on-error-scope-concept) (On Error Continue and On Error Propagate) inside a built-in or external Error Handler component. The following example shows a simple flow that is configured in Studio to return the results of an HTTP request when the HTTP listener is triggered. Unlike the [default error-handling example](#default_error_handling), this example configures On Error Continue (`on-error-continue`) inside the flow’s built-in Error Handler (`error-handler`) component, and On Error Continue contains a Logger that writes a description of the error. ![A flow showing error handling configurations with components like Listener, Request, and Logger](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-on-error-continue.png) The XML for the example looks like this: ```xml ``` As in the default error-handling example, the requested page is not found, so the flow returns a 404 error that Mule identifies as an HTTP:NOT\_FOUND error. However, in this case, the tab of the browser used to trigger the HTTP listener is blank because the error is not propagated. With On Error Continue, the flow in the example is treated as though it ends successfully with a 200 for the GET request, even though the page is not found. The HTTP listener executes the behavior for the default success response (returning `payload` content as the message body). Because the page was not found, there is no content to display in the browser, so the browser tab is blank. The Studio console also prints an error message (the first ERROR message below) indicating that `OnErrorContinueHandler` is handling the error, and it prints an ERROR message from the logger (the second ERROR below) that describes the Mule error (an `error.description`, see [Selector Expressions for Mule Errors](https://docs.mulesoft.com/mule-runtime/4.9/mule-error-concept#selector_expressions)). ```txt ERROR 2021-01-19 18:42:04,583 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorContinueHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15 Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-normalFlow(error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ERROR 2021-01-19 18:42:04,586 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/errorHandler/0/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` If you instead create the same Mule app using On Error Propagate (`on-error-propagate`) instead of On Error Continue (`on-error-continue`), you receive the same error messages in the Studio console, but you also see the logged error message in your browser. This behavior is identical to the default error handling behavior because both use On Error Propagate. Note that within each On-Error component, the error path you define can incorporate any number of event processors to handle specific error types as precisely as you want. You can select specific Mule errors for the On-Error component to handle. The Error Handler component routes an error to the first On-Error component that matches the error. For more information about On Error Continue and On Error Propagate, see [On-Error components](https://docs.mulesoft.com/mule-runtime/4.9/on-error-scope-concept). ### Referencing a Global Error Handler A global error handler can be useful if you want more than one flow or Try scope to handle errors in the same way. You can create reuse configurations by providing a reference to an error handler: - [Setting a Global Error-Handling Configuration](#global_error_config_set) - [Referencing an Error-Handling Configuration from a Flow](#global_error_config_ref) #### Setting a Global Error-Handling Configuration The following XML configuration defines a default error-handling configuration that uses `` to reference the `` configuration. ```xml ``` In the Studio UI, the global error-handling example looks like this: ![A global error-handler configuration](/mulesoft/current/en-us/mule-runtime/4.9/_images/error-handlers-global.png) The example includes two main components for handling errors, an Error Handler (`error-handler`) with embedded components that are visible in the Studio canvas and a global error-handling configuration, which is not visible in the canvas. The flow (**someFlow**) in the UI example illustrates that the Error Handler component lies outside any flow in the Mule app. Because the request produces an HTTP:NOT\_FOUND error, the Studio console prints an error message indicating that `OnErrorContinueHandler` is handling the error. On Error Continue configurations do not propagate the errors they handle (see [Using On-Error Components to Handle Messaging Errors](#on_error_continue)). To set up the global error-handling example through the Studio UI instead of writing the configuration in XML markup: 1. Drag the Error Handler component from the **Mule Palette** to the Studio canvas, and name it **allErrorHandler**. Notice that the component is not part of any flow. 2. Drag the On Error Continue component into the Error Handler component. 3. Drag a Set Payload component into the On Error Continue component. Note that the Set Payload component is an example. You can use other components, such as a Logger, and you can write your own error message inside that component. The Set Payload example uses a Mule variable for the error description (see the `error` variable in [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) for details). 4. Create a global error-handling reference in Studio: 1. Click **Global Elements** to open **Global Configuration Elements**. **Global Elements** is located below the Studio canvas. 2. In **Global Configuration Elements**, click **Create** to open the **Choose Global Type** dialog. ![A configuration panel for choosing a global element type including configuration](/mulesoft/current/en-us/mule-runtime/4.9/_images/error-handling-global-type.png) 3. From the dialog, select **Global Configuration** -→ **Configuration**, and then click **OK** to open the **Configuration** dialog. ![A configuration dialog general fields including settings](/mulesoft/current/en-us/mule-runtime/4.9/_images/error-handling-global-config.png) 4. From the select **Configuration** dialog, select **allErrorHandler** for the **Default Error Handler** field, and click **OK**. 5. Set up the HTTP listener and HTTP request components using the values described in the XML. 6. Check that the XML configuration looks correct by clicking **Configuration XML** (located below the Studio canvas). ### Referencing an Error-Handling Configuration from a Flow > [!NOTE] The configuration of some elements in these examples is XML-only. A flow can reference a global error handler that resides outside the flow. The flow logs all its errors through a reference. Example: XML Configuration for the App ```xml ``` In this XML example, the global error handler is configured through an `` element named `loggingErrorHandler`. The flow references the error handler with ``. To reference a global error handler configuration from a flow in Studio: 1. From Studio, drag an **Error Handler** component from the **Mule Palette** to the canvas, and configure it components through the UI. 2. In the Mule app, click **Configuration XML** (located below the Studio canvas). 3. (XML-only configuration) Within your `` element, type the XML for the reference, for example, ``. The following example references a global On Error Continue element (``) using `` within an `` element. Both require manual configuration through the **Configuration XML**, rather than the UI. ```xml ``` ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.9/mule-error-concept) - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.9/on-error-scope-concept) - [Try Scope](https://docs.mulesoft.com/mule-runtime/4.9/try-scope-concept) - [Raise Error Component](https://docs.mulesoft.com/mule-runtime/4.9/raise-error-component-reference) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: error handling, exceptions, exception catching, exceptions --- # Error Handlers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Errors that occur in Mule belong to one of two major categories: - [System Errors](#system_errors) - [Messaging Errors](#messaging_errors) ## System Errors Mule throws a system error when an exception occurs at the system level and no Mule event is involved. A system error handler manages exceptions that occur: - During application startup. - When a connection to an external system fails. When a system error occurs, Mule sends an error notification to registered listeners, logs the error, and if the error is caused by a connection failure, executes a reconnection strategy. System error handlers are not configurable in Mule. ## Messaging Errors Mule throws a messaging error (a [Mule error](https://docs.mulesoft.com/mule-runtime/latest/mule-error-concept)) whenever a problem occurs within a flow of a Mule app, where Mule events and the messages they contain are processed. You can handle Mule messaging errors in more than one way: - You can rely on the [default error handling](#default_error_handling) mechanism. - Within a flow, you can set up [On-Error components](https://docs.mulesoft.com/mule-runtime/latest/on-error-scope-concept) (On Error Continue and On Error Propagate) inside the flow’s built-in Error Handler component. These components can contain any number of components to process the error. The following figure shows what happens when an event processor, such as an HTTP request or database operation, throws an error: ![A flow showing multiple event processors and an Error Handling component](/mulesoft/current/en-us/mule-runtime/latest/_images/error-handling-39be7.png) - Outside a flow, you can set up an [Error Handler](#global_error_handler) component and reference it from other Error Handler configurations. The global Error Handler can also contain On-Error components and their contents. - It is also possible to set up error handling from within a [Try scope](https://docs.mulesoft.com/mule-runtime/latest/try-scope-concept) that resides in a flow. The scope contains a built-in Error Handler in which you can configure On-Error components and their contents. ### Using Default Error Handling for Messages By default, unhandled messaging errors are logged and propagated. When a flow is processing a Mule message that raises an error, the normal execution of the flow stops, and the process transfers to the flow’s default error handler, which propagates the error. The following example shows a simple Mule app configuration that relies on default error handling instead of using explicitly configured error handling components to manage the error. ![An error message display from an HTTP request failure in a Mule application](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-error-handling-default.png) The XML for the default error handling example looks like this: ```xml ``` After you start a Mule app with this configuration and trigger the HTTP listener by loading `[http://0.0.0.0:8081/users](http://0.0.0.0:8081/users)` (for example, into a browser), the flow makes an HTTP request (`http://jsonplaceholder.typicode.com:80/somebadrequest`) for a file that does not exist. As a result, the Anypoint Studio console logs and propagates the error to the web browser. - Anypoint Studio Console Log The Studio console prints an error message. The message indicates that the default handler, `OnErrorPropagateHandler`, propagates a 404 error returned from the HTTP GET request. Mule identifies this error as HTTP:NOT\_FOUND. ```txt ERROR 2021-01-19 18:48:50,392 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-example/processors/0; event: 1d3baf11-5aa0-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request) Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-example(error-handlers-example/processors/0 @ error-handlers-example:error-handlers-example.xml:15 (Request)) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ``` The error logs in the Studio console present the following information: - **Message**: Description of the error - **Element**: XML element that failed execution and caused the error - **Element DSL**: XML element that failed execution and caused the error, expressed in DSL - **Error type**: Type of Mule error raised by the Mule app - **Flowstack**: Flowstack trace error log This field lists an entry for each flow that processed the Mule event and the processor that sent the event to the next flow. The last entry shows the flow and the processor that failed during the processing of the event. Starting with Mule 4.3.0, the Flowstack entry is enabled by default. You can disable Flowstack logging by setting the `mule.flowTrace` configuration property to `false`. - Error Propagation to the Web Browser A description of the HTTP:NOT\_FOUND error appears in the browser tab you use to trigger the listener: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` This Mule error description appears in the browser for two reasons: - The default error handler uses an On Error Propagate process (`OnErrorPropagateHandler`). The On Error Propagate component causes the flow to fail and the HTTP listener to prepare an error response for the `404` error associated with the file not found. - The HTTP listener is using default error (`error.description`) and success (`payload`) responses to return the message body. Because no custom responses are configured, the browser shows the description of the error. ### Using On-Error Components to Handle Messaging Errors Instead of relying on the default error-handling mechanism, you can use [On-Error components](https://docs.mulesoft.com/mule-runtime/latest/on-error-scope-concept) (On Error Continue and On Error Propagate) inside a built-in or external Error Handler component. The following example shows a simple flow that is configured in Studio to return the results of an HTTP request when the HTTP listener is triggered. Unlike the [default error-handling example](#default_error_handling), this example configures On Error Continue (`on-error-continue`) inside the flow’s built-in Error Handler (`error-handler`) component, and On Error Continue contains a Logger that writes a description of the error. ![A flow showing error handling configurations with components like Listener, Request, and Logger](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-on-error-continue.png) The XML for the example looks like this: ```xml ``` As in the default error-handling example, the requested page is not found, so the flow returns a 404 error that Mule identifies as an HTTP:NOT\_FOUND error. However, in this case, the tab of the browser used to trigger the HTTP listener is blank because the error is not propagated. With On Error Continue, the flow in the example is treated as though it ends successfully with a 200 for the GET request, even though the page is not found. The HTTP listener executes the behavior for the default success response (returning `payload` content as the message body). Because the page was not found, there is no content to display in the browser, so the browser tab is blank. The Studio console also prints an error message (the first ERROR message below) indicating that `OnErrorContinueHandler` is handling the error, and it prints an ERROR message from the logger (the second ERROR below) that describes the Mule error (an `error.description`, see [Selector Expressions for Mule Errors](https://docs.mulesoft.com/mule-runtime/latest/mule-error-concept#selector_expressions)). ```txt ERROR 2021-01-19 18:42:04,583 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.exception.OnErrorContinueHandler: ******************************************************************************** Message : HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). Element : error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15 Element DSL : Error type : HTTP:NOT_FOUND FlowStack : at error-handlers-normalFlow(error-handlers-normalFlow/processors/0 @ error-handlers-example:error-handlers-example.xml:15) (set debug level logging or '-Dmule.verbose.exceptions=true' for everything) ******************************************************************************** ERROR 2021-01-19 18:42:04,586 [[error-handlers-example].http.requester.HTTP_Request_configuration.11 SelectorRunner] [processor: error-handlers-normalFlow/errorHandler/0/processors/0; event: 2a95eaa1-5a9f-11eb-b96f-a483e7abe2b5] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/somebadrequest' failed: not found (404). ``` If you instead create the same Mule app using On Error Propagate (`on-error-propagate`) instead of On Error Continue (`on-error-continue`), you receive the same error messages in the Studio console, but you also see the logged error message in your browser. This behavior is identical to the default error handling behavior because both use On Error Propagate. Note that within each On-Error component, the error path you define can incorporate any number of event processors to handle specific error types as precisely as you want. You can select specific Mule errors for the On-Error component to handle. The Error Handler component routes an error to the first On-Error component that matches the error. For more information about On Error Continue and On Error Propagate, see [On-Error components](https://docs.mulesoft.com/mule-runtime/latest/on-error-scope-concept). ### Referencing a Global Error Handler A global error handler can be useful if you want more than one flow or Try scope to handle errors in the same way. You can create reuse configurations by providing a reference to an error handler: - [Setting a Global Error-Handling Configuration](#global_error_config_set) - [Referencing an Error-Handling Configuration from a Flow](#global_error_config_ref) #### Setting a Global Error-Handling Configuration The following XML configuration defines a default error-handling configuration that uses `` to reference the `` configuration. ```xml ``` In the Studio UI, the global error-handling example looks like this: ![A global error-handler configuration](/mulesoft/current/en-us/mule-runtime/latest/_images/error-handlers-global.png) The example includes two main components for handling errors, an Error Handler (`error-handler`) with embedded components that are visible in the Studio canvas and a global error-handling configuration, which is not visible in the canvas. The flow (**someFlow**) in the UI example illustrates that the Error Handler component lies outside any flow in the Mule app. Because the request produces an HTTP:NOT\_FOUND error, the Studio console prints an error message indicating that `OnErrorContinueHandler` is handling the error. On Error Continue configurations do not propagate the errors they handle (see [Using On-Error Components to Handle Messaging Errors](#on_error_continue)). To set up the global error-handling example through the Studio UI instead of writing the configuration in XML markup: 1. Drag the Error Handler component from the **Mule Palette** to the Studio canvas, and name it **allErrorHandler**. Notice that the component is not part of any flow. 2. Drag the On Error Continue component into the Error Handler component. 3. Drag a Set Payload component into the On Error Continue component. Note that the Set Payload component is an example. You can use other components, such as a Logger, and you can write your own error message inside that component. The Set Payload example uses a Mule variable for the error description (see the `error` variable in [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) for details). 4. Create a global error-handling reference in Studio: 1. Click **Global Elements** to open **Global Configuration Elements**. **Global Elements** is located below the Studio canvas. 2. In **Global Configuration Elements**, click **Create** to open the **Choose Global Type** dialog. ![A configuration panel for choosing a global element type including configuration](/mulesoft/current/en-us/mule-runtime/latest/_images/error-handling-global-type.png) 3. From the dialog, select **Global Configuration** -→ **Configuration**, and then click **OK** to open the **Configuration** dialog. ![A configuration dialog general fields including settings](/mulesoft/current/en-us/mule-runtime/latest/_images/error-handling-global-config.png) 4. From the select **Configuration** dialog, select **allErrorHandler** for the **Default Error Handler** field, and click **OK**. 5. Set up the HTTP listener and HTTP request components using the values described in the XML. 6. Check that the XML configuration looks correct by clicking **Configuration XML** (located below the Studio canvas). ### Referencing an Error-Handling Configuration from a Flow > [!NOTE] The configuration of some elements in these examples is XML-only. A flow can reference a global error handler that resides outside the flow. The flow logs all its errors through a reference. Example: XML Configuration for the App ```xml ``` In this XML example, the global error handler is configured through an `` element named `loggingErrorHandler`. The flow references the error handler with ``. To reference a global error handler configuration from a flow in Studio: 1. From Studio, drag an **Error Handler** component from the **Mule Palette** to the canvas, and configure it components through the UI. 2. In the Mule app, click **Configuration XML** (located below the Studio canvas). 3. (XML-only configuration) Within your `` element, type the XML for the reference, for example, ``. The following example references a global On Error Continue element (``) using `` within an `` element. Both require manual configuration through the **Configuration XML**, rather than the UI. ```xml ``` ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/latest/mule-error-concept) - [On-Error Components](https://docs.mulesoft.com/mule-runtime/latest/on-error-scope-concept) - [Try Scope](https://docs.mulesoft.com/mule-runtime/latest/try-scope-concept) - [Raise Error Component](https://docs.mulesoft.com/mule-runtime/latest/raise-error-component-reference) --- product: Mule Runtime version: 4.11 keywords: mule, threading, scheduler, non-blocking --- # Execution Engine > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine implements a reactive execution engine, tuned for nonblocking and asynchronous execution. To see more details about reactive programming, visit [https://en.wikipedia.org/wiki/Reactive\_programming](https://en.wikipedia.org/wiki/Reactive_programming). This task-oriented execution model enables you to take advantage of nonblocking I/O at high concurrency levels transparently, meaning you don’t need to account for threading or asynchronicity in your flows. Each operation inside a Mule flow is a task that provides metadata about its execution, and Mule makes tuning decisions based on that metadata. Mule event processors indicate to Mule whether they are CPU-intensive, CPU-light, or I/O-intensive operations. These workload types help Mule tune for different workloads, so you don’t need to manage thread pools manually to achieve optimum performance. Instead, Mule introspects the available resources (such as memory and CPU cores) in the system to tune thread pools automatically. ## Processing Types Mule event processors indicate to Mule what kind of work they do, which can be one of: - CPU-Light For quick operations (around 10 ms), or nonblocking I/O, for example, a Logger (`logger`) or HTTP Request operation (`http:request`). These tasks should not perform any blocking I/O activities. The applicable strings in the logs are `CPU_LIGHT` and `CPU_LIGHT_ASYNC`. - Blocking I/O For I/O that blocks the calling thread, for example, a Database Select operation (`db:select`) or a SFTP read (`sftp:read`) . Applicable strings in the logs are `BLOCKING` and `IO`. - CPU Intensive For CPU-bound computations, usually taking more than 10 ms to execute. These tasks should not perform any I/O activities. One example is the Transform Message component (`ee:transform`). The applicable string in the logs is `CPU_INTENSIVE`. See specific component or module documentation to learn the processing type it supports. If none is specified, the default type is CPU Light. For connectors created with the Mule SDK, the SDK determines the most appropriate processing type based on how the connector is implemented. For details on that mechanism, refer to the [Mule SDK documentation](https://docs.mulesoft.com/mule-sdk/latest/). ## Threading Starting in Mule 4.3, Mule contains one unique thread pool, called the UBER pool. This thread pool is managed by Mule and shared across all apps in the same Mule instance. At startup, Mule introspects the available resources (such as memory and CPU cores) in the system and tunes automatically for the environment where Mule is running. This algorithm was established through performance testing and found optimal values for most scenarios. This single thread pool allows Mule to be efficient, requiring significantly fewer threads (and their inherent memory footprint) to process a given workload when compared to previous versions. > [!NOTE] If you are upgrading from earlier Mule versions, see [Threading in Mule 4.2](#threading) > to understand the differences applied to the threading model in Mule 4.3. ### Proactor Pattern Proactor is a design pattern for asynchronous execution. To understand how the Proactor design pattern works, visit [https://en.wikipedia.org/wiki/Proactor\_pattern](https://en.wikipedia.org/wiki/Proactor_pattern) According to this design pattern, tasks are classified in categories that correspond to Mule processing types, and each task is submitted for execution to the UBER pool. Performance testing shows that applying the Proactor pattern leads to better performance, even with one unique thread pool, because it allows threads to return to the main loop more quickly, allowing the system to continue to accept new work while the I/O tasks are blocked and waiting. ### Transactions When there’s an active transaction, all thread switches are suspended. Event processors participating in the transaction are executed in the same thread. ## Configuration The thread pool is automatically configured by Mule at startup, applying formulas that consider available resources such as CPU and memory. If you run Mule runtime engine on premises, you can modify these global formulas by editing the `MULE_HOME/conf/schedulers-pools.conf` file in your local Mule instance. This configuration file contains comments that document each of the properties, but depending on your pool strategy, you can configure specific properties. Configure the `org.mule.runtime.scheduler.SchedulerPoolStrategy` parameter to switch between the two available strategies: - UBER Unified scheduling strategy. Default. - DEDICATED Separated pools strategy. Legacy. ```properties # The strategy to be used for managing the thread pools that back the 3 types of schedulers in the Mule Runtime # (cpu_light, cpu_intensive and I/O). # Possible values are: # - UBER: All three scheduler types will be backed by one uber thread pool (default since 4.3.0) # - DEDICATED: Each scheduler type is backed by its own Thread pool (legacy mode to Mule 4.1.x and 4.2.x) org.mule.runtime.scheduler.SchedulerPoolStrategy=UBER ``` ### UBER Scheduling Strategy When the strategy is set to `UBER`, the following configuration applies: - `org.mule.runtime.scheduler.uber.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.uber.workQueue.size=0` - `org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.coreSize=cores # The maximum number of threads to allow in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding tasks in the uber pool before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.workQueue.size=0 # When the number of threads in the uber pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000 ``` ### DEDICATED Scheduling Strategy When the strategy is set to `DEDICATED`, the parameters from the default UBER strategy are ignored. To enable this configuration, uncomment the following parameters in your `schedulers-pools.conf` file: - `org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuLight.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.io.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000` - `org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the cpu_lite pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores # The size of the queue to use for holding cpu_lite tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.workQueue.size=0 # The number of threads to keep in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.coreSize=cores # The maximum number of threads to allow in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding I/O tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.workQueue.size=0 # When the number of threads in the I/O pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000 # The number of threads to keep in the cpu_intensive pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores # The size of the queue to use for holding cpu_intensive tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores ``` #### Considerations MuleSoft doesn’t recommend changing the used pool strategy nor change its configuration values. Note that the configuration is global and affects the entire Mule Runtime instance. MuleSoft recommends that you perform load and stress testing with all applications involved in real-life scenarios to validate any change in the threading configurations and to understand how the thread pools work in Mule 4. ### Configuration at the Application Level You can define the pool strategy to use in an application by adding the following to your application code: ```xml ``` The `poolStrategy` parameter exists for backward compatibility, enabling you to revert to the three pools scheme from earlier Mule versions: ```xml ``` The `gracefulShutdownTimeout` parameter specifies the maximum time (in milliseconds) to wait until all tasks in all the artifact thread pools have completed execution when stopping the scheduler service. The following table describes the configurable properties and includes the XML attribute for each field.
Property NameXMLDescription

Pool Size

poolSize

The number of threads to keep in the pool, even if they are idle.

Queue Size

queueSize

The size of the queue to use for holding tasks before they are executed.

Core Pool Size

corePoolSize

The number of threads to keep in the pool.

Max Pool Size

maxPoolSize

The maximum number of threads to allow in the pool.

Keep Alive

keepAlive

When the number of threads in the pool is greater than the indicated core pool size, this value sets the maximum time (in milliseconds) for excess idle threads to wait for new tasks before terminating.

#### Considerations Applying pool configurations at the application level causes Mule to create a completely new set of thread pools for the Mule app. This configuration does not change the default settings in `scheduler-conf.properties`, which is particularly important for on-premises deployments in which many Mule apps are deployed to the same Mule instance. MuleSoft recommends running Mule using default settings. If you upgrade from Mule 4.1.x or Mule 4.2.x you can use the DEDICATED strategy so that any customizations to `scheduler-conf.properties` are still used. However, MuleSoft recommends to test the new default setting to determine whether the optimizations are still required. Also, try first to customize the new UBER strategy before reverting to the legacy mode. > [!NOTE] If you define pool configurations at the application level for Mule apps deployed to > CloudHub, be mindful about worker sizes because fractional vCores have less memory. See > [CloudHub Workers](https://docs.mulesoft.com/cloudhub/cloudhub-architecture#cloudhub-workers) for more details. ## Custom Thread Pools Besides the unique UBER thread pool, some components might create additional pools for specific purposes: - NIO Selectors Enables nonblocking I/O. Each connector can create as many as required. - Recurring tasks pools Some connectors or components (expiration monitors, queue consumers, and so on) might create specific pools to perform recurring tasks. ## Back-Pressure Management Back pressure can occur when, under heavy load, Mule does not have resources available to process a specific event. This issue might occur because all threads are busy and cannot perform the handoff of the newly arrived event, or because the current flow’s `maxConcurrency` value has been exceeded already. If Mule cannot handle an event, it logs the condition with the message `Flow 'flowName' is unable to accept new events at this time`. Mule also notifies the flow source, to perform any required actions. The actions that Mule performs as a result of back-pressure are specific to each connector’s source. For example, `http:listener` might return a `503` error code, while a message-broker listener might provide the option to either wait for resources to be available or drop the message. In some cases, a source might disconnect from a remote system to avoid getting more data than it can process and then reconnect after the server state is normalized. ## Upgrading from Mule 4.2 or 4.1 When upgrading from Mule 4.2.x or 4.1.x to Mule 4.3.x or later, take the following actions: - If no custom threading settings are applied (either through `scheduler-pools.conf` or directly in the Mule app), then no action is required. - If custom threading configurations are applied, test your Mule applications using the default configuration. Because of the UBER pool strategy and other performance updates implemented in Mule 4.3, you might not need custom threading configurations. - If tests confirm that a custom configuration is still necessary, a problem might exist with resource management in the application, one of the application dependencies, or the Mule instance. Using a custom configuration can lead to inefficient use of resources and might hide underlying issues. ## Troubleshooting When troubleshooting a Mule app, consider thread naming conventions. For example, consider this flow: ```xml ``` After execution, the flow produces the following log: ERROR 2020-03-12 19:13:45,292 \[\[MuleRuntime\].uber.07: \[echo\].echoFlow.CPU\_LITE @63e7e52c\] \[event: bd56a240-64ae-11ea-8f7d-f01898419bde\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: request at 2020-03-12T19:13:45.283-03:00\[America/Argentina/Buenos\_Aires\] In this case, the thread name is `uber.07`. Mule also logs the type of the operation, which in this case is `CPU_LITE`. Thread names also show up on thread dumps or when using a profiler: ![A table listing thread groups in a profiling tool](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-thread-profiler.png) --- product: Mule Runtime version: 4.12 keywords: mule, threading, scheduler, non-blocking --- # Execution Engine > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine implements a reactive execution engine, tuned for nonblocking and asynchronous execution. To see more details about reactive programming, visit [https://en.wikipedia.org/wiki/Reactive\_programming](https://en.wikipedia.org/wiki/Reactive_programming). This task-oriented execution model enables you to take advantage of nonblocking I/O at high concurrency levels transparently, meaning you don’t need to account for threading or asynchronicity in your flows. Each operation inside a Mule flow is a task that provides metadata about its execution, and Mule makes tuning decisions based on that metadata. Mule event processors indicate to Mule whether they are CPU-intensive, CPU-light, or I/O-intensive operations. These workload types help Mule tune for different workloads, so you don’t need to manage thread pools manually to achieve optimum performance. Instead, Mule introspects the available resources (such as memory and CPU cores) in the system to tune thread pools automatically. ## Processing Types Mule event processors indicate to Mule what kind of work they do, which can be one of: - CPU-Light For quick operations (around 10 ms), or nonblocking I/O, for example, a Logger (`logger`) or HTTP Request operation (`http:request`). These tasks should not perform any blocking I/O activities. The applicable strings in the logs are `CPU_LIGHT` and `CPU_LIGHT_ASYNC`. - Blocking I/O For I/O that blocks the calling thread, for example, a Database Select operation (`db:select`) or a SFTP read (`sftp:read`) . Applicable strings in the logs are `BLOCKING` and `IO`. - CPU Intensive For CPU-bound computations, usually taking more than 10 ms to execute. These tasks should not perform any I/O activities. One example is the Transform Message component (`ee:transform`). The applicable string in the logs is `CPU_INTENSIVE`. See specific component or module documentation to learn the processing type it supports. If none is specified, the default type is CPU Light. For connectors created with the Mule SDK, the SDK determines the most appropriate processing type based on how the connector is implemented. For details on that mechanism, refer to the [Mule SDK documentation](https://docs.mulesoft.com/mule-sdk/latest/). ## Threading Starting in Mule 4.3, Mule contains one unique thread pool, called the UBER pool. This thread pool is managed by Mule and shared across all apps in the same Mule instance. At startup, Mule introspects the available resources (such as memory and CPU cores) in the system and tunes automatically for the environment where Mule is running. This algorithm was established through performance testing and found optimal values for most scenarios. This single thread pool allows Mule to be efficient, requiring significantly fewer threads (and their inherent memory footprint) to process a given workload when compared to previous versions. > [!NOTE] If you are upgrading from earlier Mule versions, see [Threading in Mule 4.2](#threading) > to understand the differences applied to the threading model in Mule 4.3. ### Proactor Pattern Proactor is a design pattern for asynchronous execution. To understand how the Proactor design pattern works, visit [https://en.wikipedia.org/wiki/Proactor\_pattern](https://en.wikipedia.org/wiki/Proactor_pattern) According to this design pattern, tasks are classified in categories that correspond to Mule processing types, and each task is submitted for execution to the UBER pool. Performance testing shows that applying the Proactor pattern leads to better performance, even with one unique thread pool, because it allows threads to return to the main loop more quickly, allowing the system to continue to accept new work while the I/O tasks are blocked and waiting. ### Transactions When there’s an active transaction, all thread switches are suspended. Event processors participating in the transaction are executed in the same thread. ## Configuration The thread pool is automatically configured by Mule at startup, applying formulas that consider available resources such as CPU and memory. If you run Mule runtime engine on premises, you can modify these global formulas by editing the `MULE_HOME/conf/schedulers-pools.conf` file in your local Mule instance. This configuration file contains comments that document each of the properties, but depending on your pool strategy, you can configure specific properties. Configure the `org.mule.runtime.scheduler.SchedulerPoolStrategy` parameter to switch between the two available strategies: - UBER Unified scheduling strategy. Default. - DEDICATED Separated pools strategy. Legacy. ```properties # The strategy to be used for managing the thread pools that back the 3 types of schedulers in the Mule Runtime # (cpu_light, cpu_intensive and I/O). # Possible values are: # - UBER: All three scheduler types will be backed by one uber thread pool (default since 4.3.0) # - DEDICATED: Each scheduler type is backed by its own Thread pool (legacy mode to Mule 4.1.x and 4.2.x) org.mule.runtime.scheduler.SchedulerPoolStrategy=UBER ``` ### UBER Scheduling Strategy When the strategy is set to `UBER`, the following configuration applies: - `org.mule.runtime.scheduler.uber.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.uber.workQueue.size=0` - `org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.coreSize=cores # The maximum number of threads to allow in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding tasks in the uber pool before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.workQueue.size=0 # When the number of threads in the uber pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000 ``` ### DEDICATED Scheduling Strategy When the strategy is set to `DEDICATED`, the parameters from the default UBER strategy are ignored. To enable this configuration, uncomment the following parameters in your `schedulers-pools.conf` file: - `org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuLight.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.io.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000` - `org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the cpu_lite pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores # The size of the queue to use for holding cpu_lite tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.workQueue.size=0 # The number of threads to keep in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.coreSize=cores # The maximum number of threads to allow in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding I/O tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.workQueue.size=0 # When the number of threads in the I/O pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000 # The number of threads to keep in the cpu_intensive pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores # The size of the queue to use for holding cpu_intensive tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores ``` #### Considerations MuleSoft doesn’t recommend changing the used pool strategy nor change its configuration values. Note that the configuration is global and affects the entire Mule Runtime instance. MuleSoft recommends that you perform load and stress testing with all applications involved in real-life scenarios to validate any change in the threading configurations and to understand how the thread pools work in Mule 4. ### Configuration at the Application Level You can define the pool strategy to use in an application by adding the following to your application code: ```xml ``` The `poolStrategy` parameter exists for backward compatibility, enabling you to revert to the three pools scheme from earlier Mule versions: ```xml ``` The `gracefulShutdownTimeout` parameter specifies the maximum time (in milliseconds) to wait until all tasks in all the artifact thread pools have completed execution when stopping the scheduler service. The following table describes the configurable properties and includes the XML attribute for each field.
Property NameXMLDescription

Pool Size

poolSize

The number of threads to keep in the pool, even if they are idle.

Queue Size

queueSize

The size of the queue to use for holding tasks before they are executed.

Core Pool Size

corePoolSize

The number of threads to keep in the pool.

Max Pool Size

maxPoolSize

The maximum number of threads to allow in the pool.

Keep Alive

keepAlive

When the number of threads in the pool is greater than the indicated core pool size, this value sets the maximum time (in milliseconds) for excess idle threads to wait for new tasks before terminating.

#### Considerations Applying pool configurations at the application level causes Mule to create a completely new set of thread pools for the Mule app. This configuration does not change the default settings in `scheduler-conf.properties`, which is particularly important for on-premises deployments in which many Mule apps are deployed to the same Mule instance. MuleSoft recommends running Mule using default settings. If you upgrade from Mule 4.1.x or Mule 4.2.x you can use the DEDICATED strategy so that any customizations to `scheduler-conf.properties` are still used. However, MuleSoft recommends to test the new default setting to determine whether the optimizations are still required. Also, try first to customize the new UBER strategy before reverting to the legacy mode. > [!NOTE] If you define pool configurations at the application level for Mule apps deployed to > CloudHub, be mindful about worker sizes because fractional vCores have less memory. See > [CloudHub Workers](https://docs.mulesoft.com/cloudhub/cloudhub-architecture#cloudhub-workers) for more details. ## Custom Thread Pools Besides the unique UBER thread pool, some components might create additional pools for specific purposes: - NIO Selectors Enables nonblocking I/O. Each connector can create as many as required. - Recurring tasks pools Some connectors or components (expiration monitors, queue consumers, and so on) might create specific pools to perform recurring tasks. ## Back-Pressure Management Back pressure can occur when, under heavy load, Mule does not have resources available to process a specific event. This issue might occur because all threads are busy and cannot perform the handoff of the newly arrived event, or because the current flow’s `maxConcurrency` value has been exceeded already. If Mule cannot handle an event, it logs the condition with the message `Flow 'flowName' is unable to accept new events at this time`. Mule also notifies the flow source, to perform any required actions. The actions that Mule performs as a result of back-pressure are specific to each connector’s source. For example, `http:listener` might return a `503` error code, while a message-broker listener might provide the option to either wait for resources to be available or drop the message. In some cases, a source might disconnect from a remote system to avoid getting more data than it can process and then reconnect after the server state is normalized. ## Upgrading from Mule 4.2 or 4.1 When upgrading from Mule 4.2.x or 4.1.x to Mule 4.3.x or later, take the following actions: - If no custom threading settings are applied (either through `scheduler-pools.conf` or directly in the Mule app), then no action is required. - If custom threading configurations are applied, test your Mule applications using the default configuration. Because of the UBER pool strategy and other performance updates implemented in Mule 4.3, you might not need custom threading configurations. - If tests confirm that a custom configuration is still necessary, a problem might exist with resource management in the application, one of the application dependencies, or the Mule instance. Using a custom configuration can lead to inefficient use of resources and might hide underlying issues. ## Troubleshooting When troubleshooting a Mule app, consider thread naming conventions. For example, consider this flow: ```xml ``` After execution, the flow produces the following log: ERROR 2020-03-12 19:13:45,292 \[\[MuleRuntime\].uber.07: \[echo\].echoFlow.CPU\_LITE @63e7e52c\] \[event: bd56a240-64ae-11ea-8f7d-f01898419bde\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: request at 2020-03-12T19:13:45.283-03:00\[America/Argentina/Buenos\_Aires\] In this case, the thread name is `uber.07`. Mule also logs the type of the operation, which in this case is `CPU_LITE`. Thread names also show up on thread dumps or when using a profiler: ![A table listing thread groups in a profiling tool](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-thread-profiler.png) --- product: Mule Runtime version: 4.3 keywords: mule, threading, scheduler, non-blocking --- # Execution Engine > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine implements a reactive execution engine, tuned for nonblocking and asynchronous execution. To see more details about reactive programming, visit [https://en.wikipedia.org/wiki/Reactive\_programming](https://en.wikipedia.org/wiki/Reactive_programming). This task-oriented execution model enables you to take advantage of nonblocking I/O at high concurrency levels transparently, meaning you don’t need to account for threading or asynchronicity in your flows. Each operation inside a Mule flow is a task that provides metadata about its execution, and Mule makes tuning decisions based on that metadata. Mule event processors indicate to Mule whether they are CPU-intensive, CPU-light, or I/O-intensive operations. These workload types help Mule tune for different workloads, so you don’t need to manage thread pools manually to achieve optimum performance. Instead, Mule introspects the available resources (such as memory and CPU cores) in the system to tune thread pools automatically. ## Processing Types Mule event processors indicate to Mule what kind of work they do, which can be one of: - CPU-Light For quick operations (around 10 ms), or nonblocking I/O, for example, a Logger (`logger`) or HTTP Request operation (`http:request`). These tasks should not perform any blocking I/O activities. The applicable strings in the logs are `CPU_LIGHT` and `CPU_LIGHT_ASYNC`. - Blocking I/O For I/O that blocks the calling thread, for example, a Database Select operation (`db:select`) or a SFTP read (`sftp:read`) . Applicable strings in the logs are `BLOCKING` and `IO`. - CPU Intensive For CPU-bound computations, usually taking more than 10 ms to execute. These tasks should not perform any I/O activities. One example is the Transform Message component (`ee:transform`). The applicable string in the logs is `CPU_INTENSIVE`. See specific component or module documentation to learn the processing type it supports. If none is specified, the default type is CPU Light. For connectors created with the Mule SDK, the SDK determines the most appropriate processing type based on how the connector is implemented. For details on that mechanism, refer to the [Mule SDK documentation](https://docs.mulesoft.com/mule-sdk/latest/). ## Threading Mule 4.3 contains one unique thread pool, called the UBER pool. This thread pool is managed by Mule and shared across all apps in the same Mule instance. At startup, Mule introspects the available resources (such as memory and CPU cores) in the system and tunes automatically for the environment where Mule is running. This algorithm was established through performance testing and found optimal values for most scenarios. This single thread pool allows Mule to be efficient, requiring significantly fewer threads (and their inherent memory footprint) to process a given workload when compared to Mule 3. ### Proactor Pattern Proactor is a design pattern for asynchronous execution. To understand how the Proactor design pattern works, visit [https://en.wikipedia.org/wiki/Proactor\_pattern](https://en.wikipedia.org/wiki/Proactor_pattern) According to this design pattern, tasks are classified in categories that correspond to Mule processing types, and each task is submitted for execution to the UBER pool. Performance testing shows that applying the Proactor pattern leads to better performance, even with one unique thread pool, because it allows threads to return to the main loop more quickly, allowing the system to continue to accept new work while the I/O tasks are blocked and waiting. ### Transactions When there’s an active transaction, all thread switches are suspended. Event processors participating in the transaction are executed in the same thread. ## Configuration The thread pool is automatically configured by Mule at startup, applying formulas that consider available resources such as CPU and memory. If you run Mule runtime engine on premises, you can modify these global formulas by editing the `MULE_HOME/conf/schedulers-pools.conf` file in your local Mule instance. This configuration file contains comments that document each of the properties, but depending on your pool strategy, you can configure specific properties. Configure the `org.mule.runtime.scheduler.SchedulerPoolStrategy` parameter to switch between the two available strategies: - UBER Unified scheduling strategy. Default. - DEDICATED Separated pools strategy. Legacy. ```properties # The strategy to be used for managing the thread pools that back the 3 types of schedulers in the Mule Runtime # (cpu_light, cpu_intensive and I/O). # Possible values are: # - UBER: All three scheduler types will be backed by one uber uber thread pool (default since 4.3.0) # - DEDICATED: Each scheduler type is backed by its own Thread pool (legacy mode to Mule 4.1.x and 4.2.x) org.mule.runtime.scheduler.SchedulerPoolStrategy=UBER ``` ### UBER Scheduling Strategy When the strategy is set to `UBER`, the following configuration applies: - `org.mule.runtime.scheduler.uber.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.uber.workQueue.size=0` - `org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.coreSize=cores # The maximum number of threads to allow in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding tasks in the uber pool before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.workQueue.size=0 # When the number of threads in the uber pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000 ``` ### DEDICATED Scheduling Strategy When the strategy is set to `DEDICATED`, the parameters from the default UBER strategy are ignored. To enable this configuration, uncomment the following parameters in your `schedulers-pools.conf` file: - `org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuLight.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.io.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000` - `org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the cpu_lite pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores # The size of the queue to use for holding cpu_lite tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.workQueue.size=0 # The number of threads to keep in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.coreSize=cores # The maximum number of threads to allow in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding I/O tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.workQueue.size=0 # When the number of threads in the I/O pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000 # The number of threads to keep in the cpu_intensive pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores # The size of the queue to use for holding cpu_intensive tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores ``` #### Considerations MuleSoft doesn’t recommend changing the used pool strategy nor change its configuration values. Note that the configuration is global and affects the entire Mule Runtime instance. MuleSoft recommends that you perform load and stress testing with all applications involved in real-life scenarios to validate any change in the threading configurations and to understand how the thread pools work in Mule 4. ### Configuration at the Application Level You can define the pool strategy to use in an application by adding the following to your application code: ```xml ``` The `poolStrategy` parameter exists for backward compatibility, enabling you to revert to the three pools scheme from earlier Mule versions: ```xml ``` #### Considerations Applying pool configurations at the application level causes Mule to create a completely new set of thread pools for the Mule app. This configuration does not change the default settings in `scheduler-conf.properties`, which is particularly important for on-premises deployments in which many Mule apps are deployed to the same Mule instance. MuleSoft recommends running Mule using default settings. If you upgrade from Mule 4.1.x or Mule 4.2.x you can use the DEDICATED strategy so that any customizations to `scheduler-conf.properties` are still used. However, MuleSoft recommends to test the new default setting to determine whether the optimizations are still required. Also, try first to customize the new UBER strategy before reverting to the legacy mode. > [!NOTE] If you define pool configurations at the application level for Mule apps deployed to > CloudHub, be mindful about worker sizes because fractional vCores have less memory. See > [CloudHub Workers](https://docs.mulesoft.com/cloudhub/cloudhub-architecture#cloudhub-workers) for more details. ## Custom Thread Pools Besides the unique UBER thread pool, some components might create additional pools for specific purposes: - NIO Selectors Enables nonblocking I/O. Each connector can create as many as required. - Recurring tasks pools Some connectors or components (expiration monitors, queue consumers, and so on) might create specific pools to perform recurring tasks. ## Back-Pressure Management Back pressure can occur when, under heavy load, Mule does not have resources available to process a specific event. This issue might occur because all threads are busy and cannot perform the handoff of the newly arrived event, or because the current flow’s `maxConcurrency` value has been exceeded already. If Mule cannot handle an event, it logs the condition with the message `Flow 'flowName' is unable to accept new events at this time`. Mule also notifies the flow source, to perform any required actions. The actions that Mule performs as a result of back-pressure are specific to each connector’s source. For example, `http:listener` might return a `503` error code, while a message-broker listener might provide the option to either wait for resources to be available or drop the message. In some cases, a source might disconnect from a remote system to avoid getting more data than it can process and then reconnect after the server state is normalized. ## Upgrading from Mule 4.2 or 4.1 If you are upgrading from Mule 4.2.x or 4.1.x to Mule 4.3.x, take the following actions: - If no custom threading settings are applied (either through `scheduler-pools.conf` or directly in the Mule app), then no action is required. - If custom threading configurations are applied, test your Mule applications using the default configuration. Because of the UBER pool strategy and other performance updates implemented in Mule 4.3, you might not need custom threading configurations. - If tests confirm that a custom configuration is still necessary, a problem might exist with resource management in the application, one of the application dependencies, or the Mule instance. Using a custom configuration can lead to inefficient use of resources and might hide underlying issues. ## Troubleshooting When troubleshooting a Mule app, consider thread naming conventions. For example, consider this flow: ```xml ``` After execution, the flow produces the following log: ERROR 2020-03-12 19:13:45,292 \[\[MuleRuntime\].uber.07: \[echo\].echoFlow.CPU\_LITE @63e7e52c\] \[event: bd56a240-64ae-11ea-8f7d-f01898419bde\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: request at 2020-03-12T19:13:45.283-03:00\[America/Argentina/Buenos\_Aires\] In this case, the thread name is `uber.07`. Mule also logs the type of the operation, which in this case is `CPU_LITE`. Thread names also show up on thread dumps or when using a profiler: ![Thread dumps in profiler](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-thread-profiler.png) --- product: Mule Runtime version: 4.4 keywords: mule, threading, scheduler, non-blocking --- # Execution Engine > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine implements a reactive execution engine, tuned for nonblocking and asynchronous execution. To see more details about reactive programming, visit [https://en.wikipedia.org/wiki/Reactive\_programming](https://en.wikipedia.org/wiki/Reactive_programming). This task-oriented execution model enables you to take advantage of nonblocking I/O at high concurrency levels transparently, meaning you don’t need to account for threading or asynchronicity in your flows. Each operation inside a Mule flow is a task that provides metadata about its execution, and Mule makes tuning decisions based on that metadata. Mule event processors indicate to Mule whether they are CPU-intensive, CPU-light, or I/O-intensive operations. These workload types help Mule tune for different workloads, so you don’t need to manage thread pools manually to achieve optimum performance. Instead, Mule introspects the available resources (such as memory and CPU cores) in the system to tune thread pools automatically. ## Processing Types Mule event processors indicate to Mule what kind of work they do, which can be one of: - CPU-Light For quick operations (around 10 ms), or nonblocking I/O, for example, a Logger (`logger`) or HTTP Request operation (`http:request`). These tasks should not perform any blocking I/O activities. The applicable strings in the logs are `CPU_LIGHT` and `CPU_LIGHT_ASYNC`. - Blocking I/O For I/O that blocks the calling thread, for example, a Database Select operation (`db:select`) or a SFTP read (`sftp:read`) . Applicable strings in the logs are `BLOCKING` and `IO`. - CPU Intensive For CPU-bound computations, usually taking more than 10 ms to execute. These tasks should not perform any I/O activities. One example is the Transform Message component (`ee:transform`). The applicable string in the logs is `CPU_INTENSIVE`. See specific component or module documentation to learn the processing type it supports. If none is specified, the default type is CPU Light. For connectors created with the Mule SDK, the SDK determines the most appropriate processing type based on how the connector is implemented. For details on that mechanism, refer to the [Mule SDK documentation](https://docs.mulesoft.com/mule-sdk/latest/). ## Threading Starting in Mule 4.3, Mule contains one unique thread pool, called the UBER pool. This thread pool is managed by Mule and shared across all apps in the same Mule instance. At startup, Mule introspects the available resources (such as memory and CPU cores) in the system and tunes automatically for the environment where Mule is running. This algorithm was established through performance testing and found optimal values for most scenarios. This single thread pool allows Mule to be efficient, requiring significantly fewer threads (and their inherent memory footprint) to process a given workload when compared to Mule 3. > [!NOTE] If you are upgrading from earlier Mule 4.x versions, see > [Threading in Mule 4.2](#threading) to understand the differences applied to the threading model > in Mule 4.3. ### Proactor Pattern Proactor is a design pattern for asynchronous execution. To understand how the Proactor design pattern works, visit [https://en.wikipedia.org/wiki/Proactor\_pattern](https://en.wikipedia.org/wiki/Proactor_pattern) According to this design pattern, tasks are classified in categories that correspond to Mule processing types, and each task is submitted for execution to the UBER pool. Performance testing shows that applying the Proactor pattern leads to better performance, even with one unique thread pool, because it allows threads to return to the main loop more quickly, allowing the system to continue to accept new work while the I/O tasks are blocked and waiting. ### Transactions When there’s an active transaction, all thread switches are suspended. Event processors participating in the transaction are executed in the same thread. ## Configuration The thread pool is automatically configured by Mule at startup, applying formulas that consider available resources such as CPU and memory. If you run Mule runtime engine on premises, you can modify these global formulas by editing the `MULE_HOME/conf/schedulers-pools.conf` file in your local Mule instance. This configuration file contains comments that document each of the properties, but depending on your pool strategy, you can configure specific properties. Configure the `org.mule.runtime.scheduler.SchedulerPoolStrategy` parameter to switch between the two available strategies: - UBER Unified scheduling strategy. Default. - DEDICATED Separated pools strategy. Legacy. ```properties # The strategy to be used for managing the thread pools that back the 3 types of schedulers in the Mule Runtime # (cpu_light, cpu_intensive and I/O). # Possible values are: # - UBER: All three scheduler types will be backed by one uber uber thread pool (default since 4.3.0) # - DEDICATED: Each scheduler type is backed by its own Thread pool (legacy mode to Mule 4.1.x and 4.2.x) org.mule.runtime.scheduler.SchedulerPoolStrategy=UBER ``` ### UBER Scheduling Strategy When the strategy is set to `UBER`, the following configuration applies: - `org.mule.runtime.scheduler.uber.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.uber.workQueue.size=0` - `org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.coreSize=cores # The maximum number of threads to allow in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding tasks in the uber pool before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.workQueue.size=0 # When the number of threads in the uber pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000 ``` ### DEDICATED Scheduling Strategy When the strategy is set to `DEDICATED`, the parameters from the default UBER strategy are ignored. To enable this configuration, uncomment the following parameters in your `schedulers-pools.conf` file: - `org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuLight.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.io.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000` - `org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the cpu_lite pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores # The size of the queue to use for holding cpu_lite tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.workQueue.size=0 # The number of threads to keep in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.coreSize=cores # The maximum number of threads to allow in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding I/O tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.workQueue.size=0 # When the number of threads in the I/O pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000 # The number of threads to keep in the cpu_intensive pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores # The size of the queue to use for holding cpu_intensive tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores ``` #### Considerations MuleSoft doesn’t recommend changing the used pool strategy nor change its configuration values. Note that the configuration is global and affects the entire Mule Runtime instance. MuleSoft recommends that you perform load and stress testing with all applications involved in real-life scenarios to validate any change in the threading configurations and to understand how the thread pools work in Mule 4. ### Configuration at the Application Level You can define the pool strategy to use in an application by adding the following to your application code: ```xml ``` The `poolStrategy` parameter exists for backward compatibility, enabling you to revert to the three pools scheme from earlier Mule versions: ```xml ``` The `gracefulShutdownTimeout` parameter specifies the maximum time (in milliseconds) to wait until all tasks in all the artifact thread pools have completed execution when stopping the scheduler service. The following table describes the configurable properties and includes the XML attribute for each field.
Property NameXMLDescription

Pool Size

poolSize

The number of threads to keep in the pool, even if they are idle.

Queue Size

queueSize

The size of the queue to use for holding tasks before they are executed.

Core Pool Size

corePoolSize

The number of threads to keep in the pool.

Max Pool Size

maxPoolSize

The maximum number of threads to allow in the pool.

Keep Alive

keepAlive

When the number of threads in the pool is greater than the indicated core pool size, this value sets the maximum time (in milliseconds) for excess idle threads to wait for new tasks before terminating.

#### Considerations Applying pool configurations at the application level causes Mule to create a completely new set of thread pools for the Mule app. This configuration does not change the default settings in `scheduler-conf.properties`, which is particularly important for on-premises deployments in which many Mule apps are deployed to the same Mule instance. MuleSoft recommends running Mule using default settings. If you upgrade from Mule 4.1.x or Mule 4.2.x you can use the DEDICATED strategy so that any customizations to `scheduler-conf.properties` are still used. However, MuleSoft recommends to test the new default setting to determine whether the optimizations are still required. Also, try first to customize the new UBER strategy before reverting to the legacy mode. > [!NOTE] If you define pool configurations at the application level for Mule apps deployed to > CloudHub, be mindful about worker sizes because fractional vCores have less memory. See > [CloudHub Workers](https://docs.mulesoft.com/cloudhub/cloudhub-architecture#cloudhub-workers) for more details. ## Custom Thread Pools Besides the unique UBER thread pool, some components might create additional pools for specific purposes: - NIO Selectors Enables nonblocking I/O. Each connector can create as many as required. - Recurring tasks pools Some connectors or components (expiration monitors, queue consumers, and so on) might create specific pools to perform recurring tasks. ## Back-Pressure Management Back pressure can occur when, under heavy load, Mule does not have resources available to process a specific event. This issue might occur because all threads are busy and cannot perform the handoff of the newly arrived event, or because the current flow’s `maxConcurrency` value has been exceeded already. If Mule cannot handle an event, it logs the condition with the message `Flow 'flowName' is unable to accept new events at this time`. Mule also notifies the flow source, to perform any required actions. The actions that Mule performs as a result of back-pressure are specific to each connector’s source. For example, `http:listener` might return a `503` error code, while a message-broker listener might provide the option to either wait for resources to be available or drop the message. In some cases, a source might disconnect from a remote system to avoid getting more data than it can process and then reconnect after the server state is normalized. ## Upgrading from Mule 4.2 or 4.1 When upgrading from Mule 4.2.x or 4.1.x to Mule 4.3.x or later, take the following actions: - If no custom threading settings are applied (either through `scheduler-pools.conf` or directly in the Mule app), then no action is required. - If custom threading configurations are applied, test your Mule applications using the default configuration. Because of the UBER pool strategy and other performance updates implemented in Mule 4.3, you might not need custom threading configurations. - If tests confirm that a custom configuration is still necessary, a problem might exist with resource management in the application, one of the application dependencies, or the Mule instance. Using a custom configuration can lead to inefficient use of resources and might hide underlying issues. ## Troubleshooting When troubleshooting a Mule app, consider thread naming conventions. For example, consider this flow: ```xml ``` After execution, the flow produces the following log: ERROR 2020-03-12 19:13:45,292 \[\[MuleRuntime\].uber.07: \[echo\].echoFlow.CPU\_LITE @63e7e52c\] \[event: bd56a240-64ae-11ea-8f7d-f01898419bde\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: request at 2020-03-12T19:13:45.283-03:00\[America/Argentina/Buenos\_Aires\] In this case, the thread name is `uber.07`. Mule also logs the type of the operation, which in this case is `CPU_LITE`. Thread names also show up on thread dumps or when using a profiler: ![Thread dumps in profiler](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-thread-profiler.png) --- product: Mule Runtime version: 4.6 keywords: mule, threading, scheduler, non-blocking --- # Execution Engine > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine implements a reactive execution engine, tuned for nonblocking and asynchronous execution. To see more details about reactive programming, visit [https://en.wikipedia.org/wiki/Reactive\_programming](https://en.wikipedia.org/wiki/Reactive_programming). This task-oriented execution model enables you to take advantage of nonblocking I/O at high concurrency levels transparently, meaning you don’t need to account for threading or asynchronicity in your flows. Each operation inside a Mule flow is a task that provides metadata about its execution, and Mule makes tuning decisions based on that metadata. Mule event processors indicate to Mule whether they are CPU-intensive, CPU-light, or I/O-intensive operations. These workload types help Mule tune for different workloads, so you don’t need to manage thread pools manually to achieve optimum performance. Instead, Mule introspects the available resources (such as memory and CPU cores) in the system to tune thread pools automatically. ## Processing Types Mule event processors indicate to Mule what kind of work they do, which can be one of: - CPU-Light For quick operations (around 10 ms), or nonblocking I/O, for example, a Logger (`logger`) or HTTP Request operation (`http:request`). These tasks should not perform any blocking I/O activities. The applicable strings in the logs are `CPU_LIGHT` and `CPU_LIGHT_ASYNC`. - Blocking I/O For I/O that blocks the calling thread, for example, a Database Select operation (`db:select`) or a SFTP read (`sftp:read`) . Applicable strings in the logs are `BLOCKING` and `IO`. - CPU Intensive For CPU-bound computations, usually taking more than 10 ms to execute. These tasks should not perform any I/O activities. One example is the Transform Message component (`ee:transform`). The applicable string in the logs is `CPU_INTENSIVE`. See specific component or module documentation to learn the processing type it supports. If none is specified, the default type is CPU Light. For connectors created with the Mule SDK, the SDK determines the most appropriate processing type based on how the connector is implemented. For details on that mechanism, refer to the [Mule SDK documentation](https://docs.mulesoft.com/mule-sdk/latest/). ## Threading Starting in Mule 4.3, Mule contains one unique thread pool, called the UBER pool. This thread pool is managed by Mule and shared across all apps in the same Mule instance. At startup, Mule introspects the available resources (such as memory and CPU cores) in the system and tunes automatically for the environment where Mule is running. This algorithm was established through performance testing and found optimal values for most scenarios. This single thread pool allows Mule to be efficient, requiring significantly fewer threads (and their inherent memory footprint) to process a given workload when compared to previous versions. > [!NOTE] If you are upgrading from earlier Mule versions, see [Threading in Mule 4.2](#threading) > to understand the differences applied to the threading model in Mule 4.3. ### Proactor Pattern Proactor is a design pattern for asynchronous execution. To understand how the Proactor design pattern works, visit [https://en.wikipedia.org/wiki/Proactor\_pattern](https://en.wikipedia.org/wiki/Proactor_pattern) According to this design pattern, tasks are classified in categories that correspond to Mule processing types, and each task is submitted for execution to the UBER pool. Performance testing shows that applying the Proactor pattern leads to better performance, even with one unique thread pool, because it allows threads to return to the main loop more quickly, allowing the system to continue to accept new work while the I/O tasks are blocked and waiting. ### Transactions When there’s an active transaction, all thread switches are suspended. Event processors participating in the transaction are executed in the same thread. ## Configuration The thread pool is automatically configured by Mule at startup, applying formulas that consider available resources such as CPU and memory. If you run Mule runtime engine on premises, you can modify these global formulas by editing the `MULE_HOME/conf/schedulers-pools.conf` file in your local Mule instance. This configuration file contains comments that document each of the properties, but depending on your pool strategy, you can configure specific properties. Configure the `org.mule.runtime.scheduler.SchedulerPoolStrategy` parameter to switch between the two available strategies: - UBER Unified scheduling strategy. Default. - DEDICATED Separated pools strategy. Legacy. ```properties # The strategy to be used for managing the thread pools that back the 3 types of schedulers in the Mule Runtime # (cpu_light, cpu_intensive and I/O). # Possible values are: # - UBER: All three scheduler types will be backed by one uber uber thread pool (default since 4.3.0) # - DEDICATED: Each scheduler type is backed by its own Thread pool (legacy mode to Mule 4.1.x and 4.2.x) org.mule.runtime.scheduler.SchedulerPoolStrategy=UBER ``` ### UBER Scheduling Strategy When the strategy is set to `UBER`, the following configuration applies: - `org.mule.runtime.scheduler.uber.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.uber.workQueue.size=0` - `org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.coreSize=cores # The maximum number of threads to allow in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding tasks in the uber pool before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.workQueue.size=0 # When the number of threads in the uber pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000 ``` ### DEDICATED Scheduling Strategy When the strategy is set to `DEDICATED`, the parameters from the default UBER strategy are ignored. To enable this configuration, uncomment the following parameters in your `schedulers-pools.conf` file: - `org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuLight.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.io.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000` - `org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the cpu_lite pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores # The size of the queue to use for holding cpu_lite tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.workQueue.size=0 # The number of threads to keep in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.coreSize=cores # The maximum number of threads to allow in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding I/O tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.workQueue.size=0 # When the number of threads in the I/O pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000 # The number of threads to keep in the cpu_intensive pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores # The size of the queue to use for holding cpu_intensive tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores ``` #### Considerations MuleSoft doesn’t recommend changing the used pool strategy nor change its configuration values. Note that the configuration is global and affects the entire Mule Runtime instance. MuleSoft recommends that you perform load and stress testing with all applications involved in real-life scenarios to validate any change in the threading configurations and to understand how the thread pools work in Mule 4. ### Configuration at the Application Level You can define the pool strategy to use in an application by adding the following to your application code: ```xml ``` The `poolStrategy` parameter exists for backward compatibility, enabling you to revert to the three pools scheme from earlier Mule versions: ```xml ``` The `gracefulShutdownTimeout` parameter specifies the maximum time (in milliseconds) to wait until all tasks in all the artifact thread pools have completed execution when stopping the scheduler service. The following table describes the configurable properties and includes the XML attribute for each field.
Property NameXMLDescription

Pool Size

poolSize

The number of threads to keep in the pool, even if they are idle.

Queue Size

queueSize

The size of the queue to use for holding tasks before they are executed.

Core Pool Size

corePoolSize

The number of threads to keep in the pool.

Max Pool Size

maxPoolSize

The maximum number of threads to allow in the pool.

Keep Alive

keepAlive

When the number of threads in the pool is greater than the indicated core pool size, this value sets the maximum time (in milliseconds) for excess idle threads to wait for new tasks before terminating.

#### Considerations Applying pool configurations at the application level causes Mule to create a completely new set of thread pools for the Mule app. This configuration does not change the default settings in `scheduler-conf.properties`, which is particularly important for on-premises deployments in which many Mule apps are deployed to the same Mule instance. MuleSoft recommends running Mule using default settings. If you upgrade from Mule 4.1.x or Mule 4.2.x you can use the DEDICATED strategy so that any customizations to `scheduler-conf.properties` are still used. However, MuleSoft recommends to test the new default setting to determine whether the optimizations are still required. Also, try first to customize the new UBER strategy before reverting to the legacy mode. > [!NOTE] If you define pool configurations at the application level for Mule apps deployed to > CloudHub, be mindful about worker sizes because fractional vCores have less memory. See > [CloudHub Workers](https://docs.mulesoft.com/cloudhub/cloudhub-architecture#cloudhub-workers) for more details. ## Custom Thread Pools Besides the unique UBER thread pool, some components might create additional pools for specific purposes: - NIO Selectors Enables nonblocking I/O. Each connector can create as many as required. - Recurring tasks pools Some connectors or components (expiration monitors, queue consumers, and so on) might create specific pools to perform recurring tasks. ## Back-Pressure Management Back pressure can occur when, under heavy load, Mule does not have resources available to process a specific event. This issue might occur because all threads are busy and cannot perform the handoff of the newly arrived event, or because the current flow’s `maxConcurrency` value has been exceeded already. If Mule cannot handle an event, it logs the condition with the message `Flow 'flowName' is unable to accept new events at this time`. Mule also notifies the flow source, to perform any required actions. The actions that Mule performs as a result of back-pressure are specific to each connector’s source. For example, `http:listener` might return a `503` error code, while a message-broker listener might provide the option to either wait for resources to be available or drop the message. In some cases, a source might disconnect from a remote system to avoid getting more data than it can process and then reconnect after the server state is normalized. ## Upgrading from Mule 4.2 or 4.1 When upgrading from Mule 4.2.x or 4.1.x to Mule 4.3.x or later, take the following actions: - If no custom threading settings are applied (either through `scheduler-pools.conf` or directly in the Mule app), then no action is required. - If custom threading configurations are applied, test your Mule applications using the default configuration. Because of the UBER pool strategy and other performance updates implemented in Mule 4.3, you might not need custom threading configurations. - If tests confirm that a custom configuration is still necessary, a problem might exist with resource management in the application, one of the application dependencies, or the Mule instance. Using a custom configuration can lead to inefficient use of resources and might hide underlying issues. ## Troubleshooting When troubleshooting a Mule app, consider thread naming conventions. For example, consider this flow: ```xml ``` After execution, the flow produces the following log: ERROR 2020-03-12 19:13:45,292 \[\[MuleRuntime\].uber.07: \[echo\].echoFlow.CPU\_LITE @63e7e52c\] \[event: bd56a240-64ae-11ea-8f7d-f01898419bde\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: request at 2020-03-12T19:13:45.283-03:00\[America/Argentina/Buenos\_Aires\] In this case, the thread name is `uber.07`. Mule also logs the type of the operation, which in this case is `CPU_LITE`. Thread names also show up on thread dumps or when using a profiler: ![Thread dumps in profiler](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-thread-profiler.png) --- product: Mule Runtime version: 4.9 keywords: mule, threading, scheduler, non-blocking --- # Execution Engine > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine implements a reactive execution engine, tuned for nonblocking and asynchronous execution. To see more details about reactive programming, visit [https://en.wikipedia.org/wiki/Reactive\_programming](https://en.wikipedia.org/wiki/Reactive_programming). This task-oriented execution model enables you to take advantage of nonblocking I/O at high concurrency levels transparently, meaning you don’t need to account for threading or asynchronicity in your flows. Each operation inside a Mule flow is a task that provides metadata about its execution, and Mule makes tuning decisions based on that metadata. Mule event processors indicate to Mule whether they are CPU-intensive, CPU-light, or I/O-intensive operations. These workload types help Mule tune for different workloads, so you don’t need to manage thread pools manually to achieve optimum performance. Instead, Mule introspects the available resources (such as memory and CPU cores) in the system to tune thread pools automatically. ## Processing Types Mule event processors indicate to Mule what kind of work they do, which can be one of: - CPU-Light For quick operations (around 10 ms), or nonblocking I/O, for example, a Logger (`logger`) or HTTP Request operation (`http:request`). These tasks should not perform any blocking I/O activities. The applicable strings in the logs are `CPU_LIGHT` and `CPU_LIGHT_ASYNC`. - Blocking I/O For I/O that blocks the calling thread, for example, a Database Select operation (`db:select`) or a SFTP read (`sftp:read`) . Applicable strings in the logs are `BLOCKING` and `IO`. - CPU Intensive For CPU-bound computations, usually taking more than 10 ms to execute. These tasks should not perform any I/O activities. One example is the Transform Message component (`ee:transform`). The applicable string in the logs is `CPU_INTENSIVE`. See specific component or module documentation to learn the processing type it supports. If none is specified, the default type is CPU Light. For connectors created with the Mule SDK, the SDK determines the most appropriate processing type based on how the connector is implemented. For details on that mechanism, refer to the [Mule SDK documentation](https://docs.mulesoft.com/mule-sdk/latest/). ## Threading Starting in Mule 4.3, Mule contains one unique thread pool, called the UBER pool. This thread pool is managed by Mule and shared across all apps in the same Mule instance. At startup, Mule introspects the available resources (such as memory and CPU cores) in the system and tunes automatically for the environment where Mule is running. This algorithm was established through performance testing and found optimal values for most scenarios. This single thread pool allows Mule to be efficient, requiring significantly fewer threads (and their inherent memory footprint) to process a given workload when compared to previous versions. > [!NOTE] If you are upgrading from earlier Mule versions, see [Threading in Mule 4.2](#threading) > to understand the differences applied to the threading model in Mule 4.3. ### Proactor Pattern Proactor is a design pattern for asynchronous execution. To understand how the Proactor design pattern works, visit [https://en.wikipedia.org/wiki/Proactor\_pattern](https://en.wikipedia.org/wiki/Proactor_pattern) According to this design pattern, tasks are classified in categories that correspond to Mule processing types, and each task is submitted for execution to the UBER pool. Performance testing shows that applying the Proactor pattern leads to better performance, even with one unique thread pool, because it allows threads to return to the main loop more quickly, allowing the system to continue to accept new work while the I/O tasks are blocked and waiting. ### Transactions When there’s an active transaction, all thread switches are suspended. Event processors participating in the transaction are executed in the same thread. ## Configuration The thread pool is automatically configured by Mule at startup, applying formulas that consider available resources such as CPU and memory. If you run Mule runtime engine on premises, you can modify these global formulas by editing the `MULE_HOME/conf/schedulers-pools.conf` file in your local Mule instance. This configuration file contains comments that document each of the properties, but depending on your pool strategy, you can configure specific properties. Configure the `org.mule.runtime.scheduler.SchedulerPoolStrategy` parameter to switch between the two available strategies: - UBER Unified scheduling strategy. Default. - DEDICATED Separated pools strategy. Legacy. ```properties # The strategy to be used for managing the thread pools that back the 3 types of schedulers in the Mule Runtime # (cpu_light, cpu_intensive and I/O). # Possible values are: # - UBER: All three scheduler types will be backed by one uber thread pool (default since 4.3.0) # - DEDICATED: Each scheduler type is backed by its own Thread pool (legacy mode to Mule 4.1.x and 4.2.x) org.mule.runtime.scheduler.SchedulerPoolStrategy=UBER ``` ### UBER Scheduling Strategy When the strategy is set to `UBER`, the following configuration applies: - `org.mule.runtime.scheduler.uber.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.uber.workQueue.size=0` - `org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.coreSize=cores # The maximum number of threads to allow in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding tasks in the uber pool before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.workQueue.size=0 # When the number of threads in the uber pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000 ``` ### DEDICATED Scheduling Strategy When the strategy is set to `DEDICATED`, the parameters from the default UBER strategy are ignored. To enable this configuration, uncomment the following parameters in your `schedulers-pools.conf` file: - `org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuLight.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.io.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000` - `org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the cpu_lite pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores # The size of the queue to use for holding cpu_lite tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.workQueue.size=0 # The number of threads to keep in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.coreSize=cores # The maximum number of threads to allow in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding I/O tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.workQueue.size=0 # When the number of threads in the I/O pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000 # The number of threads to keep in the cpu_intensive pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores # The size of the queue to use for holding cpu_intensive tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores ``` #### Considerations MuleSoft doesn’t recommend changing the used pool strategy nor change its configuration values. Note that the configuration is global and affects the entire Mule Runtime instance. MuleSoft recommends that you perform load and stress testing with all applications involved in real-life scenarios to validate any change in the threading configurations and to understand how the thread pools work in Mule 4. ### Configuration at the Application Level You can define the pool strategy to use in an application by adding the following to your application code: ```xml ``` The `poolStrategy` parameter exists for backward compatibility, enabling you to revert to the three pools scheme from earlier Mule versions: ```xml ``` The `gracefulShutdownTimeout` parameter specifies the maximum time (in milliseconds) to wait until all tasks in all the artifact thread pools have completed execution when stopping the scheduler service. The following table describes the configurable properties and includes the XML attribute for each field.
Property NameXMLDescription

Pool Size

poolSize

The number of threads to keep in the pool, even if they are idle.

Queue Size

queueSize

The size of the queue to use for holding tasks before they are executed.

Core Pool Size

corePoolSize

The number of threads to keep in the pool.

Max Pool Size

maxPoolSize

The maximum number of threads to allow in the pool.

Keep Alive

keepAlive

When the number of threads in the pool is greater than the indicated core pool size, this value sets the maximum time (in milliseconds) for excess idle threads to wait for new tasks before terminating.

#### Considerations Applying pool configurations at the application level causes Mule to create a completely new set of thread pools for the Mule app. This configuration does not change the default settings in `scheduler-conf.properties`, which is particularly important for on-premises deployments in which many Mule apps are deployed to the same Mule instance. MuleSoft recommends running Mule using default settings. If you upgrade from Mule 4.1.x or Mule 4.2.x you can use the DEDICATED strategy so that any customizations to `scheduler-conf.properties` are still used. However, MuleSoft recommends to test the new default setting to determine whether the optimizations are still required. Also, try first to customize the new UBER strategy before reverting to the legacy mode. > [!NOTE] If you define pool configurations at the application level for Mule apps deployed to > CloudHub, be mindful about worker sizes because fractional vCores have less memory. See > [CloudHub Workers](https://docs.mulesoft.com/cloudhub/cloudhub-architecture#cloudhub-workers) for more details. ## Custom Thread Pools Besides the unique UBER thread pool, some components might create additional pools for specific purposes: - NIO Selectors Enables nonblocking I/O. Each connector can create as many as required. - Recurring tasks pools Some connectors or components (expiration monitors, queue consumers, and so on) might create specific pools to perform recurring tasks. ## Back-Pressure Management Back pressure can occur when, under heavy load, Mule does not have resources available to process a specific event. This issue might occur because all threads are busy and cannot perform the handoff of the newly arrived event, or because the current flow’s `maxConcurrency` value has been exceeded already. If Mule cannot handle an event, it logs the condition with the message `Flow 'flowName' is unable to accept new events at this time`. Mule also notifies the flow source, to perform any required actions. The actions that Mule performs as a result of back-pressure are specific to each connector’s source. For example, `http:listener` might return a `503` error code, while a message-broker listener might provide the option to either wait for resources to be available or drop the message. In some cases, a source might disconnect from a remote system to avoid getting more data than it can process and then reconnect after the server state is normalized. ## Upgrading from Mule 4.2 or 4.1 When upgrading from Mule 4.2.x or 4.1.x to Mule 4.3.x or later, take the following actions: - If no custom threading settings are applied (either through `scheduler-pools.conf` or directly in the Mule app), then no action is required. - If custom threading configurations are applied, test your Mule applications using the default configuration. Because of the UBER pool strategy and other performance updates implemented in Mule 4.3, you might not need custom threading configurations. - If tests confirm that a custom configuration is still necessary, a problem might exist with resource management in the application, one of the application dependencies, or the Mule instance. Using a custom configuration can lead to inefficient use of resources and might hide underlying issues. ## Troubleshooting When troubleshooting a Mule app, consider thread naming conventions. For example, consider this flow: ```xml ``` After execution, the flow produces the following log: ERROR 2020-03-12 19:13:45,292 \[\[MuleRuntime\].uber.07: \[echo\].echoFlow.CPU\_LITE @63e7e52c\] \[event: bd56a240-64ae-11ea-8f7d-f01898419bde\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: request at 2020-03-12T19:13:45.283-03:00\[America/Argentina/Buenos\_Aires\] In this case, the thread name is `uber.07`. Mule also logs the type of the operation, which in this case is `CPU_LITE`. Thread names also show up on thread dumps or when using a profiler: ![A table listing thread groups in a profiling tool](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-thread-profiler.png) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: mule, threading, scheduler, non-blocking --- # Execution Engine > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine implements a reactive execution engine, tuned for nonblocking and asynchronous execution. To see more details about reactive programming, visit [https://en.wikipedia.org/wiki/Reactive\_programming](https://en.wikipedia.org/wiki/Reactive_programming). This task-oriented execution model enables you to take advantage of nonblocking I/O at high concurrency levels transparently, meaning you don’t need to account for threading or asynchronicity in your flows. Each operation inside a Mule flow is a task that provides metadata about its execution, and Mule makes tuning decisions based on that metadata. Mule event processors indicate to Mule whether they are CPU-intensive, CPU-light, or I/O-intensive operations. These workload types help Mule tune for different workloads, so you don’t need to manage thread pools manually to achieve optimum performance. Instead, Mule introspects the available resources (such as memory and CPU cores) in the system to tune thread pools automatically. ## Processing Types Mule event processors indicate to Mule what kind of work they do, which can be one of: - CPU-Light For quick operations (around 10 ms), or nonblocking I/O, for example, a Logger (`logger`) or HTTP Request operation (`http:request`). These tasks should not perform any blocking I/O activities. The applicable strings in the logs are `CPU_LIGHT` and `CPU_LIGHT_ASYNC`. - Blocking I/O For I/O that blocks the calling thread, for example, a Database Select operation (`db:select`) or a SFTP read (`sftp:read`) . Applicable strings in the logs are `BLOCKING` and `IO`. - CPU Intensive For CPU-bound computations, usually taking more than 10 ms to execute. These tasks should not perform any I/O activities. One example is the Transform Message component (`ee:transform`). The applicable string in the logs is `CPU_INTENSIVE`. See specific component or module documentation to learn the processing type it supports. If none is specified, the default type is CPU Light. For connectors created with the Mule SDK, the SDK determines the most appropriate processing type based on how the connector is implemented. For details on that mechanism, refer to the [Mule SDK documentation](https://docs.mulesoft.com/mule-sdk/latest/). ## Threading Starting in Mule 4.3, Mule contains one unique thread pool, called the UBER pool. This thread pool is managed by Mule and shared across all apps in the same Mule instance. At startup, Mule introspects the available resources (such as memory and CPU cores) in the system and tunes automatically for the environment where Mule is running. This algorithm was established through performance testing and found optimal values for most scenarios. This single thread pool allows Mule to be efficient, requiring significantly fewer threads (and their inherent memory footprint) to process a given workload when compared to previous versions. > [!NOTE] If you are upgrading from earlier Mule versions, see [Threading in Mule 4.2](#threading) > to understand the differences applied to the threading model in Mule 4.3. ### Proactor Pattern Proactor is a design pattern for asynchronous execution. To understand how the Proactor design pattern works, visit [https://en.wikipedia.org/wiki/Proactor\_pattern](https://en.wikipedia.org/wiki/Proactor_pattern) According to this design pattern, tasks are classified in categories that correspond to Mule processing types, and each task is submitted for execution to the UBER pool. Performance testing shows that applying the Proactor pattern leads to better performance, even with one unique thread pool, because it allows threads to return to the main loop more quickly, allowing the system to continue to accept new work while the I/O tasks are blocked and waiting. ### Transactions When there’s an active transaction, all thread switches are suspended. Event processors participating in the transaction are executed in the same thread. ## Configuration The thread pool is automatically configured by Mule at startup, applying formulas that consider available resources such as CPU and memory. If you run Mule runtime engine on premises, you can modify these global formulas by editing the `MULE_HOME/conf/schedulers-pools.conf` file in your local Mule instance. This configuration file contains comments that document each of the properties, but depending on your pool strategy, you can configure specific properties. Configure the `org.mule.runtime.scheduler.SchedulerPoolStrategy` parameter to switch between the two available strategies: - UBER Unified scheduling strategy. Default. - DEDICATED Separated pools strategy. Legacy. ```properties # The strategy to be used for managing the thread pools that back the 3 types of schedulers in the Mule Runtime # (cpu_light, cpu_intensive and I/O). # Possible values are: # - UBER: All three scheduler types will be backed by one uber thread pool (default since 4.3.0) # - DEDICATED: Each scheduler type is backed by its own Thread pool (legacy mode to Mule 4.1.x and 4.2.x) org.mule.runtime.scheduler.SchedulerPoolStrategy=UBER ``` ### UBER Scheduling Strategy When the strategy is set to `UBER`, the following configuration applies: - `org.mule.runtime.scheduler.uber.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.uber.workQueue.size=0` - `org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.coreSize=cores # The maximum number of threads to allow in the uber pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding tasks in the uber pool before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER org.mule.runtime.scheduler.uber.workQueue.size=0 # When the number of threads in the uber pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # Only applies when org.mule.runtime.scheduler.threadPool.strategy=UBER # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. org.mule.runtime.scheduler.uber.threadPool.threadKeepAlive=30000 ``` ### DEDICATED Scheduling Strategy When the strategy is set to `DEDICATED`, the parameters from the default UBER strategy are ignored. To enable this configuration, uncomment the following parameters in your `schedulers-pools.conf` file: - `org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuLight.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.coreSize=cores` - `org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120))` - `org.mule.runtime.scheduler.io.workQueue.size=0` - `org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000` - `org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores` - `org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores` Example `schedulers-pools.conf` file: ```properties # The number of threads to keep in the cpu_lite pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.threadPool.size=2*cores # The size of the queue to use for holding cpu_lite tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuLight.workQueue.size=0 # The number of threads to keep in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.coreSize=cores # The maximum number of threads to allow in the I/O pool. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.maxSize=max(2, cores + ((mem - 245760) / 5120)) # The size of the queue to use for holding I/O tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.workQueue.size=0 # When the number of threads in the I/O pool is greater than SchedulerService.io.coreThreadPoolSize, this is the maximum # time (in milliseconds) that excess idle threads will wait for new tasks before terminating. # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.io.threadPool.threadKeepAlive=30000 # The number of threads to keep in the cpu_intensive pool, even if they are idle. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.threadPool.size=2*cores # The size of the queue to use for holding cpu_intensive tasks before they are executed. # Supports Expressions # Only applies when org.mule.runtime.scheduler.threadPool.strategy=DEDICATED org.mule.runtime.scheduler.cpuIntensive.workQueue.size=2*cores ``` #### Considerations MuleSoft doesn’t recommend changing the used pool strategy nor change its configuration values. Note that the configuration is global and affects the entire Mule Runtime instance. MuleSoft recommends that you perform load and stress testing with all applications involved in real-life scenarios to validate any change in the threading configurations and to understand how the thread pools work in Mule 4. ### Configuration at the Application Level You can define the pool strategy to use in an application by adding the following to your application code: ```xml ``` The `poolStrategy` parameter exists for backward compatibility, enabling you to revert to the three pools scheme from earlier Mule versions: ```xml ``` The `gracefulShutdownTimeout` parameter specifies the maximum time (in milliseconds) to wait until all tasks in all the artifact thread pools have completed execution when stopping the scheduler service. The following table describes the configurable properties and includes the XML attribute for each field.
Property NameXMLDescription

Pool Size

poolSize

The number of threads to keep in the pool, even if they are idle.

Queue Size

queueSize

The size of the queue to use for holding tasks before they are executed.

Core Pool Size

corePoolSize

The number of threads to keep in the pool.

Max Pool Size

maxPoolSize

The maximum number of threads to allow in the pool.

Keep Alive

keepAlive

When the number of threads in the pool is greater than the indicated core pool size, this value sets the maximum time (in milliseconds) for excess idle threads to wait for new tasks before terminating.

#### Considerations Applying pool configurations at the application level causes Mule to create a completely new set of thread pools for the Mule app. This configuration does not change the default settings in `scheduler-conf.properties`, which is particularly important for on-premises deployments in which many Mule apps are deployed to the same Mule instance. MuleSoft recommends running Mule using default settings. If you upgrade from Mule 4.1.x or Mule 4.2.x you can use the DEDICATED strategy so that any customizations to `scheduler-conf.properties` are still used. However, MuleSoft recommends to test the new default setting to determine whether the optimizations are still required. Also, try first to customize the new UBER strategy before reverting to the legacy mode. > [!NOTE] If you define pool configurations at the application level for Mule apps deployed to > CloudHub, be mindful about worker sizes because fractional vCores have less memory. See > [CloudHub Workers](https://docs.mulesoft.com/cloudhub/cloudhub-architecture#cloudhub-workers) for more details. ## Custom Thread Pools Besides the unique UBER thread pool, some components might create additional pools for specific purposes: - NIO Selectors Enables nonblocking I/O. Each connector can create as many as required. - Recurring tasks pools Some connectors or components (expiration monitors, queue consumers, and so on) might create specific pools to perform recurring tasks. ## Back-Pressure Management Back pressure can occur when, under heavy load, Mule does not have resources available to process a specific event. This issue might occur because all threads are busy and cannot perform the handoff of the newly arrived event, or because the current flow’s `maxConcurrency` value has been exceeded already. If Mule cannot handle an event, it logs the condition with the message `Flow 'flowName' is unable to accept new events at this time`. Mule also notifies the flow source, to perform any required actions. The actions that Mule performs as a result of back-pressure are specific to each connector’s source. For example, `http:listener` might return a `503` error code, while a message-broker listener might provide the option to either wait for resources to be available or drop the message. In some cases, a source might disconnect from a remote system to avoid getting more data than it can process and then reconnect after the server state is normalized. ## Upgrading from Mule 4.2 or 4.1 When upgrading from Mule 4.2.x or 4.1.x to Mule 4.3.x or later, take the following actions: - If no custom threading settings are applied (either through `scheduler-pools.conf` or directly in the Mule app), then no action is required. - If custom threading configurations are applied, test your Mule applications using the default configuration. Because of the UBER pool strategy and other performance updates implemented in Mule 4.3, you might not need custom threading configurations. - If tests confirm that a custom configuration is still necessary, a problem might exist with resource management in the application, one of the application dependencies, or the Mule instance. Using a custom configuration can lead to inefficient use of resources and might hide underlying issues. ## Troubleshooting When troubleshooting a Mule app, consider thread naming conventions. For example, consider this flow: ```xml ``` After execution, the flow produces the following log: ERROR 2020-03-12 19:13:45,292 \[\[MuleRuntime\].uber.07: \[echo\].echoFlow.CPU\_LITE @63e7e52c\] \[event: bd56a240-64ae-11ea-8f7d-f01898419bde\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: request at 2020-03-12T19:13:45.283-03:00\[America/Argentina/Buenos\_Aires\] In this case, the thread name is `uber.07`. Mule also logs the type of the operation, which in this case is `CPU_LITE`. Thread names also show up on thread dumps or when using a profiler: ![A table listing thread groups in a profiling tool](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-thread-profiler.png) --- product: Mule Runtime version: 4.11 --- # Export Resources > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule Applications, Mule Domains and Mule Policies contain a set of resources which may be properties files, DataWeave transformation files, Java classes, etc. By default, all of these files are internal to the artifact in which they are defined, and as a result, they are inaccessible from other artifacts. For instance, if a resource defined at the domain level is not explicitly exported, then it cannot be accessed from within any of the applications that belong to that shared domain. Another example is classes from an application that are meant to be used by the Java module. If those classes are not exported, then the Java module will not be able to access them. ## How to Export Java Classes To export Java classes, you have to export the complete package that contains them by using the `exportedPackages` field of the `mule-artifact.json` file of your artifact. Individual classes cannot be exported. Use `.api.` when naming public packages and `.internal.` when naming your non-public packages to make them easier to identify. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["org.mule.myapp.api.customer", "org.mule.myapp.api.account"] } } } ``` Any internal dependencies in your Java classes are automatically exported with this configuration. ### Considerations - Export the minimum number of packages required for your application to work This reduces the likelihood of conflicts with other artifacts, such as modules or connectors, that you might be using within your application. - Configure shared libraries if any component in your Mule app needs to access the exported packages Due to the classloading isolation mechanism implemented in Mule, connectors and modules cannot access application dependencies unless these dependencies are configured as shared libraries. ## How to Export Resource Files To export resources, use the `exportedResources` field of the `mule-artifact.json` file for your artifact. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [ "/org/mule/myapp/customer-to-user.dwl", "/org/mule/myapp/beans.xml" ] } } } } ``` > [!IMPORTANT] This same mechanism applies to every artifact, including custom extensions developed > with the Mule SDK. ## See Also - [Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.11/about-classloading-isolation#shared-libraries) - [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.11/mmp-concept#configure-shared-libraries) --- product: Mule Runtime version: 4.12 --- # Export Resources > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule Applications, Mule Domains and Mule Policies contain a set of resources which may be properties files, DataWeave transformation files, Java classes, etc. By default, all of these files are internal to the artifact in which they are defined, and as a result, they are inaccessible from other artifacts. For instance, if a resource defined at the domain level is not explicitly exported, then it cannot be accessed from within any of the applications that belong to that shared domain. Another example is classes from an application that are meant to be used by the Java module. If those classes are not exported, then the Java module will not be able to access them. ## How to Export Java Classes To export Java classes, you have to export the complete package that contains them by using the `exportedPackages` field of the `mule-artifact.json` file of your artifact. Individual classes cannot be exported. Use `.api.` when naming public packages and `.internal.` when naming your non-public packages to make them easier to identify. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["org.mule.myapp.api.customer", "org.mule.myapp.api.account"] } } } ``` Any internal dependencies in your Java classes are automatically exported with this configuration. ### Considerations - Export the minimum number of packages required for your application to work This reduces the likelihood of conflicts with other artifacts, such as modules or connectors, that you might be using within your application. - Configure shared libraries if any component in your Mule app needs to access the exported packages Due to the classloading isolation mechanism implemented in Mule, connectors and modules cannot access application dependencies unless these dependencies are configured as shared libraries. ## How to Export Resource Files To export resources, use the `exportedResources` field of the `mule-artifact.json` file for your artifact. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [ "/org/mule/myapp/customer-to-user.dwl", "/org/mule/myapp/beans.xml" ] } } } } ``` > [!IMPORTANT] This same mechanism applies to every artifact, including custom extensions developed > with the Mule SDK. > [!NOTE] A common case for exporting resource files is a DataWeave script (`.dwl` file) referenced > from a Transform Message component through the `resource` attribute. Starting in Mule 4.5, the > runtime validates the accessibility of these scripts, so export any referenced `.dwl` file that > the runtime needs. For more information, see > [Exporting Referenced DataWeave Files](https://docs.mulesoft.com/mule-runtime/4.12/transform-dataweave-xml-reference#export-referenced-dwl-files). ## See Also - [Adding DataWeave Scripts to the Transform Component](https://docs.mulesoft.com/mule-runtime/4.12/transform-dataweave-xml-reference#adding-dataweave-scripts-to-the-transform-component) - [Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.12/about-classloading-isolation#shared-libraries) - [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.12/mmp-concept#configure-shared-libraries) --- product: Mule Runtime version: 4.3 --- # Export Resources > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule Applications, Mule Domains and Mule Policies contain a set of resources which may be properties files, DataWeave transformation files, Java classes, etc. By default, all of these files are internal to the artifact in which they are defined, and as a result, they are inaccessible from other artifacts. For instance, if a resource defined at the domain level is not explicitly exported, then it cannot be accessed from within any of the applications that belong to that shared domain. Another example is classes from an application that are meant to be used by the Java module. If those classes are not exported, then the Java module will not be able to access them. ## How to Export Java Classes To export Java classes, you have the export the complete package that contains them by using the `exportedPackages` field of the `mule-artifact.json` file of your artifact. Individual classes cannot be exported. Use `.api.` when naming public packages and `.internal.` when naming your non-public packages to make them easier to identify. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["org.mule.myapp.api.customer", "org.mule.myapp.api.account"] } } } ``` Any internal dependencies in your Java classes are automatically exported with this configuration. ### Considerations - Export the minimum number of packages required for your application to work This reduces the likelihood of conflicts with other artifacts, such as modules or connectors, that you might be using within your application. - Configure shared libraries if any component in your Mule app needs to access the exported packages Due to the classloading isolation mechanism implemented in Mule, connectors and modules cannot access application dependencies unless these dependencies are configured as shared libraries. ## How to Export Resource Files To export resources, use the `exportedResources` field of the `mule-artifact.json` file for your artifact. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [ "/org/mule/myapp/customer-to-user.dwl", "/org/mule/myapp/beans.xml" ] } } } } ``` > [!IMPORTANT] This same mechanism applies to every artifact, including custom extensions developed > with the Mule SDK. ## See Also - [Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.3/about-classloading-isolation#shared-libraries) - [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.3/mmp-concept#configure-shared-libraries) --- product: Mule Runtime version: 4.4 --- # Export Resources > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule Applications, Mule Domains and Mule Policies contain a set of resources which may be properties files, DataWeave transformation files, Java classes, etc. By default, all of these files are internal to the artifact in which they are defined, and as a result, they are inaccessible from other artifacts. For instance, if a resource defined at the domain level is not explicitly exported, then it cannot be accessed from within any of the applications that belong to that shared domain. Another example is classes from an application that are meant to be used by the Java module. If those classes are not exported, then the Java module will not be able to access them. ## How to Export Java Classes To export Java classes, you have to export the complete package that contains them by using the `exportedPackages` field of the `mule-artifact.json` file of your artifact. Individual classes cannot be exported. Use `.api.` when naming public packages and `.internal.` when naming your non-public packages to make them easier to identify. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["org.mule.myapp.api.customer", "org.mule.myapp.api.account"] } } } ``` Any internal dependencies in your Java classes are automatically exported with this configuration. ### Considerations - Export the minimum number of packages required for your application to work This reduces the likelihood of conflicts with other artifacts, such as modules or connectors, that you might be using within your application. - Configure shared libraries if any component in your Mule app needs to access the exported packages Due to the classloading isolation mechanism implemented in Mule, connectors and modules cannot access application dependencies unless these dependencies are configured as shared libraries. ## How to Export Resource Files To export resources, use the `exportedResources` field of the `mule-artifact.json` file for your artifact. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [ "/org/mule/myapp/customer-to-user.dwl", "/org/mule/myapp/beans.xml" ] } } } } ``` > [!IMPORTANT] This same mechanism applies to every artifact, including custom extensions developed > with the Mule SDK. ## See Also - [Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.4/about-classloading-isolation#shared-libraries) - [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.4/mmp-concept#configure-shared-libraries) --- product: Mule Runtime version: 4.6 --- # Export Resources > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule Applications, Mule Domains and Mule Policies contain a set of resources which may be properties files, DataWeave transformation files, Java classes, etc. By default, all of these files are internal to the artifact in which they are defined, and as a result, they are inaccessible from other artifacts. For instance, if a resource defined at the domain level is not explicitly exported, then it cannot be accessed from within any of the applications that belong to that shared domain. Another example is classes from an application that are meant to be used by the Java module. If those classes are not exported, then the Java module will not be able to access them. ## How to Export Java Classes To export Java classes, you have to export the complete package that contains them by using the `exportedPackages` field of the `mule-artifact.json` file of your artifact. Individual classes cannot be exported. Use `.api.` when naming public packages and `.internal.` when naming your non-public packages to make them easier to identify. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["org.mule.myapp.api.customer", "org.mule.myapp.api.account"] } } } ``` Any internal dependencies in your Java classes are automatically exported with this configuration. ### Considerations - Export the minimum number of packages required for your application to work This reduces the likelihood of conflicts with other artifacts, such as modules or connectors, that you might be using within your application. - Configure shared libraries if any component in your Mule app needs to access the exported packages Due to the classloading isolation mechanism implemented in Mule, connectors and modules cannot access application dependencies unless these dependencies are configured as shared libraries. ## How to Export Resource Files To export resources, use the `exportedResources` field of the `mule-artifact.json` file for your artifact. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [ "/org/mule/myapp/customer-to-user.dwl", "/org/mule/myapp/beans.xml" ] } } } } ``` > [!IMPORTANT] This same mechanism applies to every artifact, including custom extensions developed > with the Mule SDK. ## See Also - [Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.6/about-classloading-isolation#shared-libraries) - [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.6/mmp-concept#configure-shared-libraries) --- product: Mule Runtime version: 4.9 --- # Export Resources > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule Applications, Mule Domains and Mule Policies contain a set of resources which may be properties files, DataWeave transformation files, Java classes, etc. By default, all of these files are internal to the artifact in which they are defined, and as a result, they are inaccessible from other artifacts. For instance, if a resource defined at the domain level is not explicitly exported, then it cannot be accessed from within any of the applications that belong to that shared domain. Another example is classes from an application that are meant to be used by the Java module. If those classes are not exported, then the Java module will not be able to access them. ## How to Export Java Classes To export Java classes, you have to export the complete package that contains them by using the `exportedPackages` field of the `mule-artifact.json` file of your artifact. Individual classes cannot be exported. Use `.api.` when naming public packages and `.internal.` when naming your non-public packages to make them easier to identify. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["org.mule.myapp.api.customer", "org.mule.myapp.api.account"] } } } ``` Any internal dependencies in your Java classes are automatically exported with this configuration. ### Considerations - Export the minimum number of packages required for your application to work This reduces the likelihood of conflicts with other artifacts, such as modules or connectors, that you might be using within your application. - Configure shared libraries if any component in your Mule app needs to access the exported packages Due to the classloading isolation mechanism implemented in Mule, connectors and modules cannot access application dependencies unless these dependencies are configured as shared libraries. ## How to Export Resource Files To export resources, use the `exportedResources` field of the `mule-artifact.json` file for your artifact. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [ "/org/mule/myapp/customer-to-user.dwl", "/org/mule/myapp/beans.xml" ] } } } } ``` > [!IMPORTANT] This same mechanism applies to every artifact, including custom extensions developed > with the Mule SDK. ## See Also - [Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.9/about-classloading-isolation#shared-libraries) - [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/4.9/mmp-concept#configure-shared-libraries) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Export Resources > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule Applications, Mule Domains and Mule Policies contain a set of resources which may be properties files, DataWeave transformation files, Java classes, etc. By default, all of these files are internal to the artifact in which they are defined, and as a result, they are inaccessible from other artifacts. For instance, if a resource defined at the domain level is not explicitly exported, then it cannot be accessed from within any of the applications that belong to that shared domain. Another example is classes from an application that are meant to be used by the Java module. If those classes are not exported, then the Java module will not be able to access them. ## How to Export Java Classes To export Java classes, you have to export the complete package that contains them by using the `exportedPackages` field of the `mule-artifact.json` file of your artifact. Individual classes cannot be exported. Use `.api.` when naming public packages and `.internal.` when naming your non-public packages to make them easier to identify. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedPackages": ["org.mule.myapp.api.customer", "org.mule.myapp.api.account"] } } } ``` Any internal dependencies in your Java classes are automatically exported with this configuration. ### Considerations - Export the minimum number of packages required for your application to work This reduces the likelihood of conflicts with other artifacts, such as modules or connectors, that you might be using within your application. - Configure shared libraries if any component in your Mule app needs to access the exported packages Due to the classloading isolation mechanism implemented in Mule, connectors and modules cannot access application dependencies unless these dependencies are configured as shared libraries. ## How to Export Resource Files To export resources, use the `exportedResources` field of the `mule-artifact.json` file for your artifact. ```json { "name": "MyApp", "minMuleVersion": "4.0.0", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [ "/org/mule/myapp/customer-to-user.dwl", "/org/mule/myapp/beans.xml" ] } } } } ``` > [!IMPORTANT] This same mechanism applies to every artifact, including custom extensions developed > with the Mule SDK. > [!NOTE] A common case for exporting resource files is a DataWeave script (`.dwl` file) referenced > from a Transform Message component through the `resource` attribute. Starting in Mule 4.5, the > runtime validates the accessibility of these scripts, so export any referenced `.dwl` file that > the runtime needs. For more information, see > [Exporting Referenced DataWeave Files](https://docs.mulesoft.com/mule-runtime/latest/transform-dataweave-xml-reference#export-referenced-dwl-files). ## See Also - [Adding DataWeave Scripts to the Transform Component](https://docs.mulesoft.com/mule-runtime/latest/transform-dataweave-xml-reference#adding-dataweave-scripts-to-the-transform-component) - [Shared Libraries](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#shared-libraries) - [Configure Shared Libraries](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept#configure-shared-libraries) --- product: Mule Runtime version: 4.11 --- # Feature Flagging Mechanism > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine incorporates a feature flagging mechanism that enables Mule applications to change the behavior of the Mule instance depending on the required minimum Mule version. This feature ensures backward compatibility because it allows Mule applications to continue working on later Mule runtime versions, while new Mule applications can benefit from the latest bug fixes implemented in the Mule instance. The feature flagging mechanism is automatic. For each Mule application deployed to a Mule instance, Mule determines which features are enabled or disabled based on the application’s minimum Mule version configured in the application descriptor file (`mule-artifact.json`) of the Mule app. By default, Mule runtime engine disables any new features or bug fixes that aren’t backward compatible with Mule applications running in earlier Mule versions. However, it is possible to manage the feature flags configured for each Mule application or all applications running in the same Mule instance. ## Configure Feature Flags for a Mule Application To configure feature flags for a Mule application, change the `minMuleVersion` value in the `mule-artifact.json` file of your app. This configuration instructs the Mule instance to run this application implementing all features and bug fixes that were released to that particular version and disabling features and bug fixes that are active by default in later Mule versions. For example, you can run a Mule application in Mule 4.5.0 instructing the Mule instance to apply only the features that don’t change core functionality up to Mule 4.1.0: Example `mule-artifact.json` file { "minMuleVersion": "4.1.0" } ## Configure Feature Flags for the Mule Instance An alternative way to configure feature flags is by using system properties. In this case, you can enable or disable each one of the available feature flags. However, configuring feature flags through system properties applies the changes at the Mule instance level, so all applications deployed to this Mule instance behave according to the configured feature flags. Note that this configuration is compatible with on-premise deployments only because you cannot configure system properties in other deployment targets. For example, you can configure a Mule 4.5.0 instance to enable and disable specific features for all applications running on this instance: Example `wrapper.conf` file … wrapper.java.additional.999=-DHONOUR\_RESERVED\_PROPERTIES\_PROPERTY=true wrapper.java.additional.1000=-DCOMPUTE\_CONNECTION\_ERRORS\_IN\_STATS\_PROPERTY=false ## Feature Flags Reference The following table shows the available feature flags, a description of their functionality, the Mule version in which the flag became available, the earlier minor version releases that enable the flag by default, and the issue ID in which the change was implemented:
Feature FlagDescription

mule.batch.fixed.aggregator.transaction.record.buffer

When enabled, batch aggregators with fixed size aggregators commit only when a full block is processed.

Available Since

  • 4.4.0

  • 4.3.0-20210304

  • 4.2.2-20210304

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19218

mule.compute.connection.errors.in.stats

When enabled, connection errors are computed as part of alerts triggering.

Available Since

  • 4.4.0

  • 4.3.0-20210304

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19020

mule.enable.default.errorhandler.not.rollback.incorrect.tx

When enabled, the default error handler added by the Runtime doesn’t roll back a transaction if it doesn’t correspond to have this roll back made.

Available Since

  • 4.5.0

  • 4.4.0-20211227

  • 4.3.0-20211222

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19919

mule.dw.remove_shadowed_implicit_inputs

When enabled, DataWeave removes implicit inputs when a variable with the same name is declared at the root level.

Available Since

  • 4.5.0

  • 4.4.0-20211026

Enabled by Default Since

  • 4.4.0

Issue ID

  • DW-893

mule.enable.policy.isolation

When enabled, Mule manages extensions imported by a policy in complete isolation from the extensions imported by the Mule application. Also, validations prevent the use of explicit configurations that the application declared as part of the policy initialization.

Available Since

  • 4.4.0

  • 4.3.0-20210622

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19226

mule.enable.profiling.service

When enabled, the Runtime profiling capabilities become available.

Available Since

  • 4.4.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19588

mule.entityResolver.failOnFirstError

When enabled, the Mule XML DSL parser fails when deploying an application that declares a schema that cannot be located. Otherwise, the parser fails if the application also makes use of the namespace to which such a schema is bound.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • EE-7827

mule.force.runtime.profiling.consumers.enablement

When enabled, profiling consumers implemented by the Runtime are enabled by default.

Available Since

  • 4.5.0

  • 4.4.0-20220221

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19967

mule.dw.handle_splitter_exception

When enabled, DataWeave correctly handles internal exceptions while splitting a payload, preventing subsequent serialization errors.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • DW-383

mule.honour.reserved.properties

When enabled, reserved properties such as app.name can’t be overridden by global properties (overrides are ignored).

Available Since

  • 4.4.0

  • 4.3.0-20220221

Enabled by Default Since

  • 4.3.0

Issue ID

  • MULE-17659

mule.honourErrorMappingsWhenPolicyAppliedOnOperation

When enabled, the operation policy’s error resolution is ignored. Therefore, the error mappings of the processor on which the policy is applied are set successfully.

Available Since

  • 4.5.0

  • 4.4.0-20220722

  • 4.3.0-20220725

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11147961

mule.detailedCompositeRoutingExceptionLog

When enabled, AbstractForkJoinRouter-based processors, such as Parallel For Each and Scatter-Gather routers, now show detailed error information for their failed routes.

Available Since

  • 4.5.0

  • 4.4.0-20220622

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10965130

mule.parallelForeach.flattenMessage

When enabled, if the items to iterate over on a parallel-foreach scope are messages (such as the output of an operation that returns Result objects), they are flattened in a way that is consistent with what the foreach scope does.

Available Since

  • 4.5.0

  • 4.4.0-20220124

  • 4.3.0-20220124

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-20067

mule.setVariable.WithNullValue

When enabled, the Set Variable component creates a variable even if its value is null.

Available Since

  • 4.4.0

  • 4.3.0-20210622

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19443

mule.startExtensionComponentsWithArtifactClassloader

When enabled, extensions are only able to load exported resources from the deployable artifacts (application, policy, domain).

Available Since

  • 4.4.0

  • 4.3.0-20211026

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19815

mule.transformer.toString.transformIteratorElements

When enabled, managed cursor iterators transformed to strings show the representation of the elements instead of generic value org.mule.runtime.core.internal.streaming.object.-ManagedCursorIteratorProvider$ManagedCursorIterator@.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19323

mule.suppress.mule.exceptions

When enabled, error suppression occurs. This feature prevents components such as the Web Service Consumer connector and the Until Successful scope from reporting errors outside their namespaces.

Example of an error log extract for a connectivity error at the Web Service Consumer (HTTP:CONNECTIVITY is being suppressed):

Error type : WSC:INVALID_WSDL
Caused by  : HTTP:CONNECTIVITY

Suppressed errors are treated as underlying causes that can also be matched by On Error handlers.

Available Since

  • 4.4.0-20220922

Enabled by Default Since

  • Enabled by default in every Mule version

Issue ID

  • W-11308645

mule.support.native.library.dependencies

When enabled, if an application accesses a native library, the rest of its declared native libraries are also loaded. This prevents errors like UnsatisfiedLinkError when the accessed native library depends on another native library. Libraries must be declared at the sharedLibraries configuration following the dependency order, meaning that if library A depends on library B, then A must be declared first. Declaring the native libraries at a domain is also supported.

Available Since

  • 4.5.0

  • 4.4.0-20230417

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11855052

mule.rethrowExceptionsInIdempotentMessageValidator

When enabled, internal exceptions are rethrown instead of throwing a general MULE:DUPLICATE_MESSAGE when processing an event in the idempotent-message-validator.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11529823

com.mulesoft.dw.xml_reader.honourMixedContentStructure

When this property is set to true, DataWeave retains a mixed-content structure instead of grouping text with mixed content into a single text field.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11071481

ENFORCE_ERROR_TYPES_VALIDATION

When enabled, error types validations are enforced, even for error handlers/components that aren’t being referenced. This feature isn’t configurable by system property.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19879

mule.disable.attribute.parameter.whitespace.trimming

When enabled, the runtime trims whitespaces from parameter values defined at the attribute level in the DSL.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19803

mule.disable.pojo.text.parameter.whitespace.trimming

When enabled, the runtime trims whitespaces from CDATA text parameter of pojos in the DSL.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-20048

mule.enforce.expression.validation

When enabled, expression validations are enforced for targetValue, not allowing a literal value.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19987

mule.enforce.dw.expression.validation

When enabled, expression validations are enforced for all DataWeave expressions.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19967

mule.disable.registryBootstrapOptionalEntries

When enabled, optional attribute in entries in a registry-bootstrap.properties are ignored.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Deprecated Since

  • 4.9.0, the optional attribute in entries is no longer supported

Issue ID

  • W-10736301

mule.disable.applyObjectProcessor

When enabled, org.mule.runtime.core.privileged.registry.ObjectProcessor implementations aren’t applied on objects registered into the SimpleRegistry.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-11737

mule.deployment.validateAppModelWithRegionClassloader

When enabled, the application model is validated with the region classloader. When disabled, it is validated with the application classloader.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10808757

mule.suppress.mule.exceptions

When enabled, error suppression happens. This affects, for example, the Web Service Consumer connector and the Until Successful scope that always reports errors from their corresponding namespaces (MULE and WSC). Suppressed errors are treated as underlying causes.

Available Since

  • 4.5.0

  • 4.4.0-202210

Enabled by Default Since

  • Enabled by default in every Mule version

Issue ID

  • W-11308645

mule.foreachRouterRejectsMapExpressions

When enabled, the 'foreach' router generates an IllegalArgumentException if the collection expression evaluates to a java.util.Map.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-12207110

mule.honour.insecure.tls.configuration

When enabled, the insecure TLS configuration is honored even if there are fields of the TrustStore configured.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10822938

mule.transaction.sink.index

When enabled, flux sinks are cached using index as part of the key. If a sink is already in use, a new sink is created.

Available Since

  • 4.4.0

Enabled by Default Since

  • Enabled by default in every Mule version

Issue ID

  • W-12128703

mule.enable.policy.context.parallel.scopes

When enabled, a new (Source) Policy Context is created for the execution of parallel scopes: ParallelForeach, ScatterGather, and Async.

Available Since

  • 4.5.0

  • 4.4.0-202306

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-13509911

mule.put.trace.id.and.span.id.in.mdc

When enabled, the trace ID and span ID are added to the MDC when available.

Available Since

  • 4.5.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-12979787

mule.enable.mule.specific.tracing.information

When enabled, the ancestor-mule-span-id value is added in the trace state when a span is propagated.

Available Since

  • 4.5.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-13215870

mule.disableJmx.for.commons.pool2

When enabled, MBeans aren’t registered for commons-pool2.

Available Since

  • 4.6.0

Enabled by Default Since

  • 4.6.0

Issue ID

  • W-12422473

mule.disable.scheduler.logging

When enabled, the Scheduler doesn’t log exceptions.

Available Since

  • 4.6.0

Enabled by Default Since

  • 4.6.0

Issue ID

  • W-13881167

mule.tx.error.when.timeout

When enabled, an error is thrown when a local or XA transaction reach timeout. This error can be handled using error handling.

Available Since

  • 4.6.1

Enabled by Default Since

  • 4.6.1

Issue ID

  • W-14608096

mule.disableXmlSdkImplicitConfigurationCreation

When enabled, implicit configuration for the XML SDK isn’t created.

Available Since

  • 4.7.0

Enabled by Default Since

  • 4.7.0

Issue ID

  • W-10634129

mule.enable.xml.sdk.mdc.reset

When enabled, the MDC context resets after XML SDK operation is executed.

Available Since

  • 4.8.0

  • 4.7.1

  • 4.6.4

  • 4.4.0-20240522

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15206528

mule.unsupportedExtensionsClientRunAsync

When enabled, org.mule.runtime.extension.api.client.ExtensionsClient deprecated methods (executeAsync(String, String, OperationParameters) and execute(String, String, OperationParameters)) throw an UnsupportedOperationException.

Available Since

  • 1.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15399821

ENFORCE_IMPORT_TARGET_SAME_TYPE

When enabled, the root element of import targets are validated to be the same as the importing configuration.

Available Since

  • 4.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15509819

mule.honour.persisted.flow.state

When enabled, flows honor the state configured in flows.deployment.properties when restarting the app, regardless of the initial state.

Available Since

  • 4.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15750334

mule.ntlm.avoid.send.payload.on.type1

When enabled, body contents aren’t sent on NTLM type 1 requests. This saves resources by not sending a payload that is never consumed (the server rejects the payload until the dance is completed).

Available Since

  • 4.9.0

  • 4.8.4

  • 4.6.12

Enabled by Default Since

  • 4.9.0

Issue ID

  • W-17107281

mule.forkJoin.completeChildContextsOnTimeout

When enabled, the processors that perform fork and join work (currently, Scatter-Gather and Parallel For Each routers) complete the child event contexts when a timeout occurs.

Available Since

  • 4.10.0

  • 4.9.2

  • 4.6.14

  • 4.4.0-20250217

Enabled by Default Since

  • 4.10.0

Issue ID

  • W-16941297

mule.repeatableStreaming.bytes.eagerRead

When enabled, the read methods of bytes repeatable streams return immediately with any available data. If disabled, they don’t return until the requested len is fully read. Set this property to true to process SSE events over HTTP as they arrive instead of buffering them.

Available Since

  • 4.10.0

  • 4.9.7

  • 4.6.20

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-18716253

mule.disable.optimised.notification.handler.dynamic.resolution.update.based.on.delegate

When disabled, dynamic resolution of notification handling doesn’t occur after the Mule artifact is initialized. This can cause race conditions that affect monitoring metrics.

Available Since

  • 4.10.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-16828516

mule.redeliveryPolicy.encode.secureHash

When set to true, the encrypted payload is encoded in hexadecimal format when no Expression ID is specified.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-18584560

mule.forcefulShutdown.raiseCancelledError

When set to true, events cancelled during a forceful shutdown raise a MULE:CANCELLED error instead of MULE:UNKNOWN. Dynamic configuration creation attempts during shutdown also raise a MULE:CANCELLED error instead of MULE:UNKNOWN.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

  • 4.6.24

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-19648397

mule.untilSuccessful.retryOnCriticalError.disallow

When set to true, events aren’t retried if a MULE:CRITICAL error occurs within an until-successful scope.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

  • 4.6.24

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-19648397

mule.batch.record.exceptions.disallow

When set to true, batch processing uses batch errors instead of step exceptions. The DataWeave exception-based bindings Batch::getFirstException(), Batch::getLastException(), Batch::failureExceptionForStep(String), and Batch::getStepExceptions() are replaced by their error-based equivalents Batch::getFirstError(), Batch::getLastError(), Batch::failureErrorForStep(String), and Batch::getStepErrors().

Available Since

  • 4.11.0

  • 4.10.2

  • 4.9.12

  • 4.6.25

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-19607093

mule.netty.redirect.filterSensitiveHeaders

When set to true, the Authorization, Proxy-Authorization, and Expect headers are removed from redirected requests to a different host. This applies only when the HTTP Service implementation is Netty.

Available Since

  • 4.11.0

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-20903125

mule.propagate.objectStore.customization.to.policies

When set to true, policies use the object store implementation configured for the application. This enables alternative implementations, such as Object Store v2, to be used by policies.

Available Since

  • 4.11.2

  • 4.9.15

  • 4.6.28

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-19607093

mule.enable.inline.tls.context.initialization

When set to true, inline TLS contexts invoke their lifecycle initialization method, ensuring inline TLS contexts are fully initialized before use.

Available Since

  • 4.11.3

  • 4.9.16

  • 4.6.29

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-20038933

mule.enable.byteBuddy.objectCreation

When enabled, the object factories are created with Byte Buddy instead of CGLIB.

Available Since

  • 4.4.0-202203

  • 4.3.0-202203

Enabled by Default Since

  • 4.4.0

Deprecated Since

  • 4.5.0, ByteBuddy is mandatory

Issue ID

  • W-10672687

mule.flowStop.parallel.enable

When enabled, all flows are stopped in parallel rather than sequentially when a Mule application stops. This prevents delays caused by in-flight events in one flow from delaying the shutdown of other flows.

Available Since

  • 4.12.0

  • 4.11.1

  • 4.9.14

  • 4.6.27

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-21228085

mule.serialize.message.in.cache

When enabled, ee:cache persists only the Message instead of the full Event. Java customizations for ee:cache aren’t supported, including custom implementations of cachingStrategy-ref, keyGenerator, responseGenerator, and eventCopyStrategy. After this feature flag is enabled, it can’t be disabled because the format of persisted data is updated.

Available Since

  • 4.12.0

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-21549211

## See Also [Configure System Properties](https://docs.mulesoft.com/mule-runtime/4.11/mule-app-properties-system) --- product: Mule Runtime version: 4.12 --- # Feature Flagging Mechanism > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine incorporates a feature flagging mechanism that enables Mule applications to change the behavior of the Mule instance depending on the required minimum Mule version. This feature ensures backward compatibility because it allows Mule applications to continue working on later Mule runtime versions, while new Mule applications can benefit from the latest bug fixes implemented in the Mule instance. The feature flagging mechanism is automatic. For each Mule application deployed to a Mule instance, Mule determines which features are enabled or disabled based on the application’s minimum Mule version configured in the application descriptor file (`mule-artifact.json`) of the Mule app. By default, Mule runtime engine disables any new features or bug fixes that aren’t backward compatible with Mule applications running in earlier Mule versions. However, it is possible to manage the feature flags configured for each Mule application or all applications running in the same Mule instance. ## Understanding minMuleVersion > [!NOTE] If your deployment was rejected because of `minMuleVersion`, set it to the target > runtime’s version or earlier, keeping the patch at `.0` unless you need a backported fix (see > [Adopting a Backported Bug Fix (Advanced)](#adopting-a-backported-bug-fix-advanced)). Don’t set it > to the exact patch of the runtime you built or scaffolded with. `minMuleVersion` declares the minimum runtime feature set that a Mule application requires. Conceptually, this corresponds to the `minor` number in [Semantic Versioning](https://semver.org/). Mule 4 follows Semantic Versioning 2.0.0. Anypoint Studio and Anypoint Code Builder use this value when scaffolding a new application. ### How the Runtime and Tools Check minMuleVersion `minMuleVersion` isn’t only a feature-flag selector. The runtime, and other tools that work with a Mule artifact, compare its `minMuleVersion` against a target version using the full `major.minor.patch`. If the artifact’s `minMuleVersion` is later than the target, it’s rejected. The most visible case is deployment. The runtime refuses to deploy an application whose `minMuleVersion` is later than the running runtime, and reports that the application requires a later runtime version. For example, an application with `minMuleVersion=4.12.2` doesn’t deploy on a `4.12.1` runtime, even though the two only differ in patch. To check the version of the target runtime in CloudHub, CloudHub 2.0, Runtime Fabric, or a server managed by Runtime Manager, check the environment or instance details in Runtime Manager. On a standalone on-premises server, run `./mule -version` or check the startup log. The same comparison also happens outside the deployment cycle. Any tooling that reads a Mule artifact without deploying it applies the same check. For example, a service that introspects an application’s flows to list its triggers compares the artifact’s `minMuleVersion` exactly as deployment does. So does Anypoint Exchange when it extracts metadata as you publish an asset. Over-declaring `minMuleVersion` can therefore cause an artifact to be rejected by such tooling even when you aren’t deploying it. This comparison is patch-sensitive by design. That’s what makes the backported bug fixes described in [Adopting a Backported Bug Fix (Advanced)](#adopting-a-backported-bug-fix-advanced) possible. Raising the patch of `minMuleVersion` is how an application opts into a backported bug fix. ### Choosing the Value Set `minMuleVersion` to the earliest Mule version whose feature set your application needs, not the latest patch of whatever runtime you happened to build or scaffold with. Declaring a later version than necessary is called over-declaring, and it can prevent an otherwise-compatible runtime or tool from accepting the application. Setting `minMuleVersion` to an earlier version has a trade-off too: It disables any feature or bug fix enabled by default between the new value and the version the application previously declared. Choose the earliest version whose behavior your application relies on, not an arbitrarily early one. ### Adopting a Backported Bug Fix (Advanced) The `patch` component of `minMuleVersion` (the third number, for example, the `2` in `4.12.2`) only matters for one corner case: a bug fix backported into a patch release instead of shipping with the next minor version. This typically results from an escalated product request. The [Feature Flags Reference](#feature-flags-reference) table documents these cases. Most flags become available at a minor release, but a few become available at a patch release, for example, `mule.tx.error.when.timeout`, available since Mule 4.6.1. Like every entry in that table, a backported bug fix is disabled by default, so an application relying on the preexisting behavior isn’t affected by upgrading the runtime. Enabling it is a deliberate opt-in. On an on-premises Mule instance, the recommended way to opt in to a backported fix (or any flag) is to configure it explicitly through a system property, as described in [Configure Feature Flags for the Mule Instance](#configure-feature-flags-for-the-mule-instance), rather than by bumping the patch component of `minMuleVersion`. Raising the patch changes every flag available since that patch at once, including ones you didn’t intend to adopt, and it also tightens the compatibility check described in [How the Runtime and Tools Check minMuleVersion](#how-the-runtime-and-tools-check-minmuleversion). Only set a patch-level `minMuleVersion` when all these conditions are true: - The application depends on a specific backported fix. - The deployment target doesn’t support a system-property override. - MuleSoft Support has directed you to do so. Otherwise, leave the patch at `.0`. For the full list of fields in `mule-artifact.json`, including `minMuleVersion`, see [Application Descriptor Reference (mule-artifact.json)](https://docs.mulesoft.com/mule-runtime/4.12/mule-artifact-json). ## Configure Feature Flags for a Mule Application To configure feature flags for a Mule application, change the `minMuleVersion` value in the `mule-artifact.json` file of your app. With this configuration, the Mule instance runs the application using all features and bug fixes that were released to that particular version. The instance disables features and bug fixes that are active by default in later Mule versions. For example, you can run a Mule application in Mule 4.5.0 instructing the Mule instance to apply only the features that don’t change core functionality up to Mule 4.1.0: Example `mule-artifact.json` file { "minMuleVersion": "4.1.0" } > [!NOTE] This example intentionally uses an earlier version, `4.1.0`, to illustrate selecting an > earlier feature set. It’s not a recommended value for a new application. See > [Understanding minMuleVersion](#understanding-minmuleversion). ## Configure Feature Flags for the Mule Instance An alternative way to configure feature flags is by using system properties. In this case, you can enable or disable each one of the available feature flags. However, configuring feature flags through system properties applies the changes at the Mule instance level, so all applications deployed to this Mule instance behave according to the configured feature flags. Note that this configuration is compatible with on-premise deployments only because you cannot configure system properties in other deployment targets. For example, you can configure a Mule 4.5.0 instance to enable and disable specific features for all applications running on this instance: Example `wrapper.conf` file … wrapper.java.additional.999=-DHONOUR\_RESERVED\_PROPERTIES\_PROPERTY=true wrapper.java.additional.1000=-DCOMPUTE\_CONNECTION\_ERRORS\_IN\_STATS\_PROPERTY=false ## Feature Flags Reference The following table shows the available feature flags, a description of their functionality, the Mule version in which the flag became available, the earlier minor version releases that enable the flag by default, and the issue ID in which the change was implemented:
Feature FlagDescription

mule.batch.fixed.aggregator.transaction.record.buffer

When enabled, batch aggregators with fixed size aggregators commit only when a full block is processed.

Available Since

  • 4.4.0

  • 4.3.0-20210304

  • 4.2.2-20210304

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19218

mule.compute.connection.errors.in.stats

When enabled, connection errors are computed as part of alerts triggering.

Available Since

  • 4.4.0

  • 4.3.0-20210304

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19020

mule.enable.default.errorhandler.not.rollback.incorrect.tx

When enabled, the default error handler added by the Runtime doesn’t roll back a transaction if it doesn’t correspond to have this roll back made.

Available Since

  • 4.5.0

  • 4.4.0-20211227

  • 4.3.0-20211222

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19919

mule.dw.remove_shadowed_implicit_inputs

When enabled, DataWeave removes implicit inputs when a variable with the same name is declared at the root level.

Available Since

  • 4.5.0

  • 4.4.0-20211026

Enabled by Default Since

  • 4.4.0

Issue ID

  • DW-893

mule.enable.policy.isolation

When enabled, Mule manages extensions imported by a policy in complete isolation from the extensions imported by the Mule application. Also, validations prevent the use of explicit configurations that the application declared as part of the policy initialization.

Available Since

  • 4.4.0

  • 4.3.0-20210622

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19226

mule.enable.profiling.service

When enabled, the Runtime profiling capabilities become available.

Available Since

  • 4.4.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19588

mule.entityResolver.failOnFirstError

When enabled, the Mule XML DSL parser fails when deploying an application that declares a schema that cannot be located. Otherwise, the parser fails if the application also makes use of the namespace to which such a schema is bound.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • EE-7827

mule.force.runtime.profiling.consumers.enablement

When enabled, profiling consumers implemented by the Runtime are enabled by default.

Available Since

  • 4.5.0

  • 4.4.0-20220221

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19967

mule.dw.handle_splitter_exception

When enabled, DataWeave correctly handles internal exceptions while splitting a payload, preventing subsequent serialization errors.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • DW-383

mule.honour.reserved.properties

When enabled, reserved properties such as app.name can’t be overridden by global properties (overrides are ignored).

Available Since

  • 4.4.0

  • 4.3.0-20220221

Enabled by Default Since

  • 4.3.0

Issue ID

  • MULE-17659

mule.honourErrorMappingsWhenPolicyAppliedOnOperation

When enabled, the operation policy’s error resolution is ignored. Therefore, the error mappings of the processor on which the policy is applied are set successfully.

Available Since

  • 4.5.0

  • 4.4.0-20220722

  • 4.3.0-20220725

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11147961

mule.detailedCompositeRoutingExceptionLog

When enabled, AbstractForkJoinRouter-based processors, such as Parallel For Each and Scatter-Gather routers, now show detailed error information for their failed routes.

Available Since

  • 4.5.0

  • 4.4.0-20220622

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10965130

mule.parallelForeach.flattenMessage

When enabled, if the items to iterate over on a parallel-foreach scope are messages (such as the output of an operation that returns Result objects), they are flattened in a way that is consistent with what the foreach scope does.

Available Since

  • 4.5.0

  • 4.4.0-20220124

  • 4.3.0-20220124

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-20067

mule.setVariable.WithNullValue

When enabled, the Set Variable component creates a variable even if its value is null.

Available Since

  • 4.4.0

  • 4.3.0-20210622

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19443

mule.startExtensionComponentsWithArtifactClassloader

When enabled, extensions are only able to load exported resources from the deployable artifacts (application, policy, domain).

Available Since

  • 4.4.0

  • 4.3.0-20211026

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19815

mule.transformer.toString.transformIteratorElements

When enabled, managed cursor iterators transformed to strings show the representation of the elements instead of generic value org.mule.runtime.core.internal.streaming.object.-ManagedCursorIteratorProvider$ManagedCursorIterator@.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19323

mule.suppress.mule.exceptions

When enabled, error suppression occurs. This feature prevents components such as the Web Service Consumer connector and the Until Successful scope from reporting errors outside their namespaces.

Example of an error log extract for a connectivity error at the Web Service Consumer (HTTP:CONNECTIVITY is being suppressed):

Error type : WSC:INVALID_WSDL
Caused by  : HTTP:CONNECTIVITY

Suppressed errors are treated as underlying causes that can also be matched by On Error handlers.

Available Since

  • 4.4.0-20220922

Enabled by Default Since

  • Enabled by default in every Mule version

Issue ID

  • W-11308645

mule.support.native.library.dependencies

When enabled, if an application accesses a native library, the rest of its declared native libraries are also loaded. This prevents errors like UnsatisfiedLinkError when the accessed native library depends on another native library. Libraries must be declared at the sharedLibraries configuration following the dependency order, meaning that if library A depends on library B, then A must be declared first. Declaring the native libraries at a domain is also supported.

Available Since

  • 4.5.0

  • 4.4.0-20230417

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11855052

mule.rethrowExceptionsInIdempotentMessageValidator

When enabled, internal exceptions are rethrown instead of throwing a general MULE:DUPLICATE_MESSAGE when processing an event in the idempotent-message-validator.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11529823

com.mulesoft.dw.xml_reader.honourMixedContentStructure

When this property is set to true, DataWeave retains a mixed-content structure instead of grouping text with mixed content into a single text field.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11071481

ENFORCE_ERROR_TYPES_VALIDATION

When enabled, error types validations are enforced, even for error handlers/components that aren’t being referenced. This feature isn’t configurable by system property.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19879

mule.disable.attribute.parameter.whitespace.trimming

When enabled, the runtime trims whitespaces from parameter values defined at the attribute level in the DSL.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19803

mule.disable.pojo.text.parameter.whitespace.trimming

When enabled, the runtime trims whitespaces from CDATA text parameter of pojos in the DSL.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-20048

mule.enforce.expression.validation

When enabled, expression validations are enforced for targetValue, not allowing a literal value.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19987

mule.enforce.dw.expression.validation

When enabled, expression validations are enforced for all DataWeave expressions.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19967

mule.disable.registryBootstrapOptionalEntries

When enabled, optional attribute in entries in a registry-bootstrap.properties are ignored.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Deprecated Since

  • 4.9.0, the optional attribute in entries is no longer supported

Issue ID

  • W-10736301

mule.disable.applyObjectProcessor

When enabled, org.mule.runtime.core.privileged.registry.ObjectProcessor implementations aren’t applied on objects registered into the SimpleRegistry.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-11737

mule.deployment.validateAppModelWithRegionClassloader

When enabled, the application model is validated with the region classloader. When disabled, it is validated with the application classloader.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10808757

mule.suppress.mule.exceptions

When enabled, error suppression happens. This affects, for example, the Web Service Consumer connector and the Until Successful scope that always reports errors from their corresponding namespaces (MULE and WSC). Suppressed errors are treated as underlying causes.

Available Since

  • 4.5.0

  • 4.4.0-202210

Enabled by Default Since

  • Enabled by default in every Mule version

Issue ID

  • W-11308645

mule.foreachRouterRejectsMapExpressions

When enabled, the 'foreach' router generates an IllegalArgumentException if the collection expression evaluates to a java.util.Map.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-12207110

mule.honour.insecure.tls.configuration

When enabled, the insecure TLS configuration is honored even if there are fields of the TrustStore configured.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10822938

mule.transaction.sink.index

When enabled, flux sinks are cached using index as part of the key. If a sink is already in use, a new sink is created.

Available Since

  • 4.4.0

Enabled by Default Since

  • Enabled by default in every Mule version

Issue ID

  • W-12128703

mule.enable.policy.context.parallel.scopes

When enabled, a new (Source) Policy Context is created for the execution of parallel scopes: ParallelForeach, ScatterGather, and Async.

Available Since

  • 4.5.0

  • 4.4.0-202306

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-13509911

mule.put.trace.id.and.span.id.in.mdc

When enabled, the trace ID and span ID are added to the MDC when available.

Available Since

  • 4.5.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-12979787

mule.enable.mule.specific.tracing.information

When enabled, the ancestor-mule-span-id value is added in the trace state when a span is propagated.

Available Since

  • 4.5.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-13215870

mule.disableJmx.for.commons.pool2

When enabled, MBeans aren’t registered for commons-pool2.

Available Since

  • 4.6.0

Enabled by Default Since

  • 4.6.0

Issue ID

  • W-12422473

mule.disable.scheduler.logging

When enabled, the Scheduler doesn’t log exceptions.

Available Since

  • 4.6.0

Enabled by Default Since

  • 4.6.0

Issue ID

  • W-13881167

mule.tx.error.when.timeout

When enabled, an error is thrown when a local or XA transaction reach timeout. This error can be handled using error handling.

Available Since

  • 4.6.1

Enabled by Default Since

  • 4.6.1

Issue ID

  • W-14608096

mule.disableXmlSdkImplicitConfigurationCreation

When enabled, implicit configuration for the XML SDK isn’t created.

Available Since

  • 4.7.0

Enabled by Default Since

  • 4.7.0

Issue ID

  • W-10634129

mule.enable.xml.sdk.mdc.reset

When enabled, the MDC context resets after XML SDK operation is executed.

Available Since

  • 4.8.0

  • 4.7.1

  • 4.6.4

  • 4.4.0-20240522

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15206528

mule.unsupportedExtensionsClientRunAsync

When enabled, org.mule.runtime.extension.api.client.ExtensionsClient deprecated methods (executeAsync(String, String, OperationParameters) and execute(String, String, OperationParameters)) throw an UnsupportedOperationException.

Available Since

  • 1.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15399821

ENFORCE_IMPORT_TARGET_SAME_TYPE

When enabled, the root element of import targets are validated to be the same as the importing configuration.

Available Since

  • 4.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15509819

mule.honour.persisted.flow.state

When enabled, flows honor the state configured in flows.deployment.properties when restarting the app, regardless of the initial state.

Available Since

  • 4.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15750334

mule.ntlm.avoid.send.payload.on.type1

When enabled, body contents aren’t sent on NTLM type 1 requests. This saves resources by not sending a payload that is never consumed (the server rejects the payload until the dance is completed).

Available Since

  • 4.9.0

  • 4.8.4

  • 4.6.12

Enabled by Default Since

  • 4.9.0

Issue ID

  • W-17107281

mule.forkJoin.completeChildContextsOnTimeout

When enabled, the processors that perform fork and join work (currently, Scatter-Gather and Parallel For Each routers) complete the child event contexts when a timeout occurs.

Available Since

  • 4.10.0

  • 4.9.2

  • 4.6.14

  • 4.4.0-20250217

Enabled by Default Since

  • 4.10.0

Issue ID

  • W-16941297

mule.repeatableStreaming.bytes.eagerRead

When enabled, the read methods of bytes repeatable streams return immediately with any available data. If disabled, they don’t return until the requested len is fully read. Set this property to true to process SSE events over HTTP as they arrive instead of buffering them.

Available Since

  • 4.10.0

  • 4.9.7

  • 4.6.20

Enabled by Default Since

  • Not enabled by default in any Mule version

Deprecated Since

  • 4.12.0, this is configurable on streaming configuration. Use the bytes.eagerRead property instead.

Issue ID

  • W-18716253

mule.disable.optimised.notification.handler.dynamic.resolution.update.based.on.delegate

When disabled, dynamic resolution of notification handling doesn’t occur after the Mule artifact is initialized. This can cause race conditions that affect monitoring metrics.

Available Since

  • 4.10.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-16828516

mule.redeliveryPolicy.encode.secureHash

When enabled, the encrypted payload is encoded in hexadecimal format when no Expression ID is specified.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-18584560

mule.forcefulShutdown.raiseCancelledError

When enabled, events cancelled during a forceful shutdown raise a MULE:CANCELLED error instead of MULE:UNKNOWN. Dynamic configuration creation attempts during shutdown also raise a MULE:CANCELLED error instead of MULE:UNKNOWN.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

  • 4.6.24

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-19648397

mule.untilSuccessful.retryOnCriticalError.disallow

When enabled, events aren’t retried if a MULE:CRITICAL error occurs within an until-successful scope.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

  • 4.6.24

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-19648397

mule.batch.record.exceptions.disallow

When enabled, batch processing uses batch errors instead of step exceptions. The DataWeave exception-based bindings Batch::getFirstException(), Batch::getLastException(), Batch::failureExceptionForStep(String), and Batch::getStepExceptions() are replaced by their error-based equivalents Batch::getFirstError(), Batch::getLastError(), Batch::failureErrorForStep(String), and Batch::getStepErrors().

Available Since

  • 4.11.0

  • 4.10.2

  • 4.9.12

  • 4.6.25

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-19607093

mule.netty.redirect.filterSensitiveHeaders

When enabled, the Authorization, Proxy-Authorization, and Expect headers are removed from redirected requests to a different host. This applies only when the HTTP Service implementation is Netty.

Available Since

  • 4.11.0

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-20903125

mule.propagate.objectStore.customization.to.policies

When enabled, policies use the object store implementation configured for the application. This enables alternative implementations, such as Object Store v2, to be used by policies.

Available Since

  • 4.11.1

  • 4.10.3

  • 4.9.13

  • 4.6.26

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-19607093

mule.enable.inline.tls.context.initialization

When enabled, inline TLS contexts invoke their lifecycle initialization method, ensuring inline TLS contexts are fully initialized before use.

Available Since

  • 4.11.3

  • 4.9.16

  • 4.6.29

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-20038933

mule.flowStop.parallel.enable

When enabled, all Mule flows are stopped in parallel rather than sequentially when a Mule application is stopped. This prevents delays caused by in-flight events in one flow from delaying the shutdown of other flows.

Available Since

  • 4.12.0

  • 4.11.1

  • 4.9.14

  • 4.6.27

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-21228085

mule.serialize.message.in.cache

When enabled, ee:cache persists only the Message instead of the full Event. Java customizations for ee:cache aren’t supported, including custom implementations of cachingStrategy-ref, keyGenerator, responseGenerator, and eventCopyStrategy. After this feature flag is enabled, it can’t be disabled because the format of persisted data is updated.

Available Since

  • 4.12.0

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-21549211

mule.enable.byteBuddy.objectCreation

When enabled, the object factories are created with Byte Buddy instead of CGLIB.

Available Since

  • 4.4.0-202203

  • 4.3.0-202203

Enabled by Default Since

  • 4.4.0

Deprecated Since

  • 4.5.0, ByteBuddy is mandatory

Issue ID

  • W-10672687

ENFORCE_BATCH_AGGREGATOR_VALIDATION

When enabled, batch:aggregator validations are enforced.

Available Since

  • 4.12.0

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-21549351

ENFORCE_POLICY_PROXY_VALIDATION

When enabled, http-policy:proxy completeness validations are enforced.

Available Since

  • 4.12.0

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-21549351

## See Also [Configure System Properties](https://docs.mulesoft.com/mule-runtime/4.12/mule-app-properties-system) --- product: Mule Runtime version: 4.4 --- # Feature Flagging Mechanism > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine incorporates a feature flagging mechanism that enables Mule applications to change the behavior of the Mule instance depending on the required minimum Mule version. This feature ensures backward compatibility because it allows Mule applications to continue working on later Mule runtime versions, while new Mule applications can benefit from the latest bug fixes implemented in the Mule instance. The feature flagging mechanism is automatic. For each Mule application deployed to a Mule instance, Mule determines which features are enabled or disabled based on the application’s minimum Mule version configured in the application descriptor file (`mule-artifact.json`) of the Mule app. By default, Mule runtime engine disables any new features or bug fixes that are not backward compatible with Mule applications running in earlier Mule versions. However, it is possible to manage the feature flags configured for each Mule application or all applications running in the same Mule instance. ## Configure Feature Flags for a Mule Application To configure feature flags for a Mule application, change the `minMuleVersion` value in the `mule-artifact.json` file of your app. This configuration instructs the Mule instance to run this application implementing all features and bug fixes that were released to that particular version and disabling features and bug fixes that are active by default in later Mule versions. For example, you can run a Mule application in Mule 4.4.0 instructing the Mule instance to apply only the features that do not change core functionality up to Mule 4.1.0: Example `mule-artifact.json` file { "minMuleVersion": "4.1.0" } ## Configure Feature Flags for the Mule Instance An alternative way to configure feature flags is by using system properties. In this case, you can enable or disable each one of the available feature flags. However, configuring feature flags through system properties applies the changes at the Mule instance level, so all applications deployed to this Mule instance behave according to the configured feature flags. Note that this configuration is compatible with on-premise deployments only because you cannot configure system properties in other deployment targets. For example, you can configure a Mule 4.3.0 instance to enable and disable specific features for all applications running on this instance: Example `wrapper.conf` file … wrapper.java.additional.999=-DHONOUR\_RESERVED\_PROPERTIES\_PROPERTY=true wrapper.java.additional.1000=-DCOMPUTE\_CONNECTION\_ERRORS\_IN\_STATS\_PROPERTY=false ## Feature Flags Reference The following table shows the available feature flags, a description of their functionality, the Mule version in which the flag became available, the earlier minor version releases that enable the flag by default, and the issue ID in which the change was implemented:
Feature FlagDescription

mule.batch.fixed.aggregator.transaction.record.buffer

When enabled, batch aggregators with fixed size aggregators commit only when a full block is processed.

Available Since

  • 4.4.0

  • 4.3.0-20210304

  • 4.2.2-20210304

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19218

mule.compute.connection.errors.in.stats

When enabled, connection errors are computed as part of alerts triggering.

Available Since

  • 4.4.0

  • 4.3.0-20210304

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19020

mule.enable.default.errorhandler.not.rollback.incorrect.tx

When enabled, the default error handler added by the Runtime doesn’t roll back a transaction if it doesn’t correspond to have this roll back made.

Available Since

  • 4.4.0-20211227

  • 4.3.0-20211222

Enabled by Default Since

  • Not enabled by default in any Mule version.

Issue ID

  • MULE-19919

mule.dw.remove_shadowed_implicit_inputs

When enabled, DataWeave removes implicit inputs when a variable with the same name is declared at the root level.

Available Since

  • 4.4.0-20211026

Enabled by Default Since

  • 4.4.0

Issue ID

  • DW-893

mule.enable.byteBuddy.objectCreation

When enabled, the object’s factories are created with Byte Buddy instead of CGLIB.

Available Since

  • 4.4.0-20220321

  • 4.3.0-20220321

Enabled by Default Since

  • 4.4.0

Issue ID

  • W-10672687

mule.enable.policy.isolation

When enabled, Mule manages extensions imported by a policy in complete isolation from the extensions imported by the Mule application. Also, validations prevent the use of explicit configurations that the application declared as part of the policy initialization.

Available Since

  • 4.4.0

  • 4.3.0-20210622

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19226

mule.enable.profiling.service

When enabled, the Runtime profiling capabilities become available.

Available Since

  • 4.4.0

Enabled by Default Since

  • Not enabled by default in any Mule version.

Issue ID

  • MULE-19588

mule.entityResolver.failOnFirstError

When enabled, the Mule XML DSL parser fails when deploying an application that declares a schema that cannot be located. Otherwise, the parser fails if the application also makes use of the namespace to which such a schema is bound.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • EE-7827

mule.force.runtime.profiling.consumers.enablement

When enabled, profiling consumers implemented by the Runtime are enabled by default.

Available Since

  • 4.4.0-20220221

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19967

mule.dw.handle_splitter_exception

When enabled, DataWeave correctly handles internal exceptions while splitting a payload, preventing subsequent serialization errors.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • DW-383

mule.honour.reserved.properties

When enabled, reserved properties such as app.name can’t be overridden by global properties (overrides are ignored).

Available Since

  • 4.4.0

  • 4.3.0-20220221

Enabled by Default Since

  • 4.4.0

  • 4.3.0

Issue ID

  • MULE-17659

mule.honourErrorMappingsWhenPolicyAppliedOnOperation

When enabled, the operation policy’s error resolution is ignored. Therefore, the error mappings of the processor on which the policy is applied are set successfully.

Available Since

  • 4.4.0-20220722

  • 4.3.0-20220725

Enabled by Default Since

  • Not enabled by default in any Mule version.

Issue ID

  • W-11147961

mule.detailedCompositeRoutingExceptionLog

When enabled, AbstractForkJoinRouter-based processors, such as Parallel For Each and Scatter-Gather routers, now show detailed error information for their failed routes.

Available Since

  • 4.4.0-20220622

Enabled by Default Since

  • Not enabled by default in any Mule version.

Issue ID

  • W-10965130

mule.parallelForeach.flattenMessage

When enabled, if the items to iterate over on a parallel-foreach scope are messages (such as the output of an operation that returns Result objects), they are flattened in a way that is consistent with what the foreach scope does.

Available Since

  • 4.4.0-20220221

  • 4.3.0-20220221

Enabled by Default Since

  • Not enabled by default in any Mule version.

Issue ID

  • MULE-20067

mule.setVariable.WithNullValue

When enabled, the Set Variable component creates a variable even if its value is null.

Available Since

  • 4.4.0

  • 4.3.0-20210622

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19443

mule.startExtensionComponentsWithArtifactClassloader

When enabled, extensions are only able to load exported resources from the deployable artifacts (application, policy, domain).

Available Since

  • 4.4.0

  • 4.3.0-20211026

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19815

mule.transformer.toString.transformIteratorElements

When enabled, managed cursor iterators transformed to strings show the representation of the elements instead of generic value org.mule.runtime.core.internal.streaming.object.-ManagedCursorIteratorProvider$ManagedCursorIterator@.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19323

mule.suppress.mule.exceptions

When enabled, error suppression occurs. This feature prevents components such as the Web Service Consumer connector and the Until Successful scope from reporting errors outside their namespaces.

Example of an error log extract for a connectivity error at the Web Service Consumer (HTTP:CONNECTIVITY is being suppressed):

Error type : WSC:INVALID_WSDL
Caused by  : HTTP:CONNECTIVITY

Suppressed errors are treated as underlying causes that can also be matched by On Error handlers.

Available Since

  • 4.4.0-20220922

Enabled by Default Since

  • 4.4.0-20220922

Issue ID

  • W-11778765

mule.errorTypes.lax

When enabled, error types validations are enforced even for error handlers/components that are not referenced.

Available Since

  • 4.4.0-20211227

Enabled by Default Since

  • Not enabled by default in any Mule version.

Issue ID

  • MULE-19879

mule.support.native.library.dependencies

When enabled, if an application accesses a native library, the rest of its declared native libraries are also loaded. This prevents errors like UnsatisfiedLinkError when the accessed native library depends on another native library. Libraries must be declared at the sharedLibraries configuration following the dependency order, meaning that if library A depends on library B, then A must be declared first. Declaring the native libraries at a domain is also supported.

Available Since

  • 4.4.0-20230417

Enabled by Default Since

  • Not enabled by default in any Mule version.

Issue ID

  • W-11855052

mule.forkJoin.completeChildContextsOnTimeout

When enabled, the processors that perform fork and join work (currently, Scatter-Gather and Parallel For Each routers) complete the child event contexts when a timeout occurs.

Available Since

  • 4.4.0-20250217

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-16941297

## See Also [Configure System Properties](https://docs.mulesoft.com/mule-runtime/4.4/mule-app-properties-system) --- product: Mule Runtime version: 4.6 --- # Feature Flagging Mechanism > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine incorporates a feature flagging mechanism that enables Mule applications to change the behavior of the Mule instance depending on the required minimum Mule version. This feature ensures backward compatibility because it allows Mule applications to continue working on later Mule runtime versions, while new Mule applications can benefit from the latest bug fixes implemented in the Mule instance. The feature flagging mechanism is automatic. For each Mule application deployed to a Mule instance, Mule determines which features are enabled or disabled based on the application’s minimum Mule version configured in the application descriptor file (`mule-artifact.json`) of the Mule app. By default, Mule runtime engine disables any new features or bug fixes that aren’t backward compatible with Mule applications running in earlier Mule versions. However, it is possible to manage the feature flags configured for each Mule application or all applications running in the same Mule instance. ## Configure Feature Flags for a Mule Application To configure feature flags for a Mule application, change the `minMuleVersion` value in the `mule-artifact.json` file of your app. This configuration instructs the Mule instance to run this application implementing all features and bug fixes that were released to that particular version and disabling features and bug fixes that are active by default in later Mule versions. For example, you can run a Mule application in Mule 4.5.0 instructing the Mule instance to apply only the features that don’t change core functionality up to Mule 4.1.0: Example `mule-artifact.json` file { "minMuleVersion": "4.1.0" } ## Configure Feature Flags for the Mule Instance An alternative way to configure feature flags is by using system properties. In this case, you can enable or disable each one of the available feature flags. However, configuring feature flags through system properties applies the changes at the Mule instance level, so all applications deployed to this Mule instance behave according to the configured feature flags. Note that this configuration is compatible with on-premise deployments only because you cannot configure system properties in other deployment targets. For example, you can configure a Mule 4.5.0 instance to enable and disable specific features for all applications running on this instance: Example `wrapper.conf` file … wrapper.java.additional.999=-DHONOUR\_RESERVED\_PROPERTIES\_PROPERTY=true wrapper.java.additional.1000=-DCOMPUTE\_CONNECTION\_ERRORS\_IN\_STATS\_PROPERTY=false ## Feature Flags Reference The following table shows the available feature flags, a description of their functionality, the Mule version in which the flag became available, the earlier minor version releases that enable the flag by default, and the issue ID in which the change was implemented:
Feature FlagDescription

mule.batch.fixed.aggregator.transaction.record.buffer

When enabled, batch aggregators with fixed size aggregators commit only when a full block is processed.

Available Since

  • 4.4.0

  • 4.3.0-20210304

  • 4.2.2-20210304

Enabled by Default Since

Issue ID

  • MULE-19218

mule.compute.connection.errors.in.stats

When enabled, connection errors are computed as part of alerts triggering.

Available Since

  • 4.4.0

  • 4.3.0-20210304

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19020

mule.enable.default.errorhandler.not.rollback.incorrect.tx

When enabled, the default error handler added by the Runtime doesn’t roll back a transaction if it doesn’t correspond to have this roll back made.

Available Since

  • 4.5.0

  • 4.4.0-20211227

  • 4.3.0-20211222

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19919

mule.dw.remove_shadowed_implicit_inputs

When enabled, DataWeave removes implicit inputs when a variable with the same name is declared at the root level.

Available Since

  • 4.4.0-20211026

Enabled by Default Since

  • 4.4.0

Issue ID

  • DW-893

mule.enable.byteBuddy.objectCreation

When enabled, the object’s factories are created with Byte Buddy instead of CGLIB.

Available Since

  • 4.4.0-20220321

  • 4.3.0-20220321

Enabled by Default Since

  • 4.4.0

Deprecated Since

  • 4.5.0, ByteBuddy is mandatory

Issue ID

  • W-10672687

mule.enable.policy.isolation

When enabled, Mule manages extensions imported by a policy in complete isolation from the extensions imported by the Mule application. Also, validations prevent the use of explicit configurations that the application declared as part of the policy initialization.

Available Since

  • 4.4.0

  • 4.3.0-20210622

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19226

mule.enable.profiling.service

When enabled, the Runtime profiling capabilities become available.

Available Since

  • 4.4.0

Enabled by Default Since

Issue ID

  • MULE-19588

mule.entityResolver.failOnFirstError

When enabled, the Mule XML DSL parser fails when deploying an application that declares a schema that cannot be located. Otherwise, the parser fails if the application also makes use of the namespace to which such a schema is bound.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • EE-7827

mule.force.runtime.profiling.consumers.enablement

When enabled, profiling consumers implemented by the Runtime are enabled by default.

Available Since

  • 4.4.0-20220221

Enabled by Default Since

Issue ID

  • MULE-19967

mule.dw.handle_splitter_exception

When enabled, DataWeave correctly handles internal exceptions while splitting a payload, preventing subsequent serialization errors.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • DW-383

mule.honour.reserved.properties

When enabled, reserved properties such as app.name can’t be overridden by global properties (overrides are ignored).

Available Since

  • 4.4.0

  • 4.3.0-20220221

Enabled by Default Since

  • 4.4.0, 4.3.0

Issue ID

  • MULE-17659

mule.honourErrorMappingsWhenPolicyAppliedOnOperation

When enabled, the operation policy’s error resolution is ignored. Therefore, the error mappings of the processor on which the policy is applied are set successfully.

Available Since

  • 4.5.0

  • 4.4.0-20220722

  • 4.3.0-20220725

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11147961

mule.detailedCompositeRoutingExceptionLog

When enabled, AbstractForkJoinRouter-based processors, such as Parallel For Each and Scatter-Gather routers, now show detailed error information for their failed routes.

Available Since

  • 4.5.0

  • 4.4.0-20220622

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10965130

mule.parallelForeach.flattenMessage

When enabled, if the items to iterate over on a parallel-foreach scope are messages (such as the output of an operation that returns Result objects), they are flattened in a way that is consistent with what the foreach scope does.

Available Since

  • 4.5.0

  • 4.4.0-20220221

  • 4.3.0-20220221

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-20067

mule.setVariable.WithNullValue

When enabled, the Set Variable component creates a variable even if its value is null.

Available Since

  • 4.4.0

  • 4.3.0-20210622

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19443

mule.startExtensionComponentsWithArtifactClassloader

When enabled, extensions are only able to load exported resources from the deployable artifacts (application, policy, domain).

Available Since

  • 4.4.0

  • 4.3.0-20211026

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19815

mule.transformer.toString.transformIteratorElements

When enabled, managed cursor iterators transformed to strings show the representation of the elements instead of generic value org.mule.runtime.core.internal.streaming.object.-ManagedCursorIteratorProvider$ManagedCursorIterator@.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19323

mule.suppress.mule.exceptions

When enabled, error suppression occurs. This feature prevents components such as the Web Service Consumer connector and the Until Successful scope from reporting errors outside their namespaces.

Example of an error log extract for a connectivity error at the Web Service Consumer (HTTP:CONNECTIVITY is being suppressed):

Error type : WSC:INVALID_WSDL
Caused by  : HTTP:CONNECTIVITY

Suppressed errors are treated as underlying causes that can also be matched by On Error handlers.

Available Since

  • 4.4.0-20220922

Enabled by Default Since

  • 4.5.0, 4.4.0-202210, 4.3.0-202210

Issue ID

  • W-11308645

mule.support.native.library.dependencies

When enabled, if an application accesses a native library, the rest of its declared native libraries are also loaded. This prevents errors like UnsatisfiedLinkError when the accessed native library depends on another native library. Libraries must be declared at the sharedLibraries configuration following the dependency order, meaning that if library A depends on library B, then A must be declared first. Declaring the native libraries at a domain is also supported.

Available Since

  • 4.5.0

  • 4.4.0-20230417

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11855052

mule.rethrowExceptionsInIdempotentMessageValidator

When enabled, internal exceptions are rethrown instead of throwing a general MULE:DUPLICATE_MESSAGE when processing an event in the idempotent-message-validator.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11529823

com.mulesoft.dw.xml_reader.honourMixedContentStructure

When this property is set to true, DataWeave retains a mixed-content structure instead of grouping text with mixed content into a single text field.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11071481

ENFORCE_ERROR_TYPES_VALIDATION

When enabled, error types validations are enforced, even for error handlers/components that aren’t being referenced. This feature isn’t configurable by system property.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19879

mule.disable.attribute.parameter.whitespace.trimming

When enabled, the runtime trims whitespaces from parameter values defined at the attribute level in the DSL.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19803

mule.disable.pojo.text.parameter.whitespace.trimming

When enabled, the runtime trims whitespaces from CDATA text parameter of pojos in the DSL.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-20048

mule.enforce.expression.validation

When enabled, expression validations are enforced for targetValue, not allowing a literal value.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19987

mule.enforce.dw.expression.validation

When enabled, expression validations are enforced for all DataWeave expressions.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19967

mule.disable.registryBootstrapOptionalEntries

When enabled, optional attribute in entries in a registry-bootstrap.properties are ignored.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10736301

mule.disable.applyObjectProcessor

When enabled, org.mule.runtime.core.privileged.registry.ObjectProcessor implementations aren’t applied on objects registered into the SimpleRegistry.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-11737

mule.deployment.validateAppModelWithRegionClassloader

When enabled, the application model is validated with the region classloader. When disabled, it is validated with the application classloader.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10808757

mule.suppress.mule.exceptions

When enabled, error suppression happens. This affects, for example, the Web Service Consumer connector and the Until Successful scope that always reports errors from their corresponding namespaces (MULE and WSC). Suppressed errors are treated as underlying causes.

Available Since

  • 4.5.0

  • 4.4.0-202210

Enabled by Default Since

  • 4.5.0, 4.4.0-202210, 4.3.0-202210

Issue ID

  • W-11308645

mule.foreachRouterRejectsMapExpressions

When enabled, the 'foreach' router generates an IllegalArgumentException if the collection expression evaluates to a java.util.Map.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-12207110

mule.honour.insecure.tls.configuration

When enabled, the insecure TLS configuration is honored even if there are fields of the TrustStore configured.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10822938

mule.transaction.sink.index

When enabled, flux sinks are cached using index as part of the key. If a sink is already in use, a new sink is created.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.0.0, 4.1.0, 4.2.0, 4.3.0, 4.4.0, 4.5.0

Issue ID

  • W-12128703

mule.enable.policy.context.parallel.scopes

When enabled, a new (Source) Policy Context is created for the execution of parallel scopes: ParallelForeach, ScatterGather, and Async.

Available Since

  • 4.5.0

  • 4.4.0-202306

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-13509911

mule.disableJmx.for.commons.pool2

When enabled, MBeans aren’t registered for commons-pool2.

Available Since

  • 4.6.0

Enabled by Default Since

  • 4.6.0

Issue ID

  • W-12422473

mule.disable.scheduler.logging

When enabled, the Scheduler doesn’t log exceptions.

Available Since

  • 4.6.0

  • 4.5.1

  • 4.4.0-20231026

Enabled by Default Since

  • 4.6.0

Issue ID

  • W-13881167

mule.forkJoin.completeChildContextsOnTimeout

When enabled, the processors that perform fork and join work (currently, Scatter-Gather and Parallel For Each routers) complete the child event contexts when a timeout occurs.

Available Since

  • 4.6.14

  • 4.4.0-20250217

Enabled by Default Since

  • 4.10.0

Issue ID

  • W-16941297

mule.forcefulShutdown.raiseCancelledError

When set to true, events cancelled during a forceful shutdown raise a MULE:CANCELLED error instead of MULE:UNKNOWN. Dynamic configuration creation attempts during shutdown also raise a MULE:CANCELLED error instead of MULE:UNKNOWN.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

  • 4.6.24

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-19648397

mule.propagate.objectStore.customization.to.policies

When set to true, policies use the object store implementation configured for the application. This enables alternative implementations, such as Object Store v2, to be used by policies.

Available Since

  • 4.11.2

  • 4.9.15

  • 4.6.28

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-19607093

mule.enable.inline.tls.context.initialization

When set to true, inline TLS contexts invoke their lifecycle initialization method, ensuring inline TLS contexts are fully initialized before use.

Available Since

  • 4.11.3

  • 4.9.16

  • 4.6.29

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-20038933

mule.put.trace.id.and.span.id.in.mdc

When enabled, the trace ID and span ID are added to the MDC when available.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-12979787

mule.enable.mule.specific.tracing.information

When enabled, the ancestor-mule-span-id value is added in the trace state when a span is propagated.

Available Since

  • 4.5.0

Enabled by Default Since

Issue ID

  • W-13215870

mule.tx.error.when.timeout

When enabled, an error is thrown when a local or XA transaction reach timeout. This error can be handled using error handling.

Available Since

  • 4.6.1

Enabled by Default Since

  • 4.6.1

Issue ID

  • W-14608096

mule.enable.xml.sdk.mdc.reset

When enabled, the MDC context resets after XML SDK operation is executed.

Available Since

  • 4.8.0

  • 4.7.1

  • 4.6.4

  • 4.4.0-202406

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15206528

mule.honour.persisted.flow.state

When enabled, flows honor the state configured in flows.deployment.properties when restarting the app, regardless of the initial state.

Available Since

  • 4.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15750334

mule.disable.optimised.notification.handler.dynamic.resolution.update.based.on.delegate

When disabled, dynamic resolution of notification handling doesn’t occur after the Mule artifact is initialized. This can cause race conditions that affect monitoring metrics.

Available Since

  • 4.8.0

Enabled by Default Since

Issue ID

  • W-16828516

mule.ntlm.avoid.send.payload.on.type1

When enabled, body contents aren’t sent on NTLM type 1 requests. This saves resources by not sending a payload that is never consumed (the server rejects the payload until the dance is completed).

Available Since

  • 4.8.0

Enabled by Default Since

  • 4.9.0

Issue ID

  • W-17107281

mule.repeatableStreaming.bytes.eagerRead

When enabled, the read methods of bytes repeatable streams return immediately with any available data. If disabled, they don’t return until the requested len is fully read. Set this property to true to process SSE events over HTTP as they arrive instead of buffering them.

Available Since

  • 4.10.0

  • 4.9.7

  • 4.6.20

Enabled by Default Since

  • 4.10.0

Issue ID

  • W-18716253

mule.redeliveryPolicy.encode.secureHash

When enabled, the encrypted payload is encoded in hexadecimal format when no Expression ID is specified.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-18584560

mule.untilSuccessful.retryOnCriticalError.disallow

When enabled, events aren’t retried if a MULE:CRITICAL error occurs within an until-successful scope.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

  • 4.6.24

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-19648397

mule.flowStop.parallel.enable

When enabled, all Mule flows are stopped in parallel rather than sequentially when a Mule application is stopped. This prevents delays caused by in-flight events in one flow from delaying the shutdown of other flows.

Available Since

  • 4.12.0

  • 4.11.1

  • 4.9.14

  • 4.6.27

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-21228085

## See Also [Configure System Properties](https://docs.mulesoft.com/mule-runtime/4.6/mule-app-properties-system) --- product: Mule Runtime version: 4.9 --- # Feature Flagging Mechanism > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine incorporates a feature flagging mechanism that enables Mule applications to change the behavior of the Mule instance depending on the required minimum Mule version. This feature ensures backward compatibility because it allows Mule applications to continue working on later Mule runtime versions, while new Mule applications can benefit from the latest bug fixes implemented in the Mule instance. The feature flagging mechanism is automatic. For each Mule application deployed to a Mule instance, Mule determines which features are enabled or disabled based on the application’s minimum Mule version configured in the application descriptor file (`mule-artifact.json`) of the Mule app. By default, Mule runtime engine disables any new features or bug fixes that aren’t backward compatible with Mule applications running in earlier Mule versions. However, it is possible to manage the feature flags configured for each Mule application or all applications running in the same Mule instance. ## Understanding minMuleVersion > [!NOTE] If your deployment was rejected because of `minMuleVersion`, set it to the target > runtime’s version or earlier, keeping the patch at `.0` unless you need a backported fix (see > [Adopting a Backported Bug Fix (Advanced)](#adopting-a-backported-bug-fix-advanced)). Don’t set it > to the exact patch of the runtime you built or scaffolded with. `minMuleVersion` declares the minimum runtime feature set that a Mule application requires. Conceptually, this corresponds to the `minor` number in [Semantic Versioning](https://semver.org/). Mule 4 follows Semantic Versioning 2.0.0. Anypoint Studio and Anypoint Code Builder use this value when scaffolding a new application. ### How the Runtime and Tools Check minMuleVersion `minMuleVersion` isn’t only a feature-flag selector. The runtime, and other tools that work with a Mule artifact, compare its `minMuleVersion` against a target version using the full `major.minor.patch`. If the artifact’s `minMuleVersion` is later than the target, it’s rejected. The most visible case is deployment. The runtime refuses to deploy an application whose `minMuleVersion` is later than the running runtime, and reports that the application requires a later runtime version. For example, an application with `minMuleVersion=4.12.2` doesn’t deploy on a `4.12.1` runtime, even though the two only differ in patch. To check the version of the target runtime in CloudHub, CloudHub 2.0, Runtime Fabric, or a server managed by Runtime Manager, check the environment or instance details in Runtime Manager. On a standalone on-premises server, run `./mule -version` or check the startup log. The same comparison also happens outside the deployment cycle. Any tooling that reads a Mule artifact without deploying it applies the same check. For example, a service that introspects an application’s flows to list its triggers compares the artifact’s `minMuleVersion` exactly as deployment does. So does Anypoint Exchange when it extracts metadata as you publish an asset. Over-declaring `minMuleVersion` can therefore cause an artifact to be rejected by such tooling even when you aren’t deploying it. This comparison is patch-sensitive by design. That’s what makes the backported bug fixes described in [Adopting a Backported Bug Fix (Advanced)](#adopting-a-backported-bug-fix-advanced) possible. Raising the patch of `minMuleVersion` is how an application opts into a backported bug fix. ### Choosing the Value Set `minMuleVersion` to the earliest Mule version whose feature set your application needs, not the latest patch of whatever runtime you happened to build or scaffold with. Declaring a later version than necessary is called over-declaring, and it can prevent an otherwise-compatible runtime or tool from accepting the application. Setting `minMuleVersion` to an earlier version has a trade-off too: It disables any feature or bug fix enabled by default between the new value and the version the application previously declared. Choose the earliest version whose behavior your application relies on, not an arbitrarily early one. ### Adopting a Backported Bug Fix (Advanced) The `patch` component of `minMuleVersion` (the third number, for example, the `2` in `4.12.2`) only matters for one corner case: a bug fix backported into a patch release instead of shipping with the next minor version. This typically results from an escalated product request. The [Feature Flags Reference](#feature-flags-reference) table documents these cases. Most flags become available at a minor release, but a few become available at a patch release, for example, `mule.tx.error.when.timeout`, available since Mule 4.6.1. Like every entry in that table, a backported bug fix is disabled by default, so an application relying on the preexisting behavior isn’t affected by upgrading the runtime. Enabling it is a deliberate opt-in. On an on-premises Mule instance, the recommended way to opt in to a backported fix (or any flag) is to configure it explicitly through a system property, as described in [Configure Feature Flags for the Mule Instance](#configure-feature-flags-for-the-mule-instance), rather than by bumping the patch component of `minMuleVersion`. Raising the patch changes every flag available since that patch at once, including ones you didn’t intend to adopt, and it also tightens the compatibility check described in [How the Runtime and Tools Check minMuleVersion](#how-the-runtime-and-tools-check-minmuleversion). Only set a patch-level `minMuleVersion` when all these conditions are true: - The application depends on a specific backported fix. - The deployment target doesn’t support a system-property override. - MuleSoft Support has directed you to do so. Otherwise, leave the patch at `.0`. For the full list of fields in `mule-artifact.json`, including `minMuleVersion`, see [Application Descriptor Reference (mule-artifact.json)](https://docs.mulesoft.com/mule-runtime/4.9/mule-artifact-json). ## Configure Feature Flags for a Mule Application To configure feature flags for a Mule application, change the `minMuleVersion` value in the `mule-artifact.json` file of your app. With this configuration, the Mule instance runs the application using all features and bug fixes that were released to that particular version. The instance disables features and bug fixes that are active by default in later Mule versions. For example, you can run a Mule application in Mule 4.5.0 instructing the Mule instance to apply only the features that don’t change core functionality up to Mule 4.1.0: Example `mule-artifact.json` file { "minMuleVersion": "4.1.0" } > [!NOTE] This example intentionally uses an earlier version, `4.1.0`, to illustrate selecting an > earlier feature set. It’s not a recommended value for a new application. See > [Understanding minMuleVersion](#understanding-minmuleversion). ## Configure Feature Flags for the Mule Instance An alternative way to configure feature flags is by using system properties. In this case, you can enable or disable each one of the available feature flags. However, configuring feature flags through system properties applies the changes at the Mule instance level, so all applications deployed to this Mule instance behave according to the configured feature flags. Note that this configuration is compatible with on-premise deployments only because you cannot configure system properties in other deployment targets. For example, you can configure a Mule 4.5.0 instance to enable and disable specific features for all applications running on this instance: Example `wrapper.conf` file … wrapper.java.additional.999=-DHONOUR\_RESERVED\_PROPERTIES\_PROPERTY=true wrapper.java.additional.1000=-DCOMPUTE\_CONNECTION\_ERRORS\_IN\_STATS\_PROPERTY=false ## Feature Flags Reference The following table shows the available feature flags, a description of their functionality, the Mule version in which the flag became available, the earlier minor version releases that enable the flag by default, and the issue ID in which the change was implemented:
Feature FlagDescription

mule.batch.fixed.aggregator.transaction.record.buffer

When enabled, batch aggregators with fixed size aggregators commit only when a full block is processed.

Available Since

  • 4.4.0

  • 4.3.0-20210304

  • 4.2.2-20210304

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19218

mule.compute.connection.errors.in.stats

When enabled, connection errors are computed as part of alerts triggering.

Available Since

  • 4.4.0

  • 4.3.0-20210304

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19020

mule.enable.default.errorhandler.not.rollback.incorrect.tx

When enabled, the default error handler added by the Runtime doesn’t roll back a transaction if it doesn’t correspond to have this roll back made.

Available Since

  • 4.5.0

  • 4.4.0-20211227

  • 4.3.0-20211222

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19919

mule.dw.remove_shadowed_implicit_inputs

When enabled, DataWeave removes implicit inputs when a variable with the same name is declared at the root level.

Available Since

  • 4.5.0

  • 4.4.0-20211026

Enabled by Default Since

  • 4.4.0

Issue ID

  • DW-893

mule.enable.policy.isolation

When enabled, Mule manages extensions imported by a policy in complete isolation from the extensions imported by the Mule application. Also, validations prevent the use of explicit configurations that the application declared as part of the policy initialization.

Available Since

  • 4.4.0

  • 4.3.0-20210622

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19226

mule.enable.profiling.service

When enabled, the Runtime profiling capabilities become available.

Available Since

  • 4.4.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19588

mule.entityResolver.failOnFirstError

When enabled, the Mule XML DSL parser fails when deploying an application that declares a schema that cannot be located. Otherwise, the parser fails if the application also makes use of the namespace to which such a schema is bound.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • EE-7827

mule.force.runtime.profiling.consumers.enablement

When enabled, profiling consumers implemented by the Runtime are enabled by default.

Available Since

  • 4.5.0

  • 4.4.0-20220221

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19967

mule.dw.handle_splitter_exception

When enabled, DataWeave correctly handles internal exceptions while splitting a payload, preventing subsequent serialization errors.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • DW-383

mule.honour.reserved.properties

When enabled, reserved properties such as app.name can’t be overridden by global properties (overrides are ignored).

Available Since

  • 4.4.0

  • 4.3.0-20220221

Enabled by Default Since

  • 4.3.0

Issue ID

  • MULE-17659

mule.honourErrorMappingsWhenPolicyAppliedOnOperation

When enabled, the operation policy’s error resolution is ignored. Therefore, the error mappings of the processor on which the policy is applied are set successfully.

Available Since

  • 4.5.0

  • 4.4.0-20220722

  • 4.3.0-20220725

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11147961

mule.detailedCompositeRoutingExceptionLog

When enabled, AbstractForkJoinRouter-based processors, such as Parallel For Each and Scatter-Gather routers, now show detailed error information for their failed routes.

Available Since

  • 4.5.0

  • 4.4.0-20220622

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10965130

mule.parallelForeach.flattenMessage

When enabled, if the items to iterate over on a parallel-foreach scope are messages (such as the output of an operation that returns Result objects), they are flattened in a way that is consistent with what the foreach scope does.

Available Since

  • 4.5.0

  • 4.4.0-20220221

  • 4.3.0-20220221

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-20067

mule.setVariable.WithNullValue

When enabled, the Set Variable component creates a variable even if its value is null.

Available Since

  • 4.4.0

  • 4.3.0-20210622

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19443

mule.startExtensionComponentsWithArtifactClassloader

When enabled, extensions are only able to load exported resources from the deployable artifacts (application, policy, domain).

Available Since

  • 4.4.0

  • 4.3.0-20211026

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19815

mule.transformer.toString.transformIteratorElements

When enabled, managed cursor iterators transformed to strings show the representation of the elements instead of generic value org.mule.runtime.core.internal.streaming.object.-ManagedCursorIteratorProvider$ManagedCursorIterator@.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19323

mule.suppress.mule.exceptions

When enabled, error suppression occurs. This feature prevents components such as the Web Service Consumer connector and the Until Successful scope from reporting errors outside their namespaces.

Example of an error log extract for a connectivity error at the Web Service Consumer (HTTP:CONNECTIVITY is being suppressed):

Error type : WSC:INVALID_WSDL
Caused by  : HTTP:CONNECTIVITY

Suppressed errors are treated as underlying causes that can also be matched by On Error handlers.

Available Since

  • 4.4.0-20220922

Enabled by Default Since

  • Enabled by default in every Mule version

Issue ID

  • W-11308645

mule.support.native.library.dependencies

When enabled, if an application accesses a native library, the rest of its declared native libraries are also loaded. This prevents errors like UnsatisfiedLinkError when the accessed native library depends on another native library. Libraries must be declared at the sharedLibraries configuration following the dependency order, meaning that if library A depends on library B, then A must be declared first. Declaring the native libraries at a domain is also supported.

Available Since

  • 4.5.0

  • 4.4.0-20230417

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11855052

mule.rethrowExceptionsInIdempotentMessageValidator

When enabled, internal exceptions are rethrown instead of throwing a general MULE:DUPLICATE_MESSAGE when processing an event in the idempotent-message-validator.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11529823

com.mulesoft.dw.xml_reader.honourMixedContentStructure

When this property is set to true, DataWeave retains a mixed-content structure instead of grouping text with mixed content into a single text field.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11071481

ENFORCE_ERROR_TYPES_VALIDATION

When enabled, error types validations are enforced, even for error handlers/components that aren’t being referenced. This feature isn’t configurable by system property.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19879

mule.disable.attribute.parameter.whitespace.trimming

When enabled, the runtime trims whitespaces from parameter values defined at the attribute level in the DSL.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19803

mule.disable.pojo.text.parameter.whitespace.trimming

When enabled, the runtime trims whitespaces from CDATA text parameter of pojos in the DSL.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-20048

mule.enforce.expression.validation

When enabled, expression validations are enforced for targetValue, not allowing a literal value.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19987

mule.enforce.dw.expression.validation

When enabled, expression validations are enforced for all DataWeave expressions.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19967

mule.disable.registryBootstrapOptionalEntries

When enabled, optional attribute in entries in a registry-bootstrap.properties are ignored.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Deprecated Since

  • 4.9.0, the optional attribute in entries is no longer supported

Issue ID

  • W-10736301

mule.disable.applyObjectProcessor

When enabled, org.mule.runtime.core.privileged.registry.ObjectProcessor implementations aren’t applied on objects registered into the SimpleRegistry.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-11737

mule.deployment.validateAppModelWithRegionClassloader

When enabled, the application model is validated with the region classloader. When disabled, it is validated with the application classloader.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10808757

mule.suppress.mule.exceptions

When enabled, error suppression happens. This affects, for example, the Web Service Consumer connector and the Until Successful scope that always reports errors from their corresponding namespaces (MULE and WSC). Suppressed errors are treated as underlying causes.

Available Since

  • 4.5.0

  • 4.4.0-202210

Enabled by Default Since

  • Enabled by default in every Mule version

Issue ID

  • W-11308645

mule.foreachRouterRejectsMapExpressions

When enabled, the 'foreach' router generates an IllegalArgumentException if the collection expression evaluates to a java.util.Map.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-12207110

mule.honour.insecure.tls.configuration

When enabled, the insecure TLS configuration is honored even if there are fields of the TrustStore configured.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10822938

mule.transaction.sink.index

When enabled, flux sinks are cached using index as part of the key. If a sink is already in use, a new sink is created.

Available Since

  • 4.4.0

Enabled by Default Since

  • Enabled by default in every Mule version

Issue ID

  • W-12128703

mule.enable.policy.context.parallel.scopes

When enabled, a new (Source) Policy Context is created for the execution of parallel scopes: ParallelForeach, ScatterGather, and Async.

Available Since

  • 4.5.0

  • 4.4.0-202306

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-13509911

mule.put.trace.id.and.span.id.in.mdc

When enabled, the trace ID and span ID are added to the MDC when available.

Available Since

  • 4.5.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-12979787

mule.enable.mule.specific.tracing.information

When enabled, the ancestor-mule-span-id value is added in the trace state when a span is propagated.

Available Since

  • 4.5.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-13215870

mule.disableJmx.for.commons.pool2

When enabled, MBeans aren’t registered for commons-pool2.

Available Since

  • 4.6.0

Enabled by Default Since

  • 4.6.0

Issue ID

  • W-12422473

mule.disable.scheduler.logging

When enabled, the Scheduler doesn’t log exceptions.

Available Since

  • 4.6.0

Enabled by Default Since

  • 4.6.0

Issue ID

  • W-13881167

mule.tx.error.when.timeout

When enabled, an error is thrown when a local or XA transaction reach timeout. This error can be handled using error handling.

Available Since

  • 4.6.1

Enabled by Default Since

  • 4.6.1

Issue ID

  • W-14608096

mule.disableXmlSdkImplicitConfigurationCreation

When enabled, implicit configuration for the XML SDK isn’t created.

Available Since

  • 4.7.0

Enabled by Default Since

  • 4.7.0

Issue ID

  • W-10634129

mule.enable.xml.sdk.mdc.reset

When enabled, the MDC context resets after XML SDK operation is executed.

Available Since

  • 4.8.0

  • 4.7.1

  • 4.6.4

  • 4.4.0-20240522

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15206528

mule.unsupportedExtensionsClientRunAsync

When enabled, org.mule.runtime.extension.api.client.ExtensionsClient deprecated methods (executeAsync(String, String, OperationParameters) and execute(String, String, OperationParameters)) throw an UnsupportedOperationException.

Available Since

  • 1.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15399821

ENFORCE_IMPORT_TARGET_SAME_TYPE

When enabled, the root element of import targets are validated to be the same as the importing configuration.

Available Since

  • 4.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15509819

mule.honour.persisted.flow.state

When enabled, flows honor the state configured in flows.deployment.properties when restarting the app, regardless of the initial state.

Available Since

  • 4.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15750334

mule.ntlm.avoid.send.payload.on.type1

When enabled, body contents aren’t sent on NTLM type 1 requests. This saves resources by not sending a payload that is never consumed (the server rejects the payload until the dance is completed).

Available Since

  • 4.9.0

  • 4.8.4

  • 4.6.12

Enabled by Default Since

  • 4.9.0

Issue ID

  • W-17107281

mule.forkJoin.completeChildContextsOnTimeout

When enabled, the processors that perform fork and join work (currently, Scatter-Gather and Parallel For Each routers) complete the child event contexts when a timeout occurs.

Available Since

  • 4.9.2

  • 4.6.14

  • 4.4.0-20250217

Enabled by Default Since

  • 4.10.0

Issue ID

  • W-16941297

mule.forcefulShutdown.raiseCancelledError

When set to true, events cancelled during a forceful shutdown raise a MULE:CANCELLED error instead of MULE:UNKNOWN. Dynamic configuration creation attempts during shutdown also raise a MULE:CANCELLED error instead of MULE:UNKNOWN.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

  • 4.6.24

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-19648397

mule.propagate.objectStore.customization.to.policies

When set to true, policies use the object store implementation configured for the application. This enables alternative implementations, such as Object Store v2, to be used by policies.

Available Since

  • 4.11.2

  • 4.9.15

  • 4.6.28

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-19607093

mule.enable.inline.tls.context.initialization

When set to true, inline TLS contexts invoke their lifecycle initialization method, ensuring inline TLS contexts are fully initialized before use.

Available Since

  • 4.11.3

  • 4.9.16

  • 4.6.29

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-20038933

mule.enable.byteBuddy.objectCreation

When enabled, the object factories are created with Byte Buddy instead of CGLIB.

Available Since

  • 4.4.0-202203

  • 4.3.0-202203

Enabled by Default Since

  • 4.4.0

Deprecated Since

  • 4.5.0, ByteBuddy is mandatory

Issue ID

  • W-10672687

mule.disable.optimised.notification.handler.dynamic.resolution.update.based.on.delegate

When disabled, dynamic resolution of notification handling doesn’t occur after the Mule artifact is initialized. This can cause race conditions that affect monitoring metrics.

Available Since

  • 4.8

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-16828516

mule.repeatableStreaming.bytes.eagerRead

When enabled, the read methods of bytes repeatable streams return immediately with any available data. If disabled, they don’t return until the requested len is fully read. Set this property to true to process SSE events over HTTP as they arrive instead of buffering them.

Available Since

  • 4.10.0

  • 4.9.7

  • 4.6.20

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-18716253

mule.redeliveryPolicy.encode.secureHash

When enabled, the encrypted payload is encoded in hexadecimal format when no Expression ID is specified.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-18584560

mule.untilSuccessful.retryOnCriticalError.disallow

When enabled, events aren’t retried if a MULE:CRITICAL error occurs within an until-successful scope.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

  • 4.6.24

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-19648397

mule.flowStop.parallel.enable

When enabled, all flows are stopped in parallel rather than sequentially when a Mule application stops. This prevents delays caused by in-flight events in one flow from delaying the shutdown of other flows.

Available Since

  • 4.12.0

  • 4.11.1

  • 4.9.14

  • 4.6.27

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-21228085

## See Also [Configure System Properties](https://docs.mulesoft.com/mule-runtime/4.9/mule-app-properties-system) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Feature Flagging Mechanism > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine incorporates a feature flagging mechanism that enables Mule applications to change the behavior of the Mule instance depending on the required minimum Mule version. This feature ensures backward compatibility because it allows Mule applications to continue working on later Mule runtime versions, while new Mule applications can benefit from the latest bug fixes implemented in the Mule instance. The feature flagging mechanism is automatic. For each Mule application deployed to a Mule instance, Mule determines which features are enabled or disabled based on the application’s minimum Mule version configured in the application descriptor file (`mule-artifact.json`) of the Mule app. By default, Mule runtime engine disables any new features or bug fixes that aren’t backward compatible with Mule applications running in earlier Mule versions. However, it is possible to manage the feature flags configured for each Mule application or all applications running in the same Mule instance. ## Understanding minMuleVersion > [!NOTE] If your deployment was rejected because of `minMuleVersion`, set it to the target > runtime’s version or earlier, keeping the patch at `.0` unless you need a backported fix (see > [Adopting a Backported Bug Fix (Advanced)](#adopting-a-backported-bug-fix-advanced)). Don’t set it > to the exact patch of the runtime you built or scaffolded with. `minMuleVersion` declares the minimum runtime feature set that a Mule application requires. Conceptually, this corresponds to the `minor` number in [Semantic Versioning](https://semver.org/). Mule 4 follows Semantic Versioning 2.0.0. Anypoint Studio and Anypoint Code Builder use this value when scaffolding a new application. ### How the Runtime and Tools Check minMuleVersion `minMuleVersion` isn’t only a feature-flag selector. The runtime, and other tools that work with a Mule artifact, compare its `minMuleVersion` against a target version using the full `major.minor.patch`. If the artifact’s `minMuleVersion` is later than the target, it’s rejected. The most visible case is deployment. The runtime refuses to deploy an application whose `minMuleVersion` is later than the running runtime, and reports that the application requires a later runtime version. For example, an application with `minMuleVersion=4.12.2` doesn’t deploy on a `4.12.1` runtime, even though the two only differ in patch. To check the version of the target runtime in CloudHub, CloudHub 2.0, Runtime Fabric, or a server managed by Runtime Manager, check the environment or instance details in Runtime Manager. On a standalone on-premises server, run `./mule -version` or check the startup log. The same comparison also happens outside the deployment cycle. Any tooling that reads a Mule artifact without deploying it applies the same check. For example, a service that introspects an application’s flows to list its triggers compares the artifact’s `minMuleVersion` exactly as deployment does. So does Anypoint Exchange when it extracts metadata as you publish an asset. Over-declaring `minMuleVersion` can therefore cause an artifact to be rejected by such tooling even when you aren’t deploying it. This comparison is patch-sensitive by design. That’s what makes the backported bug fixes described in [Adopting a Backported Bug Fix (Advanced)](#adopting-a-backported-bug-fix-advanced) possible. Raising the patch of `minMuleVersion` is how an application opts into a backported bug fix. ### Choosing the Value Set `minMuleVersion` to the earliest Mule version whose feature set your application needs, not the latest patch of whatever runtime you happened to build or scaffold with. Declaring a later version than necessary is called over-declaring, and it can prevent an otherwise-compatible runtime or tool from accepting the application. Setting `minMuleVersion` to an earlier version has a trade-off too: It disables any feature or bug fix enabled by default between the new value and the version the application previously declared. Choose the earliest version whose behavior your application relies on, not an arbitrarily early one. ### Adopting a Backported Bug Fix (Advanced) The `patch` component of `minMuleVersion` (the third number, for example, the `2` in `4.12.2`) only matters for one corner case: a bug fix backported into a patch release instead of shipping with the next minor version. This typically results from an escalated product request. The [Feature Flags Reference](#feature-flags-reference) table documents these cases. Most flags become available at a minor release, but a few become available at a patch release, for example, `mule.tx.error.when.timeout`, available since Mule 4.6.1. Like every entry in that table, a backported bug fix is disabled by default, so an application relying on the preexisting behavior isn’t affected by upgrading the runtime. Enabling it is a deliberate opt-in. On an on-premises Mule instance, the recommended way to opt in to a backported fix (or any flag) is to configure it explicitly through a system property, as described in [Configure Feature Flags for the Mule Instance](#configure-feature-flags-for-the-mule-instance), rather than by bumping the patch component of `minMuleVersion`. Raising the patch changes every flag available since that patch at once, including ones you didn’t intend to adopt, and it also tightens the compatibility check described in [How the Runtime and Tools Check minMuleVersion](#how-the-runtime-and-tools-check-minmuleversion). Only set a patch-level `minMuleVersion` when all these conditions are true: - The application depends on a specific backported fix. - The deployment target doesn’t support a system-property override. - MuleSoft Support has directed you to do so. Otherwise, leave the patch at `.0`. For the full list of fields in `mule-artifact.json`, including `minMuleVersion`, see [Application Descriptor Reference (mule-artifact.json)](https://docs.mulesoft.com/mule-runtime/latest/mule-artifact-json). ## Configure Feature Flags for a Mule Application To configure feature flags for a Mule application, change the `minMuleVersion` value in the `mule-artifact.json` file of your app. With this configuration, the Mule instance runs the application using all features and bug fixes that were released to that particular version. The instance disables features and bug fixes that are active by default in later Mule versions. For example, you can run a Mule application in Mule 4.5.0 instructing the Mule instance to apply only the features that don’t change core functionality up to Mule 4.1.0: Example `mule-artifact.json` file { "minMuleVersion": "4.1.0" } > [!NOTE] This example intentionally uses an earlier version, `4.1.0`, to illustrate selecting an > earlier feature set. It’s not a recommended value for a new application. See > [Understanding minMuleVersion](#understanding-minmuleversion). ## Configure Feature Flags for the Mule Instance An alternative way to configure feature flags is by using system properties. In this case, you can enable or disable each one of the available feature flags. However, configuring feature flags through system properties applies the changes at the Mule instance level, so all applications deployed to this Mule instance behave according to the configured feature flags. Note that this configuration is compatible with on-premise deployments only because you cannot configure system properties in other deployment targets. For example, you can configure a Mule 4.5.0 instance to enable and disable specific features for all applications running on this instance: Example `wrapper.conf` file … wrapper.java.additional.999=-DHONOUR\_RESERVED\_PROPERTIES\_PROPERTY=true wrapper.java.additional.1000=-DCOMPUTE\_CONNECTION\_ERRORS\_IN\_STATS\_PROPERTY=false ## Feature Flags Reference The following table shows the available feature flags, a description of their functionality, the Mule version in which the flag became available, the earlier minor version releases that enable the flag by default, and the issue ID in which the change was implemented:
Feature FlagDescription

mule.batch.fixed.aggregator.transaction.record.buffer

When enabled, batch aggregators with fixed size aggregators commit only when a full block is processed.

Available Since

  • 4.4.0

  • 4.3.0-20210304

  • 4.2.2-20210304

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19218

mule.compute.connection.errors.in.stats

When enabled, connection errors are computed as part of alerts triggering.

Available Since

  • 4.4.0

  • 4.3.0-20210304

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19020

mule.enable.default.errorhandler.not.rollback.incorrect.tx

When enabled, the default error handler added by the Runtime doesn’t roll back a transaction if it doesn’t correspond to have this roll back made.

Available Since

  • 4.5.0

  • 4.4.0-20211227

  • 4.3.0-20211222

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19919

mule.dw.remove_shadowed_implicit_inputs

When enabled, DataWeave removes implicit inputs when a variable with the same name is declared at the root level.

Available Since

  • 4.5.0

  • 4.4.0-20211026

Enabled by Default Since

  • 4.4.0

Issue ID

  • DW-893

mule.enable.policy.isolation

When enabled, Mule manages extensions imported by a policy in complete isolation from the extensions imported by the Mule application. Also, validations prevent the use of explicit configurations that the application declared as part of the policy initialization.

Available Since

  • 4.4.0

  • 4.3.0-20210622

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19226

mule.enable.profiling.service

When enabled, the Runtime profiling capabilities become available.

Available Since

  • 4.4.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19588

mule.entityResolver.failOnFirstError

When enabled, the Mule XML DSL parser fails when deploying an application that declares a schema that cannot be located. Otherwise, the parser fails if the application also makes use of the namespace to which such a schema is bound.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • EE-7827

mule.force.runtime.profiling.consumers.enablement

When enabled, profiling consumers implemented by the Runtime are enabled by default.

Available Since

  • 4.5.0

  • 4.4.0-20220221

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • MULE-19967

mule.dw.handle_splitter_exception

When enabled, DataWeave correctly handles internal exceptions while splitting a payload, preventing subsequent serialization errors.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • DW-383

mule.honour.reserved.properties

When enabled, reserved properties such as app.name can’t be overridden by global properties (overrides are ignored).

Available Since

  • 4.4.0

  • 4.3.0-20220221

Enabled by Default Since

  • 4.3.0

Issue ID

  • MULE-17659

mule.honourErrorMappingsWhenPolicyAppliedOnOperation

When enabled, the operation policy’s error resolution is ignored. Therefore, the error mappings of the processor on which the policy is applied are set successfully.

Available Since

  • 4.5.0

  • 4.4.0-20220722

  • 4.3.0-20220725

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11147961

mule.detailedCompositeRoutingExceptionLog

When enabled, AbstractForkJoinRouter-based processors, such as Parallel For Each and Scatter-Gather routers, now show detailed error information for their failed routes.

Available Since

  • 4.5.0

  • 4.4.0-20220622

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10965130

mule.parallelForeach.flattenMessage

When enabled, if the items to iterate over on a parallel-foreach scope are messages (such as the output of an operation that returns Result objects), they are flattened in a way that is consistent with what the foreach scope does.

Available Since

  • 4.5.0

  • 4.4.0-20220124

  • 4.3.0-20220124

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-20067

mule.setVariable.WithNullValue

When enabled, the Set Variable component creates a variable even if its value is null.

Available Since

  • 4.4.0

  • 4.3.0-20210622

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19443

mule.startExtensionComponentsWithArtifactClassloader

When enabled, extensions are only able to load exported resources from the deployable artifacts (application, policy, domain).

Available Since

  • 4.4.0

  • 4.3.0-20211026

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19815

mule.transformer.toString.transformIteratorElements

When enabled, managed cursor iterators transformed to strings show the representation of the elements instead of generic value org.mule.runtime.core.internal.streaming.object.-ManagedCursorIteratorProvider$ManagedCursorIterator@.

Available Since

  • 4.4.0

Enabled by Default Since

  • 4.4.0

Issue ID

  • MULE-19323

mule.suppress.mule.exceptions

When enabled, error suppression occurs. This feature prevents components such as the Web Service Consumer connector and the Until Successful scope from reporting errors outside their namespaces.

Example of an error log extract for a connectivity error at the Web Service Consumer (HTTP:CONNECTIVITY is being suppressed):

Error type : WSC:INVALID_WSDL
Caused by  : HTTP:CONNECTIVITY

Suppressed errors are treated as underlying causes that can also be matched by On Error handlers.

Available Since

  • 4.4.0-20220922

Enabled by Default Since

  • Enabled by default in every Mule version

Issue ID

  • W-11308645

mule.support.native.library.dependencies

When enabled, if an application accesses a native library, the rest of its declared native libraries are also loaded. This prevents errors like UnsatisfiedLinkError when the accessed native library depends on another native library. Libraries must be declared at the sharedLibraries configuration following the dependency order, meaning that if library A depends on library B, then A must be declared first. Declaring the native libraries at a domain is also supported.

Available Since

  • 4.5.0

  • 4.4.0-20230417

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11855052

mule.rethrowExceptionsInIdempotentMessageValidator

When enabled, internal exceptions are rethrown instead of throwing a general MULE:DUPLICATE_MESSAGE when processing an event in the idempotent-message-validator.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11529823

com.mulesoft.dw.xml_reader.honourMixedContentStructure

When this property is set to true, DataWeave retains a mixed-content structure instead of grouping text with mixed content into a single text field.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-11071481

ENFORCE_ERROR_TYPES_VALIDATION

When enabled, error types validations are enforced, even for error handlers/components that aren’t being referenced. This feature isn’t configurable by system property.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19879

mule.disable.attribute.parameter.whitespace.trimming

When enabled, the runtime trims whitespaces from parameter values defined at the attribute level in the DSL.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19803

mule.disable.pojo.text.parameter.whitespace.trimming

When enabled, the runtime trims whitespaces from CDATA text parameter of pojos in the DSL.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-20048

mule.enforce.expression.validation

When enabled, expression validations are enforced for targetValue, not allowing a literal value.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19987

mule.enforce.dw.expression.validation

When enabled, expression validations are enforced for all DataWeave expressions.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-19967

mule.disable.registryBootstrapOptionalEntries

When enabled, optional attribute in entries in a registry-bootstrap.properties are ignored.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Deprecated Since

  • 4.9.0, the optional attribute in entries is no longer supported

Issue ID

  • W-10736301

mule.disable.applyObjectProcessor

When enabled, org.mule.runtime.core.privileged.registry.ObjectProcessor implementations aren’t applied on objects registered into the SimpleRegistry.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • MULE-11737

mule.deployment.validateAppModelWithRegionClassloader

When enabled, the application model is validated with the region classloader. When disabled, it is validated with the application classloader.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10808757

mule.suppress.mule.exceptions

When enabled, error suppression happens. This affects, for example, the Web Service Consumer connector and the Until Successful scope that always reports errors from their corresponding namespaces (MULE and WSC). Suppressed errors are treated as underlying causes.

Available Since

  • 4.5.0

  • 4.4.0-202210

Enabled by Default Since

  • Enabled by default in every Mule version

Issue ID

  • W-11308645

mule.foreachRouterRejectsMapExpressions

When enabled, the 'foreach' router generates an IllegalArgumentException if the collection expression evaluates to a java.util.Map.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-12207110

mule.honour.insecure.tls.configuration

When enabled, the insecure TLS configuration is honored even if there are fields of the TrustStore configured.

Available Since

  • 4.5.0

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-10822938

mule.transaction.sink.index

When enabled, flux sinks are cached using index as part of the key. If a sink is already in use, a new sink is created.

Available Since

  • 4.4.0

Enabled by Default Since

  • Enabled by default in every Mule version

Issue ID

  • W-12128703

mule.enable.policy.context.parallel.scopes

When enabled, a new (Source) Policy Context is created for the execution of parallel scopes: ParallelForeach, ScatterGather, and Async.

Available Since

  • 4.5.0

  • 4.4.0-202306

Enabled by Default Since

  • 4.5.0

Issue ID

  • W-13509911

mule.put.trace.id.and.span.id.in.mdc

When enabled, the trace ID and span ID are added to the MDC when available.

Available Since

  • 4.5.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-12979787

mule.enable.mule.specific.tracing.information

When enabled, the ancestor-mule-span-id value is added in the trace state when a span is propagated.

Available Since

  • 4.5.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-13215870

mule.disableJmx.for.commons.pool2

When enabled, MBeans aren’t registered for commons-pool2.

Available Since

  • 4.6.0

Enabled by Default Since

  • 4.6.0

Issue ID

  • W-12422473

mule.disable.scheduler.logging

When enabled, the Scheduler doesn’t log exceptions.

Available Since

  • 4.6.0

Enabled by Default Since

  • 4.6.0

Issue ID

  • W-13881167

mule.tx.error.when.timeout

When enabled, an error is thrown when a local or XA transaction reach timeout. This error can be handled using error handling.

Available Since

  • 4.6.1

Enabled by Default Since

  • 4.6.1

Issue ID

  • W-14608096

mule.disableXmlSdkImplicitConfigurationCreation

When enabled, implicit configuration for the XML SDK isn’t created.

Available Since

  • 4.7.0

Enabled by Default Since

  • 4.7.0

Issue ID

  • W-10634129

mule.enable.xml.sdk.mdc.reset

When enabled, the MDC context resets after XML SDK operation is executed.

Available Since

  • 4.8.0

  • 4.7.1

  • 4.6.4

  • 4.4.0-20240522

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15206528

mule.unsupportedExtensionsClientRunAsync

When enabled, org.mule.runtime.extension.api.client.ExtensionsClient deprecated methods (executeAsync(String, String, OperationParameters) and execute(String, String, OperationParameters)) throw an UnsupportedOperationException.

Available Since

  • 1.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15399821

ENFORCE_IMPORT_TARGET_SAME_TYPE

When enabled, the root element of import targets are validated to be the same as the importing configuration.

Available Since

  • 4.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15509819

mule.honour.persisted.flow.state

When enabled, flows honor the state configured in flows.deployment.properties when restarting the app, regardless of the initial state.

Available Since

  • 4.8.0

Enabled by Default Since

  • 4.8.0

Issue ID

  • W-15750334

mule.ntlm.avoid.send.payload.on.type1

When enabled, body contents aren’t sent on NTLM type 1 requests. This saves resources by not sending a payload that is never consumed (the server rejects the payload until the dance is completed).

Available Since

  • 4.9.0

  • 4.8.4

  • 4.6.12

Enabled by Default Since

  • 4.9.0

Issue ID

  • W-17107281

mule.forkJoin.completeChildContextsOnTimeout

When enabled, the processors that perform fork and join work (currently, Scatter-Gather and Parallel For Each routers) complete the child event contexts when a timeout occurs.

Available Since

  • 4.10.0

  • 4.9.2

  • 4.6.14

  • 4.4.0-20250217

Enabled by Default Since

  • 4.10.0

Issue ID

  • W-16941297

mule.repeatableStreaming.bytes.eagerRead

When enabled, the read methods of bytes repeatable streams return immediately with any available data. If disabled, they don’t return until the requested len is fully read. Set this property to true to process SSE events over HTTP as they arrive instead of buffering them.

Available Since

  • 4.10.0

  • 4.9.7

  • 4.6.20

Enabled by Default Since

  • Not enabled by default in any Mule version

Deprecated Since

  • 4.12.0, this is configurable on streaming configuration. Use the bytes.eagerRead property instead.

Issue ID

  • W-18716253

mule.disable.optimised.notification.handler.dynamic.resolution.update.based.on.delegate

When disabled, dynamic resolution of notification handling doesn’t occur after the Mule artifact is initialized. This can cause race conditions that affect monitoring metrics.

Available Since

  • 4.10.0

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-16828516

mule.redeliveryPolicy.encode.secureHash

When enabled, the encrypted payload is encoded in hexadecimal format when no Expression ID is specified.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-18584560

mule.forcefulShutdown.raiseCancelledError

When enabled, events cancelled during a forceful shutdown raise a MULE:CANCELLED error instead of MULE:UNKNOWN. Dynamic configuration creation attempts during shutdown also raise a MULE:CANCELLED error instead of MULE:UNKNOWN.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

  • 4.6.24

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-19648397

mule.untilSuccessful.retryOnCriticalError.disallow

When enabled, events aren’t retried if a MULE:CRITICAL error occurs within an until-successful scope.

Available Since

  • 4.11.0

  • 4.10.1

  • 4.9.11

  • 4.6.24

Enabled by Default Since

  • 4.11.0

Issue ID

  • W-19648397

mule.batch.record.exceptions.disallow

When enabled, batch processing uses batch errors instead of step exceptions. The DataWeave exception-based bindings Batch::getFirstException(), Batch::getLastException(), Batch::failureExceptionForStep(String), and Batch::getStepExceptions() are replaced by their error-based equivalents Batch::getFirstError(), Batch::getLastError(), Batch::failureErrorForStep(String), and Batch::getStepErrors().

Available Since

  • 4.11.0

  • 4.10.2

  • 4.9.12

  • 4.6.25

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-19607093

mule.netty.redirect.filterSensitiveHeaders

When enabled, the Authorization, Proxy-Authorization, and Expect headers are removed from redirected requests to a different host. This applies only when the HTTP Service implementation is Netty.

Available Since

  • 4.11.0

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-20903125

mule.propagate.objectStore.customization.to.policies

When enabled, policies use the object store implementation configured for the application. This enables alternative implementations, such as Object Store v2, to be used by policies.

Available Since

  • 4.11.1

  • 4.10.3

  • 4.9.13

  • 4.6.26

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-19607093

mule.enable.inline.tls.context.initialization

When enabled, inline TLS contexts invoke their lifecycle initialization method, ensuring inline TLS contexts are fully initialized before use.

Available Since

  • 4.11.3

  • 4.9.16

  • 4.6.29

Enabled by Default Since

  • Not enabled by default in any Mule version

Issue ID

  • W-20038933

mule.flowStop.parallel.enable

When enabled, all Mule flows are stopped in parallel rather than sequentially when a Mule application is stopped. This prevents delays caused by in-flight events in one flow from delaying the shutdown of other flows.

Available Since

  • 4.12.0

  • 4.11.1

  • 4.9.14

  • 4.6.27

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-21228085

mule.serialize.message.in.cache

When enabled, ee:cache persists only the Message instead of the full Event. Java customizations for ee:cache aren’t supported, including custom implementations of cachingStrategy-ref, keyGenerator, responseGenerator, and eventCopyStrategy. After this feature flag is enabled, it can’t be disabled because the format of persisted data is updated.

Available Since

  • 4.12.0

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-21549211

mule.enable.byteBuddy.objectCreation

When enabled, the object factories are created with Byte Buddy instead of CGLIB.

Available Since

  • 4.4.0-202203

  • 4.3.0-202203

Enabled by Default Since

  • 4.4.0

Deprecated Since

  • 4.5.0, ByteBuddy is mandatory

Issue ID

  • W-10672687

ENFORCE_BATCH_AGGREGATOR_VALIDATION

When enabled, batch:aggregator validations are enforced.

Available Since

  • 4.12.0

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-21549351

ENFORCE_POLICY_PROXY_VALIDATION

When enabled, http-policy:proxy completeness validations are enforced.

Available Since

  • 4.12.0

Enabled by Default Since

  • 4.12.0

Issue ID

  • W-21549351

ENABLE_OTEL_FLOW_STATISTICS_DETAILED

When enabled, the OpenTelemetry flow-statistics counters emit one data point per flow, labeled with the mule.flow.name dimension. When disabled, each counter emits a single artifact-level total data point.

Available Since

  • 4.13.0

Enabled by Default Since

  • 4.13.0

Issue ID

  • W-23616483

ENABLE_KRYO_SERIALIZATION_ALLOWLIST

When enabled, the Kryo serialization allowlist is enforced, and only allowlisted classes can be serialized. When disabled, any class can be serialized.

Available Since

  • 4.13.0

Enabled by Default Since

  • 4.13.0

Issue ID

  • W-21381354

## See Also [Configure System Properties](https://docs.mulesoft.com/mule-runtime/latest/mule-app-properties-system) --- product: Mule Runtime version: 4.11 keywords: fips, certifications, security --- # FIPS 140-2 Compliance Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule 4 Runtime can be configured to run in a Federal Information Processing Standard (FIPS) 140-2 certified environment. This includes all Runtime connectors, such as HTTP connector. Note that Mule doesn’t run in FIPS security mode by default. There are two requirements: - Have a certified cryptography module installed in your Java environment - Adjust Mule Runtime settings to run in FIPS security mode > [!NOTE] By default, Government Cloud is configured for FIPS 140-2, so you don’t need to perform > the following steps if you’re using Government Cloud. > > If you’re using Runtime Fabric, see > [Enabling FIPS 140-2 Compliance Mode for Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/enable-fips-140-2-compliance) > instead of performing these steps. ## Assumptions This document assumes that you’re familiar with [FIPS 140-2](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402.pdf), the US government security standard that requires that compliant parties use only cryptographic algorithms and techniques that have been certified by NIST. This document also assumes that you have selected and obtained a [certified security provider](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules). ## Setting Up a FIPS 140-2 Java Environment Mule relies on the Java runtime to provide a FIPS-compliant security module, which is why the first requirement is to have a FIPS 140-2 Java environment properly set up. If you’re setting up your system for FIPS compliance for the first time and you haven’t already configured a certified security provider, you must first [select and obtain one](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules), then set up your Java environment following the instructions specific to your selected provider. Details for this process vary according to your selected security provider. Refer to the documentation for your security provider for complete instructions. > [!IMPORTANT] Starting with Mule 4.9.8, you configure FIPS 140-2 by installing the FIPS license > that MuleSoft provides in the license `.zip` file. To enable FIPS 140-2 compliance, you must > install the FIPS license from the `.zip` package. The non-FIPS license in the same package isn’t > valid for FIPS mode. ### Setup Instructions Using Bouncy Castle Security Provider These instructions demonstrate how to set up a FIPS 140-2 Java environment. - [Setup Instructions in Java 8](#setupjava8) - [Setup Instructions in Java 11 and Later](#setupjava11) #### Setup Instructions in Java 8 These instructions show how to install and configure Bouncy Castle security provider in Java 8. 1. Verify that you’re using Java 8 and `JAVA_HOME` is set. 2. Download the provider files from [the BouncyCastle web page](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 3. Install the required JAR file into the `$JAVA_HOME/lib/ext` folder. Provider:bc-fips-1.0.2.7 TLS: bctls-fips-1.0.24.jar PKIX: bcpkix-fips-1.0.12.jar 4. Register the security provider in the security properties file in the `$JAVA_HOME/lib/security/java.security` folder so that only the Bouncy Castle providers are set: ![A list of security providers where to modify the provider](/mulesoft/current/en-us/mule-runtime/4.11/_images/fips-register-jar.png) 5. Save your changes. #### Setup Instructions in Java 11 and Later These instructions show how to install and configure Bouncy Castle security provider in Java 11 and later. 1. Verify that you’re using Java 11 or later and `JAVA_HOME` is set. 2. Download the provider files from [the BouncyCastle web page](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). Provider:bc-fips-1.0.2.7 TLS: bctls-fips-1.0.24.jar PKIX: bcpkix-fips-1.0.12.jar 3. Register the security provider in the security properties file in the `$JAVA_HOME/conf/security/java.security` folder so that only the Bouncy Castle providers are set. 4. Copy the 3 files downloaded to `/lib/boot` (needed for Mule runtime) and `/mule-agent-plugin/lib` (needed for Runtime Manager agent) folders in Mule runtime. 5. Run `amc_setup` and register Mule runtime. For example, in **Add Server**, you find the registration token `/amc_setup -H d32c4bde-7184-444a-bd87-7a274623e14f---704247 node10 --fips`, where `d32c4bde-7184-444a-bd87-7a274623e14f---704247` is the key from Anypoint Runtime Manager. When configuring Runtime Manager agent, include the `--fips` flag to enable FIPS compliance. If you’re using Government Cloud, also include the `--region us_gov` flag: ./amc\_setup -H --fips --region us\_gov You must pass the `--fips` argument each time you register a Mule runtime in a FIPS-compliant environment. 6. To enable FIPS, update `$MULE_HOME/conf/wrapper.conf`. Add the properties `wrapper.java.additional.=-Dmule.security.model=fips140-2` and `wrapper.java.additional.=-Dmule.cluster.network.encryption.key={someKey}`, where `someKey` is the key from your cluster that needs to be defined if you are using a clustered environment. 7. Get the latest Mule runtime distribution `4.5.x`, which enables providers `BouncyCastleFipsProvider` and `BouncyCastleJsseProvider` and set the algorithms to PKIX. 8. Start Mule runtime. ## Running Mule in FIPS Security Mode After following the steps in [Setting Up a FIPS 140-2 Java Environment](#set_up_environment), set up your Mule instances to work in a FIPS 140-2-compliant environment by updating the configuration of the wrapper that launches the Mule app server. 1. Open your `wrapper.conf` file (located in `$MULE_HOME/conf` folder). 2. Uncomment the line that configures Mule to work in FIPS security mode (as shown). Be sure to replace the `` with the next sequential number in your `wrapper.conf` file. ![A file with configuration settings for enabling FIPS 140-2 mode](/mulesoft/current/en-us/mule-runtime/4.11/_images/fips-wrapper-conf-edit.png) 3. For Java 11 and later, also uncomment this line: ![A code string suggests uncommenting for fips mode](/mulesoft/current/en-us/mule-runtime/4.11/_images/fips-wrapper-conf-edit-modules.png) 4. Set the approved-only Bouncy Castle property to enforce FIPS compliance. Be sure to replace the ``. ![A string of code showing Bouncy Castle approved only as true](/mulesoft/current/en-us/mule-runtime/4.11/_images/fips-approved-only.png) 5. Save your changes. When Mule launches again, the startup readout will indicate that FIPS security mode is enabled. ![A console output showing startup logs for a Mule server with FIPS 140-2 security model enabled](/mulesoft/current/en-us/mule-runtime/4.11/_images/fips-startup.png) With FIPS security mode enabled, Mule automatically restricts protocol negotiations to use only the subset of approved cryptographic cipher suites. Any HTTPS connectors and any other connectors that use a TLS security layer will be affected automatically by this restriction. ### Cluster Environment in FIPS mode If you’re running in FIPS mode with a Mule runtime in a clustered environment, define an encryption key for the cluster. See [Cluster reference](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#cluster_fips) for more insight. ## FIPS 140-2 Compliant Cipher Suites This list contains supported FIPS 140-2 compliant cipher suites. To configure the cipher suite used by on-prem Mule installations, see [Fine-Tuning SSL Connectors](#fine-tuning-ssl-connectors). - TLS\_DHE\_DSS\_WITH\_AES\_128\_CBC\_SHA - TLS\_DHE\_DSS\_WITH\_AES\_256\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDH\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDH\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDH\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDH\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_AES\_128\_GCM\_SHA256 - TLS\_AES\_256\_GCM\_SHA384 - TLS\_AES\_128\_CCM\_SHA256 - TLS\_AES\_128\_CCM\_8\_SHA256 ## FIPS 140-2 Compliant Keystore Formats Keystores or truststores in Mule apps are typically formatted as `PKCS12` or `JKS`. These formats aren’t FIPS compliant. For compliance, convert them to `BCFKS` format. To convert a `JKS` keystore to `BCFKS` format, make sure that you: 1. Use Java 8 or later and make sure that `JAVA_HOME` is set. 2. Download the `bc-fips.jar` file from the [Bouncy Castle website](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 3. Use this example command to convert a keystore to `BCFKS` format: BC\_FIPS\_JAR=${BC\_PATH}/bc-fips-\*.jar # Replace with a correct path OLD\_KEYSTORE="keystore.jks" # Replace with the keystore to convert OLD\_PASSWD="changeit" # Replace with the keystore password NEW\_KEYSTORE="keystore.bcfks" # Replace with the new keystore NEW\_PASSWD="changeit" # Replace with the new keystore password keytool -importkeystore \\ -providerclass org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider \\ -providerpath ${BC\_FIPS\_JAR} \\ -srckeystore ${OLD\_KEYSTORE} -srcstoretype JKS -srcstorepass ${OLD\_PASSWD} \\ -destkeystore ${NEW\_KEYSTORE} -deststoretype BCFKS -deststorepass ${NEW\_PASSWD} > [!IMPORTANT] If you’re using Java 17 or later, add the > `-J--add-exports=java.base/sun.security.provider=ALL-UNNAMED` parameter to the keytool command > before the `-importkeystore` parameter. 4. To use the new keystore or truststore, update the [TLS configuration](https://docs.mulesoft.com/mule-runtime/4.11/tls-configuration) in the Mule configuration file: > [!NOTE] If the source keystore is `PKCS12`, set the parameter `-srcstoretype` to `PKCS12` in the > `keytool` command. ## Fine-Tuning SSL Connectors The Mule conf folder includes two files that allow you to fine-tune the configuration of SSL connectors by manually setting which cipher suites Mule can use and which SSL protocols are allowed: - `tls-default.conf` (Allows fine-tuning when Mule isn’t configured to run in FIPS security mode) - `tls-fips140-2.conf` (Allows fine-tuning when Mule is running in FIPS security mode) Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and SSL protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols. ## Tips and Limitations - The Bouncy Castle security provider bundled with the Mule runtime distribution isn’t FIPS certified. When Mule starts in FIPS security mode, the Bouncy Castle provider isn’t registered or used. - Not all encryption schemes and signatures included in [Mule Cryptography Module](https://docs.mulesoft.com/mule-runtime/4.11/securing#cryptography-module) and [Mule Secure Properties](https://docs.mulesoft.com/mule-runtime/4.11/secure-configuration-properties) configuration options are FIPS compliant. If your application is using an algorithm that isn’t approved for FIPS use, you will get an error at runtime that reads: Could not find encryption algorithm ''. You are running in FIPS mode, so please verify that the algorithm is compliant with FIPS. - Keep in mind that your different environments might have different security configurations, including different encryption schemes and algorithm selections. So you might see this error in certain environments (but not others), depending on how they are set up. - Similarly, enabling FIPS at the OS level, such as on Red Hat, isn’t supported as it causes cipher suite errors during license validation. ## See Also - [Validated FIPS-2 Cryptographic Modules](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules) - [Approved Cryptographic Algorithms](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402annexa.pdf) --- product: Mule Runtime version: 4.12 keywords: fips, certifications, security --- # FIPS 140-2 Compliance Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule 4 Runtime can be configured to run in a Federal Information Processing Standard (FIPS) 140-2 certified environment. This includes all Runtime connectors, such as HTTP connector. Note that Mule doesn’t run in FIPS security mode by default. There are two requirements: - Have a certified cryptography module installed in your Java environment - Adjust Mule Runtime settings to run in FIPS security mode > [!NOTE] By default, Government Cloud is configured for FIPS 140-2, so you don’t need to perform > the following steps if you’re using Government Cloud. > > If you’re using Runtime Fabric, see > [Enabling FIPS 140-2 Compliance Mode for Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/enable-fips-140-2-compliance) > instead of performing these steps. ## Assumptions This document assumes that you’re familiar with [FIPS 140-2](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402.pdf), the US government security standard that requires that compliant parties use only cryptographic algorithms and techniques that have been certified by NIST. This document also assumes that you have selected and obtained a [certified security provider](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules). ## Setting Up a FIPS 140-2 Java Environment Mule relies on the Java runtime to provide a FIPS-compliant security module, which is why the first requirement is to have a FIPS 140-2 Java environment properly set up. If you’re setting up your system for FIPS compliance for the first time and you haven’t already configured a certified security provider, you must first [select and obtain one](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules), then set up your Java environment following the instructions specific to your selected provider. Details for this process vary according to your selected security provider. Refer to the documentation for your security provider for complete instructions. > [!IMPORTANT] Starting with Mule 4.9.8, you configure FIPS 140-2 by installing the FIPS license > that MuleSoft provides in the license `.zip` file. To enable FIPS 140-2 compliance, you must > install the FIPS license from the `.zip` package. The non-FIPS license in the same package isn’t > valid for FIPS mode. ### Setup Instructions Using Bouncy Castle Security Provider These instructions demonstrate how to set up a FIPS 140-2 Java environment. - [Setup Instructions in Java 8](#setupjava8) - [Setup Instructions in Java 11 and Later](#setupjava11) #### Setup Instructions in Java 8 These instructions show how to install and configure Bouncy Castle security provider in Java 8. 1. Verify that you’re using Java 8 and `JAVA_HOME` is set. 2. Download the provider files from [the BouncyCastle web page](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 3. Install the required JAR file into the `$JAVA_HOME/lib/ext` folder. Provider:bc-fips-1.0.2.7 TLS: bctls-fips-1.0.24.jar PKIX: bcpkix-fips-1.0.12.jar 4. Register the security provider in the security properties file in the `$JAVA_HOME/lib/security/java.security` folder so that only the Bouncy Castle providers are set: ![A list of security providers where to modify the provider](/mulesoft/current/en-us/mule-runtime/4.12/_images/fips-register-jar.png) 5. Save your changes. #### Setup Instructions in Java 11 and Later These instructions show how to install and configure Bouncy Castle security provider in Java 11 and later. 1. Verify that you’re using Java 11 or later and `JAVA_HOME` is set. 2. Download the provider files from [the BouncyCastle web page](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). Provider:bc-fips-1.0.2.7 TLS: bctls-fips-1.0.24.jar PKIX: bcpkix-fips-1.0.12.jar 3. Register the security provider in the security properties file in the `$JAVA_HOME/conf/security/java.security` folder so that only the Bouncy Castle providers are set. 4. Copy the 3 files downloaded to `/lib/boot` (needed for Mule runtime) and `/mule-agent-plugin/lib` (needed for Runtime Manager agent) folders in Mule runtime. 5. Run `amc_setup` and register Mule runtime. For example, in **Add Server**, you find the registration token `/amc_setup -H d32c4bde-7184-444a-bd87-7a274623e14f---704247 node10 --fips`, where `d32c4bde-7184-444a-bd87-7a274623e14f---704247` is the key from Anypoint Runtime Manager. When configuring Runtime Manager agent, include the `--fips` flag to enable FIPS compliance. If you’re using Government Cloud, also include the `--region us_gov` flag: ./amc\_setup -H --fips --region us\_gov You must pass the `--fips` argument each time you register a Mule runtime in a FIPS-compliant environment. 6. To enable FIPS, update `$MULE_HOME/conf/wrapper.conf`. Add the properties `wrapper.java.additional.=-Dmule.security.model=fips140-2` and `wrapper.java.additional.=-Dmule.cluster.network.encryption.key={someKey}`, where `someKey` is the key from your cluster that needs to be defined if you are using a clustered environment. 7. Get the latest Mule runtime distribution `4.5.x`, which enables providers `BouncyCastleFipsProvider` and `BouncyCastleJsseProvider` and set the algorithms to PKIX. 8. Start Mule runtime. ## Running Mule in FIPS Security Mode After following the steps in [Setting Up a FIPS 140-2 Java Environment](#set_up_environment), set up your Mule instances to work in a FIPS 140-2-compliant environment by updating the configuration of the wrapper that launches the Mule app server. 1. Open your `wrapper.conf` file (located in `$MULE_HOME/conf` folder). 2. Uncomment the line that configures Mule to work in FIPS security mode (as shown). Be sure to replace the `` with the next sequential number in your `wrapper.conf` file. ![A file with configuration settings for enabling FIPS 140-2 mode](/mulesoft/current/en-us/mule-runtime/4.12/_images/fips-wrapper-conf-edit.png) 3. For Java 11 and later, also uncomment this line: ![A code string suggests uncommenting for fips mode](/mulesoft/current/en-us/mule-runtime/4.12/_images/fips-wrapper-conf-edit-modules.png) 4. Set the approved-only Bouncy Castle property to enforce FIPS compliance. Be sure to replace the ``. ![A string of code showing Bouncy Castle approved only as true](/mulesoft/current/en-us/mule-runtime/4.12/_images/fips-approved-only.png) 5. Save your changes. When Mule launches again, the startup readout will indicate that FIPS security mode is enabled. ![A console output showing startup logs for a Mule server with FIPS 140-2 security model enabled](/mulesoft/current/en-us/mule-runtime/4.12/_images/fips-startup.png) With FIPS security mode enabled, Mule automatically restricts protocol negotiations to use only the subset of approved cryptographic cipher suites. Any HTTPS connectors and any other connectors that use a TLS security layer will be affected automatically by this restriction. ### Cluster Environment in FIPS mode If you’re running in FIPS mode with a Mule runtime in a clustered environment, define an encryption key for the cluster. See [Cluster reference](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#cluster_fips) for more insight. ## FIPS 140-2 Compliant Cipher Suites This list contains supported FIPS 140-2 compliant cipher suites. To configure the cipher suite used by on-prem Mule installations, see [Fine-Tuning SSL Connectors](#fine-tuning-ssl-connectors). - TLS\_DHE\_DSS\_WITH\_AES\_128\_CBC\_SHA - TLS\_DHE\_DSS\_WITH\_AES\_256\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDH\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDH\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDH\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDH\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_AES\_128\_GCM\_SHA256 - TLS\_AES\_256\_GCM\_SHA384 - TLS\_AES\_128\_CCM\_SHA256 - TLS\_AES\_128\_CCM\_8\_SHA256 ## FIPS 140-2 Compliant Keystore Formats Keystores or truststores in Mule apps are typically formatted as `PKCS12` or `JKS`. These formats aren’t FIPS compliant. For compliance, convert them to `BCFKS` format. To convert a `JKS` keystore to `BCFKS` format, make sure that you: 1. Use Java 8 or later and make sure that `JAVA_HOME` is set. 2. Download the `bc-fips.jar` file from the [Bouncy Castle website](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 3. Use this example command to convert a keystore to `BCFKS` format: BC\_FIPS\_JAR=${BC\_PATH}/bc-fips-\*.jar # Replace with a correct path OLD\_KEYSTORE="keystore.jks" # Replace with the keystore to convert OLD\_PASSWD="changeit" # Replace with the keystore password NEW\_KEYSTORE="keystore.bcfks" # Replace with the new keystore NEW\_PASSWD="changeit" # Replace with the new keystore password keytool -importkeystore \\ -providerclass org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider \\ -providerpath ${BC\_FIPS\_JAR} \\ -srckeystore ${OLD\_KEYSTORE} -srcstoretype JKS -srcstorepass ${OLD\_PASSWD} \\ -destkeystore ${NEW\_KEYSTORE} -deststoretype BCFKS -deststorepass ${NEW\_PASSWD} > [!IMPORTANT] If you’re using Java 17 or later, add the > `-J--add-exports=java.base/sun.security.provider=ALL-UNNAMED` parameter to the keytool command > before the `-importkeystore` parameter. 4. To use the new keystore or truststore, update the [TLS configuration](https://docs.mulesoft.com/mule-runtime/4.12/tls-configuration) in the Mule configuration file: > [!NOTE] If the source keystore is `PKCS12`, set the parameter `-srcstoretype` to `PKCS12` in the > `keytool` command. ## Fine-Tuning SSL Connectors The Mule conf folder includes two files that allow you to fine-tune the configuration of SSL connectors by manually setting which cipher suites Mule can use and which SSL protocols are allowed: - `tls-default.conf` (Allows fine-tuning when Mule isn’t configured to run in FIPS security mode) - `tls-fips140-2.conf` (Allows fine-tuning when Mule is running in FIPS security mode) Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and SSL protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols. ## Tips and Limitations - The Bouncy Castle security provider bundled with the Mule runtime distribution isn’t FIPS certified. When Mule starts in FIPS security mode, the Bouncy Castle provider isn’t registered or used. - Not all encryption schemes and signatures included in [Mule Cryptography Module](https://docs.mulesoft.com/mule-runtime/4.12/securing#cryptography-module) and [Mule Secure Properties](https://docs.mulesoft.com/mule-runtime/4.12/secure-configuration-properties) configuration options are FIPS compliant. If your application is using an algorithm that isn’t approved for FIPS use, you will get an error at runtime that reads: Could not find encryption algorithm ''. You are running in FIPS mode, so please verify that the algorithm is compliant with FIPS. - Keep in mind that your different environments might have different security configurations, including different encryption schemes and algorithm selections. So you might see this error in certain environments (but not others), depending on how they are set up. - Similarly, enabling FIPS at the OS level, such as on Red Hat, isn’t supported as it causes cipher suite errors during license validation. ## See Also - [Validated FIPS-2 Cryptographic Modules](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules) - [Approved Cryptographic Algorithms](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402annexa.pdf) --- product: Mule Runtime version: 4.3 keywords: fips, certifications, security --- # FIPS 140-2 Compliance Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule 4 Runtime can be configured to run in a FIPS 140-2 certified environment. This includes all Runtime connectors, such as HTTP connector. Note that Mule does not run in FIPS security mode by default. There are two requirements: - Have a certified cryptography module installed in your Java environment - Adjust Mule Runtime settings to run in FIPS security mode > [!NOTE] By default, Government Cloud is configured for FIPS 140-2, so you do not need to perform > the following steps if you are using Government Cloud. > > If you are using Runtime Fabric, see > [Enabling FIPS 140-2 Compliance Mode for Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/enable-fips-140-2-compliance) > instead of performing these steps. ## Assumptions This document assumes that you are familiar with [FIPS 140-2](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402.pdf), the US government security standard that requires that compliant parties use only cryptographic algorithms and techniques that have been certified by NIST. This document also assumes that you have selected and obtained a [certified security provider](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules). ## Setting Up a FIPS 140-2 Java Environment Mule relies on the Java runtime to provide a FIPS-compliant security module, which is why the first requirement is to have a FIPS 140-2 Java environment properly set up. If you are setting up your system for FIPS compliance for the first time and you have not already configured a certified security provider, you must first [select and obtain one](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules), then set up your Java environment following the instructions specific to your selected provider. Details for this process vary according to your selected security provider. Please refer to the documentation for your security provider for complete instructions. ### Example: Setup Instructions Using Bouncy Castle Security Provider The following example demonstrates how to install and configure Bouncy Castle security provider. 1. Download the provider files from [the BouncyCastle web page](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 2. Install the required JAR file into the `$JAVA_HOME/lib/ext` folder: ![FIPS-install-jars](/mulesoft/current/en-us/mule-runtime/4.3/_images/fips-install-jars.png) 3. Register the security provider in the security properties file in the `$JAVA_HOME/lib/security` folder: 1. Open the `java.security` file to add your provider’s class (for example, `org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider`) as the first item in the list of providers. 2. Modify the line with SSL provider to use the Bouncy Castle provider (`security.provider.4=com.sun.net.ssl.internal.ssl.Provider BCFIPS`): ![FIPS-register-jar](/mulesoft/current/en-us/mule-runtime/4.3/_images/fips-register-jar.png) 4. Adjust the numbering of the other security providers in the file so that they remain sequential. ![FIPS-register-jar-renumber](/mulesoft/current/en-us/mule-runtime/4.3/_images/fips-register-jar-renumber.png) 5. Save your changes. ## Running Mule in FIPS Security Mode After following the steps in [Setting Up a FIPS 140-2 Java Environment](#set_up_environment), set up your Mule instances to work in a FIPS 140-2-compliant environment by updating the configuration of the wrapper that launches the Mule app server. 1. Open your `wrapper.conf` file (located in `$MULE_HOME/conf` folder). 2. Uncomment the line that configures Mule to work in FIPS security mode (as shown). Be sure to replace the `` with the next sequential number in your `wrapper.conf` file. ![FIPS-wrapper-conf-edit](/mulesoft/current/en-us/mule-runtime/4.3/_images/fips-wrapper-conf-edit.png) 3. Save your changes. When Mule launches again, the startup readout will indicate that FIPS security mode is enabled. ![FIPS-startup](/mulesoft/current/en-us/mule-runtime/4.3/_images/fips-startup.png) With FIPS security mode enabled, Mule automatically restricts protocol negotiations to use only the subset of approved cryptographic cipher suites. Any HTTPS connectors and any other connectors that use a TLS security layer will be affected automatically by this restriction. ### Cluster Environment in FIPS mode If you are running in FIPS mode with a Mule Runtime in a clustered environment, you should define an encryption key for the cluster. See [Cluster reference](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#cluster_fips) for more insight. ## FIPS 140-2 Compliant Cipher Suites The following list contains supported FIPS 140-2 compliant cipher suites. To configure the cipher suite used by on-prem Mule installations, see [Fine-Tuning SSL Connectors](#fine-tuning-ssl-connectors). - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_DHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA ## Fine-Tuning SSL Connectors The Mule conf folder includes two files that allow you to fine-tune the configuration of SSL connectors by manually setting which cipher suites Mule can use and which SSL protocols are allowed: - `tls-default.conf` (Allows fine-tuning when Mule is not configured to run in FIPS security mode) - `tls-fips140-2.conf` (Allows fine-tuning when Mule is running in FIPS security mode) Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and SSL protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols. ## Tips and Limitations - The Bouncy Castle security provider bundled with the Mule Runtime distribution is not FIPS certified. When Mule starts in FIPS security mode, the Bouncy Castle provider is not registered or used. - Not all encryption schemes and signatures included in [Mule Cryptography Module](https://docs.mulesoft.com/mule-runtime/4.3/securing#cryptography-module) and [Mule Secure Properties](https://docs.mulesoft.com/mule-runtime/4.3/secure-configuration-properties) configuration options are FIPS compliant. If your application is using an algorithm that is not approved for FIPS use, you will get an error at runtime that reads: Could not find encryption algorithm ''. You are running in FIPS mode, so please verify that the algorithm is compliant with FIPS. - Keep in mind that your different environments might have different security configurations, including different encryption schemes and algorithm selections. So you might see this error in certain environments (but not others), depending on how they are set up. ## See Also [Validated FIPS-2 Cryptographic Modules](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules) [Approved Cryptographic Algorithms](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402annexa.pdf) --- product: Mule Runtime version: 4.4 keywords: fips, certifications, security --- # FIPS 140-2 Compliance Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule 4 Runtime can be configured to run in a FIPS 140-2 certified environment. This includes all Runtime connectors, such as HTTP connector. Note that Mule doesn’t run in FIPS security mode by default. There are two requirements: - Have a certified cryptography module installed in your Java environment - Adjust Mule Runtime settings to run in FIPS security mode > [!NOTE] By default, Government Cloud is configured for FIPS 140-2, so you don’t need to perform > the following steps if you are using Government Cloud. > > If you are using Runtime Fabric, see > [Enabling FIPS 140-2 Compliance Mode for Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/enable-fips-140-2-compliance) > instead of performing these steps. ## Assumptions This document assumes that you are familiar with [FIPS 140-2](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402.pdf), the US government security standard that requires that compliant parties use only cryptographic algorithms and techniques that have been certified by NIST. This document also assumes that you have selected and obtained a [certified security provider](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules). ## Setting Up a FIPS 140-2 Java Environment Mule relies on the Java runtime to provide a FIPS-compliant security module, which is why the first requirement is to have a FIPS 140-2 Java environment properly set up. If you are setting up your system for FIPS compliance for the first time and you haven’t already configured a certified security provider, you must first [select and obtain one](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules), then set up your Java environment following the instructions specific to your selected provider. Details for this process vary according to your selected security provider. Please refer to the documentation for your security provider for complete instructions. ### Example: Setup Instructions Using Bouncy Castle Security Provider The following example demonstrates how to install and configure Bouncy Castle security provider. 1. Download the provider files from [the BouncyCastle web page](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 2. Install the required JAR file into the `$JAVA_HOME/lib/ext` folder: ![FIPS-install-jars](/mulesoft/current/en-us/mule-runtime/4.4/_images/fips-install-jars.png) 3. Register the security provider in the security properties file in the `$JAVA_HOME/lib/security` folder: 1. Open the `java.security` file to add your provider’s class (for example, `org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider`) as the first item in the list of providers. 2. Modify the line with SSL provider to use the Bouncy Castle provider (`security.provider.4=com.sun.net.ssl.internal.ssl.Provider BCFIPS`): ![FIPS-register-jar](/mulesoft/current/en-us/mule-runtime/4.4/_images/fips-register-jar.png) 4. Adjust the numbering of the other security providers in the file so that they remain sequential. ![FIPS-register-jar-renumber](/mulesoft/current/en-us/mule-runtime/4.4/_images/fips-register-jar-renumber.png) 5. Save your changes. ## Running Mule in FIPS Security Mode After following the steps in [Setting Up a FIPS 140-2 Java Environment](#set_up_environment), set up your Mule instances to work in a FIPS 140-2-compliant environment by updating the configuration of the wrapper that launches the Mule app server. 1. Open your `wrapper.conf` file (located in `$MULE_HOME/conf` folder). 2. Uncomment the line that configures Mule to work in FIPS security mode (as shown). Be sure to replace the `` with the next sequential number in your `wrapper.conf` file. ![FIPS-wrapper-conf-edit](/mulesoft/current/en-us/mule-runtime/4.4/_images/fips-wrapper-conf-edit.png) 3. Save your changes. When Mule launches again, the startup readout will indicate that FIPS security mode is enabled. ![FIPS-startup](/mulesoft/current/en-us/mule-runtime/4.4/_images/fips-startup.png) With FIPS security mode enabled, Mule automatically restricts protocol negotiations to use only the subset of approved cryptographic cipher suites. Any HTTPS connectors and any other connectors that use a TLS security layer will be affected automatically by this restriction. ### Cluster Environment in FIPS mode If you are running in FIPS mode with a Mule Runtime in a clustered environment, you should define an encryption key for the cluster. See [Cluster reference](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#cluster_fips) for more insight. ## FIPS 140-2 Compliant Cipher Suites The following list contains supported FIPS 140-2 compliant cipher suites. To configure the cipher suite used by on-prem Mule installations, see [Fine-Tuning SSL Connectors](#fine-tuning-ssl-connectors). - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_DHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA ## FIPS 140-2 Compliant Keystore Formats Keystores or truststores in Mule apps are typically formatted as `PKCS12` or `JKS`. These formats aren’t FIPS compliant. For compliance, convert them to `BCFKS` format. To convert a `JKS` keystore to `BCFKS` format, make sure that you: 1. Use Java 8 or later and make sure that `JAVA_HOME` is set. 2. Download the `bc-fips.jar` file from the [Bouncy Castle website](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 3. Use this example command to convert a keystore to `BCFKS` format: BC\_FIPS\_JAR=${BC\_PATH}/bc-fips-\*.jar # Replace with a correct path OLD\_KEYSTORE="keystore.jks" # Replace with the keystore to convert OLD\_PASSWD="changeit" # Replace with the keystore password NEW\_KEYSTORE="keystore.bcfks" # Replace with the new keystore NEW\_PASSWD="changeit" # Replace with the new keystore password keytool -importkeystore \\ -providerclass org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider \\ -providerpath ${BC\_FIPS\_JAR} \\ -srckeystore ${OLD\_KEYSTORE} -srcstoretype JKS -srcstorepass ${OLD\_PASSWD} \\ -destkeystore ${NEW\_KEYSTORE} -deststoretype BCFKS -deststorepass ${NEW\_PASSWD} > [!IMPORTANT] If you’re using Java 17 or later, add the > `-J--add-exports=java.base/sun.security.provider=ALL-UNNAMED` parameter to the keytool command > before the `-importkeystore` parameter. 4. To use the new keystore or truststore, update the [TLS configuration](https://docs.mulesoft.com/mule-runtime/4.4/tls-configuration) in the Mule configuration file: > [!NOTE] If the source keystore is `PKCS12`, set the parameter `-srcstoretype` to `PKCS12` in the > `keytool` command. ## Fine-Tuning SSL Connectors The Mule conf folder includes two files that allow you to fine-tune the configuration of SSL connectors by manually setting which cipher suites Mule can use and which SSL protocols are allowed: - `tls-default.conf` (Allows fine-tuning when Mule isn’t configured to run in FIPS security mode) - `tls-fips140-2.conf` (Allows fine-tuning when Mule is running in FIPS security mode) Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and SSL protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols. ## Tips and Limitations - The Bouncy Castle security provider bundled with the Mule Runtime distribution isn’t FIPS certified. When Mule starts in FIPS security mode, the Bouncy Castle provider isn’t registered or used. - Not all encryption schemes and signatures included in [Mule Cryptography Module](https://docs.mulesoft.com/mule-runtime/4.4/securing#cryptography-module) and [Mule Secure Properties](https://docs.mulesoft.com/mule-runtime/4.4/secure-configuration-properties) configuration options are FIPS compliant. If your application is using an algorithm that isn’t approved for FIPS use, you will get an error at runtime that reads: Could not find encryption algorithm ''. You are running in FIPS mode, so please verify that the algorithm is compliant with FIPS. - Keep in mind that your different environments might have different security configurations, including different encryption schemes and algorithm selections. So you might see this error in certain environments (but not others), depending on how they are set up. - Similarly, enabling FIPS at the OS level, such as on Red Hat, isn’t supported as it causes cipher suite errors during license validation. ## See Also - [Validated FIPS-2 Cryptographic Modules](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules) - [Approved Cryptographic Algorithms](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402annexa.pdf) --- product: Mule Runtime version: 4.6 keywords: fips, certifications, security --- # FIPS 140-2 Compliance Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule 4 Runtime can be configured to run in a Federal Information Processing Standard (FIPS) 140-2 certified environment. This includes all Runtime connectors, such as HTTP connector. Note that Mule doesn’t run in FIPS security mode by default. There are two requirements: - Have a certified cryptography module installed in your Java environment - Adjust Mule Runtime settings to run in FIPS security mode > [!NOTE] By default, Government Cloud is configured for FIPS 140-2, so you don’t need to perform > the following steps if you’re using Government Cloud. > > If you’re using Runtime Fabric, see > [Enabling FIPS 140-2 Compliance Mode for Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/enable-fips-140-2-compliance) > instead of performing these steps. ## Assumptions This document assumes that you’re familiar with [FIPS 140-2](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402.pdf), the US government security standard that requires that compliant parties use only cryptographic algorithms and techniques that have been certified by NIST. This document also assumes that you have selected and obtained a [certified security provider](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules). ## Setting Up a FIPS 140-2 Java Environment Mule relies on the Java runtime to provide a FIPS-compliant security module, which is why the first requirement is to have a FIPS 140-2 Java environment properly set up. If you’re setting up your system for FIPS compliance for the first time and you haven’t already configured a certified security provider, you must first [select and obtain one](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules), then set up your Java environment following the instructions specific to your selected provider. Details for this process vary according to your selected security provider. Refer to the documentation for your security provider for complete instructions. > [!IMPORTANT] Starting with Mule 4.6.21, you configure FIPS 140-2 by installing the FIPS license > that MuleSoft provides in the license `.zip` file. To enable FIPS 140-2 compliance, you must > install the FIPS license from the `.zip` package. The non-FIPS license in the same package isn’t > valid for FIPS mode. ### Setup Instructions Using Bouncy Castle Security Provider These instructions demonstrate how to set up a FIPS 140-2 Java environment. - [Setup Instructions in Java 8](#setupjava8) - [Setup Instructions in Java 11 and Later](#setupjava11) #### Setup Instructions in Java 8 These instructions show how to install and configure Bouncy Castle security provider in Java 8. 1. Verify that you’re using Java 8 and `JAVA_HOME` is set. 2. Download the provider files from [the BouncyCastle web page](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 3. Install the required JAR file into the `$JAVA_HOME/lib/ext` folder. Provider:bc-fips-1.0.2.7 TLS: bctls-fips-1.0.24.jar PKIX: bcpkix-fips-1.0.12.jar 4. Register the security provider in the security properties file in the `$JAVA_HOME/lib/security/java.security` folder so that only the Bouncy Castle providers are set: ![A list of security providers where to modify the provider](/mulesoft/current/en-us/mule-runtime/4.6/_images/fips-register-jar.png) 5. Save your changes. #### Setup Instructions in Java 11 and Later These instructions show how to install and configure Bouncy Castle security provider in Java 11 and later. 1. Verify that you’re using Java 11 or later and `JAVA_HOME` is set. 2. Download the provider files from [the BouncyCastle web page](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). Provider:bc-fips-1.0.2.7 TLS: bctls-fips-1.0.24.jar PKIX: bcpkix-fips-1.0.12.jar 3. Register the security provider in the security properties file in the `$JAVA_HOME/conf/security/java.security` folder so that only the Bouncy Castle providers are set. 4. Copy the 3 files downloaded to `/lib/boot` (needed for Mule runtime) and `/mule-agent-plugin/lib` (needed for Mule agent) folders in Mule runtime. 5. Run `amc_setup` and register Mule runtime. For example, in **Add Server**, you find the registration token `/amc_setup -H d32c4bde-7184-444a-bd87-7a274623e14f---704247 node10 --fips`, where `d32c4bde-7184-444a-bd87-7a274623e14f---704247` is the key from Anypoint Runtime Manager. 6. To enable FIPS, update `$MULE_HOME/conf/wrapper.conf`. Add the properties `wrapper.java.additional.=-Dmule.security.model=fips140-2` and `wrapper.java.additional.=-Dmule.cluster.network.encryption.key={someKey}`, where `someKey` is the key from your cluster that needs to be defined if you are using a clustered environment. 7. Get the latest Mule runtime distribution `4.5.x`, which enables providers `BouncyCastleFipsProvider` and `BouncyCastleJsseProvider` and set the algorithms to PKIX. 8. Start Mule runtime. ## Running Mule in FIPS Security Mode After following the steps in [Setting Up a FIPS 140-2 Java Environment](#set_up_environment), set up your Mule instances to work in a FIPS 140-2-compliant environment by updating the configuration of the wrapper that launches the Mule app server. 1. Open your `wrapper.conf` file (located in `$MULE_HOME/conf` folder). 2. Uncomment the line that configures Mule to work in FIPS security mode (as shown). Be sure to replace the `` with the next sequential number in your `wrapper.conf` file. ![A file with configuration settings for enabling FIPS 140-2 mode](/mulesoft/current/en-us/mule-runtime/4.6/_images/fips-wrapper-conf-edit.png) 3. For Java 11 and later, also uncomment this line: ![A code string suggests uncommenting for fips mode](/mulesoft/current/en-us/mule-runtime/4.6/_images/fips-wrapper-conf-edit-modules.png) 4. Set the approved-only Bouncy Castle property to enforce FIPS compliance. Be sure to replace the ``. ![A string of code showing Bouncy Castle approved only as true](/mulesoft/current/en-us/mule-runtime/4.6/_images/fips-approved-only.png) 5. Save your changes. When Mule launches again, the startup readout will indicate that FIPS security mode is enabled. ![A console output showing startup logs for a Mule server with FIPS 140-2 security model enabled](/mulesoft/current/en-us/mule-runtime/4.6/_images/fips-startup.png) With FIPS security mode enabled, Mule automatically restricts protocol negotiations to use only the subset of approved cryptographic cipher suites. Any HTTPS connectors and any other connectors that use a TLS security layer will be affected automatically by this restriction. ### Cluster Environment in FIPS mode If you’re running in FIPS mode with a Mule runtime in a clustered environment, define an encryption key for the cluster. See [Cluster reference](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#cluster_fips) for more insight. ## FIPS 140-2 Compliant Cipher Suites This list contains supported FIPS 140-2 compliant cipher suites. To configure the cipher suite used by on-prem Mule installations, see [Fine-Tuning SSL Connectors](#fine-tuning-ssl-connectors). - TLS\_DHE\_DSS\_WITH\_AES\_128\_CBC\_SHA - TLS\_DHE\_DSS\_WITH\_AES\_256\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDH\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDH\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDH\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDH\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_AES\_128\_GCM\_SHA256 - TLS\_AES\_256\_GCM\_SHA384 - TLS\_AES\_128\_CCM\_SHA256 - TLS\_AES\_128\_CCM\_8\_SHA256 ## FIPS 140-2 Compliant Keystore Formats Keystores or truststores in Mule apps are typically formatted as `PKCS12` or `JKS`. These formats aren’t FIPS compliant. For compliance, convert them to `BCFKS` format. To convert a `JKS` keystore to `BCFKS` format, make sure that you: 1. Use Java 8 or later and make sure that `JAVA_HOME` is set. 2. Download the `bc-fips.jar` file from the [Bouncy Castle website](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 3. Use this example command to convert a keystore to `BCFKS` format: BC\_FIPS\_JAR=${BC\_PATH}/bc-fips-\*.jar # Replace with a correct path OLD\_KEYSTORE="keystore.jks" # Replace with the keystore to convert OLD\_PASSWD="changeit" # Replace with the keystore password NEW\_KEYSTORE="keystore.bcfks" # Replace with the new keystore NEW\_PASSWD="changeit" # Replace with the new keystore password keytool -importkeystore \\ -providerclass org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider \\ -providerpath ${BC\_FIPS\_JAR} \\ -srckeystore ${OLD\_KEYSTORE} -srcstoretype JKS -srcstorepass ${OLD\_PASSWD} \\ -destkeystore ${NEW\_KEYSTORE} -deststoretype BCFKS -deststorepass ${NEW\_PASSWD} > [!IMPORTANT] If you’re using Java 17 or later, add the > `-J--add-exports=java.base/sun.security.provider=ALL-UNNAMED` parameter to the keytool command > before the `-importkeystore` parameter. 4. To use the new keystore or truststore, update the [TLS configuration](https://docs.mulesoft.com/mule-runtime/4.6/tls-configuration) in the Mule configuration file: > [!NOTE] If the source keystore is `PKCS12`, set the parameter `-srcstoretype` to `PKCS12` in the > `keytool` command. ## Fine-Tuning SSL Connectors The Mule conf folder includes two files that allow you to fine-tune the configuration of SSL connectors by manually setting which cipher suites Mule can use and which SSL protocols are allowed: - `tls-default.conf` (Allows fine-tuning when Mule isn’t configured to run in FIPS security mode) - `tls-fips140-2.conf` (Allows fine-tuning when Mule is running in FIPS security mode) Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and SSL protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols. ## Tips and Limitations - The Bouncy Castle security provider bundled with the Mule runtime distribution isn’t FIPS certified. When Mule starts in FIPS security mode, the Bouncy Castle provider isn’t registered or used. - Not all encryption schemes and signatures included in [Mule Cryptography Module](https://docs.mulesoft.com/mule-runtime/4.6/securing#cryptography-module) and [Mule Secure Properties](https://docs.mulesoft.com/mule-runtime/4.6/secure-configuration-properties) configuration options are FIPS compliant. If your application is using an algorithm that isn’t approved for FIPS use, you will get an error at runtime that reads: Could not find encryption algorithm ''. You are running in FIPS mode, so please verify that the algorithm is compliant with FIPS. - Keep in mind that your different environments might have different security configurations, including different encryption schemes and algorithm selections. So you might see this error in certain environments (but not others), depending on how they are set up. - Similarly, enabling FIPS at the OS level, such as on Red Hat, isn’t supported as it causes cipher suite errors during license validation. ## See Also - [Validated FIPS-2 Cryptographic Modules](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules) - [Approved Cryptographic Algorithms](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402annexa.pdf) --- product: Mule Runtime version: 4.9 keywords: fips, certifications, security --- # FIPS 140-2 Compliance Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule 4 Runtime can be configured to run in a Federal Information Processing Standard (FIPS) 140-2 certified environment. This includes all Runtime connectors, such as HTTP connector. Note that Mule doesn’t run in FIPS security mode by default. There are two requirements: - Have a certified cryptography module installed in your Java environment - Adjust Mule Runtime settings to run in FIPS security mode > [!NOTE] By default, Government Cloud is configured for FIPS 140-2, so you don’t need to perform > the following steps if you’re using Government Cloud. > > If you’re using Runtime Fabric, see > [Enabling FIPS 140-2 Compliance Mode for Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/enable-fips-140-2-compliance) > instead of performing these steps. ## Assumptions This document assumes that you’re familiar with [FIPS 140-2](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402.pdf), the US government security standard that requires that compliant parties use only cryptographic algorithms and techniques that have been certified by NIST. This document also assumes that you have selected and obtained a [certified security provider](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules). ## Setting Up a FIPS 140-2 Java Environment Mule relies on the Java runtime to provide a FIPS-compliant security module, which is why the first requirement is to have a FIPS 140-2 Java environment properly set up. If you’re setting up your system for FIPS compliance for the first time and you haven’t already configured a certified security provider, you must first [select and obtain one](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules), then set up your Java environment following the instructions specific to your selected provider. Details for this process vary according to your selected security provider. Refer to the documentation for your security provider for complete instructions. > [!IMPORTANT] Starting with Mule 4.9.8, you configure FIPS 140-2 by installing the FIPS license > that MuleSoft provides in the license `.zip` file. To enable FIPS 140-2 compliance, you must > install the FIPS license from the `.zip` package. The non-FIPS license in the same package isn’t > valid for FIPS mode. ### Setup Instructions Using Bouncy Castle Security Provider These instructions demonstrate how to set up a FIPS 140-2 Java environment. - [Setup Instructions in Java 8](#setupjava8) - [Setup Instructions in Java 11 and Later](#setupjava11) #### Setup Instructions in Java 8 These instructions show how to install and configure Bouncy Castle security provider in Java 8. 1. Verify that you’re using Java 8 and `JAVA_HOME` is set. 2. Download the provider files from [the BouncyCastle web page](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 3. Install the required JAR file into the `$JAVA_HOME/lib/ext` folder. Provider:bc-fips-1.0.2.7 TLS: bctls-fips-1.0.24.jar PKIX: bcpkix-fips-1.0.12.jar 4. Register the security provider in the security properties file in the `$JAVA_HOME/lib/security/java.security` folder so that only the Bouncy Castle providers are set: ![A list of security providers where to modify the provider](/mulesoft/current/en-us/mule-runtime/4.9/_images/fips-register-jar.png) 5. Save your changes. #### Setup Instructions in Java 11 and Later These instructions show how to install and configure Bouncy Castle security provider in Java 11 and later. 1. Verify that you’re using Java 11 or later and `JAVA_HOME` is set. 2. Download the provider files from [the BouncyCastle web page](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). Provider:bc-fips-1.0.2.7 TLS: bctls-fips-1.0.24.jar PKIX: bcpkix-fips-1.0.12.jar 3. Register the security provider in the security properties file in the `$JAVA_HOME/conf/security/java.security` folder so that only the Bouncy Castle providers are set. 4. Copy the 3 files downloaded to `/lib/boot` (needed for Mule runtime) and `/mule-agent-plugin/lib` (needed for Mule agent) folders in Mule runtime. 5. Run `amc_setup` and register Mule runtime. For example, in **Add Server**, you find the registration token `/amc_setup -H d32c4bde-7184-444a-bd87-7a274623e14f---704247 node10 --fips`, where `d32c4bde-7184-444a-bd87-7a274623e14f---704247` is the key from Anypoint Runtime Manager. 6. To enable FIPS, update `$MULE_HOME/conf/wrapper.conf`. Add the properties `wrapper.java.additional.=-Dmule.security.model=fips140-2` and `wrapper.java.additional.=-Dmule.cluster.network.encryption.key={someKey}`, where `someKey` is the key from your cluster that needs to be defined if you are using a clustered environment. 7. Get the latest Mule runtime distribution `4.5.x`, which enables providers `BouncyCastleFipsProvider` and `BouncyCastleJsseProvider` and set the algorithms to PKIX. 8. Start Mule runtime. ## Running Mule in FIPS Security Mode After following the steps in [Setting Up a FIPS 140-2 Java Environment](#set_up_environment), set up your Mule instances to work in a FIPS 140-2-compliant environment by updating the configuration of the wrapper that launches the Mule app server. 1. Open your `wrapper.conf` file (located in `$MULE_HOME/conf` folder). 2. Uncomment the line that configures Mule to work in FIPS security mode (as shown). Be sure to replace the `` with the next sequential number in your `wrapper.conf` file. ![A file with configuration settings for enabling FIPS 140-2 mode](/mulesoft/current/en-us/mule-runtime/4.9/_images/fips-wrapper-conf-edit.png) 3. For Java 11 and later, also uncomment this line: ![A code string suggests uncommenting for fips mode](/mulesoft/current/en-us/mule-runtime/4.9/_images/fips-wrapper-conf-edit-modules.png) 4. Set the approved-only Bouncy Castle property to enforce FIPS compliance. Be sure to replace the ``. ![A string of code showing Bouncy Castle approved only as true](/mulesoft/current/en-us/mule-runtime/4.9/_images/fips-approved-only.png) 5. Save your changes. When Mule launches again, the startup readout will indicate that FIPS security mode is enabled. ![A console output showing startup logs for a Mule server with FIPS 140-2 security model enabled](/mulesoft/current/en-us/mule-runtime/4.9/_images/fips-startup.png) With FIPS security mode enabled, Mule automatically restricts protocol negotiations to use only the subset of approved cryptographic cipher suites. Any HTTPS connectors and any other connectors that use a TLS security layer will be affected automatically by this restriction. ### Cluster Environment in FIPS mode If you’re running in FIPS mode with a Mule runtime in a clustered environment, define an encryption key for the cluster. See [Cluster reference](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#cluster_fips) for more insight. ## FIPS 140-2 Compliant Cipher Suites This list contains supported FIPS 140-2 compliant cipher suites. To configure the cipher suite used by on-prem Mule installations, see [Fine-Tuning SSL Connectors](#fine-tuning-ssl-connectors). - TLS\_DHE\_DSS\_WITH\_AES\_128\_CBC\_SHA - TLS\_DHE\_DSS\_WITH\_AES\_256\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDH\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDH\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDH\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDH\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_AES\_128\_GCM\_SHA256 - TLS\_AES\_256\_GCM\_SHA384 - TLS\_AES\_128\_CCM\_SHA256 - TLS\_AES\_128\_CCM\_8\_SHA256 ## FIPS 140-2 Compliant Keystore Formats Keystores or truststores in Mule apps are typically formatted as `PKCS12` or `JKS`. These formats aren’t FIPS compliant. For compliance, convert them to `BCFKS` format. To convert a `JKS` keystore to `BCFKS` format, make sure that you: 1. Use Java 8 or later and make sure that `JAVA_HOME` is set. 2. Download the `bc-fips.jar` file from the [Bouncy Castle website](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 3. Use this example command to convert a keystore to `BCFKS` format: BC\_FIPS\_JAR=${BC\_PATH}/bc-fips-\*.jar # Replace with a correct path OLD\_KEYSTORE="keystore.jks" # Replace with the keystore to convert OLD\_PASSWD="changeit" # Replace with the keystore password NEW\_KEYSTORE="keystore.bcfks" # Replace with the new keystore NEW\_PASSWD="changeit" # Replace with the new keystore password keytool -importkeystore \\ -providerclass org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider \\ -providerpath ${BC\_FIPS\_JAR} \\ -srckeystore ${OLD\_KEYSTORE} -srcstoretype JKS -srcstorepass ${OLD\_PASSWD} \\ -destkeystore ${NEW\_KEYSTORE} -deststoretype BCFKS -deststorepass ${NEW\_PASSWD} > [!IMPORTANT] If you’re using Java 17 or later, add the > `-J--add-exports=java.base/sun.security.provider=ALL-UNNAMED` parameter to the keytool command > before the `-importkeystore` parameter. 4. To use the new keystore or truststore, update the [TLS configuration](https://docs.mulesoft.com/mule-runtime/4.9/tls-configuration) in the Mule configuration file: > [!NOTE] If the source keystore is `PKCS12`, set the parameter `-srcstoretype` to `PKCS12` in the > `keytool` command. ## Fine-Tuning SSL Connectors The Mule conf folder includes two files that allow you to fine-tune the configuration of SSL connectors by manually setting which cipher suites Mule can use and which SSL protocols are allowed: - `tls-default.conf` (Allows fine-tuning when Mule isn’t configured to run in FIPS security mode) - `tls-fips140-2.conf` (Allows fine-tuning when Mule is running in FIPS security mode) Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and SSL protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols. ## Tips and Limitations - The Bouncy Castle security provider bundled with the Mule runtime distribution isn’t FIPS certified. When Mule starts in FIPS security mode, the Bouncy Castle provider isn’t registered or used. - Not all encryption schemes and signatures included in [Mule Cryptography Module](https://docs.mulesoft.com/mule-runtime/4.9/securing#cryptography-module) and [Mule Secure Properties](https://docs.mulesoft.com/mule-runtime/4.9/secure-configuration-properties) configuration options are FIPS compliant. If your application is using an algorithm that isn’t approved for FIPS use, you will get an error at runtime that reads: Could not find encryption algorithm ''. You are running in FIPS mode, so please verify that the algorithm is compliant with FIPS. - Keep in mind that your different environments might have different security configurations, including different encryption schemes and algorithm selections. So you might see this error in certain environments (but not others), depending on how they are set up. - Similarly, enabling FIPS at the OS level, such as on Red Hat, isn’t supported as it causes cipher suite errors during license validation. ## See Also - [Validated FIPS-2 Cryptographic Modules](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules) - [Approved Cryptographic Algorithms](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402annexa.pdf) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: fips, certifications, security --- # FIPS 140-2 Compliance Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule 4 Runtime can be configured to run in a Federal Information Processing Standard (FIPS) 140-2 certified environment. This includes all Runtime connectors, such as HTTP connector. Note that Mule doesn’t run in FIPS security mode by default. There are two requirements: - Have a certified cryptography module installed in your Java environment - Adjust Mule Runtime settings to run in FIPS security mode > [!NOTE] By default, Government Cloud is configured for FIPS 140-2, so you don’t need to perform > the following steps if you’re using Government Cloud. > > If you’re using Runtime Fabric, see > [Enabling FIPS 140-2 Compliance Mode for Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/enable-fips-140-2-compliance) > instead of performing these steps. ## Assumptions This document assumes that you’re familiar with [FIPS 140-2](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402.pdf), the US government security standard that requires that compliant parties use only cryptographic algorithms and techniques that have been certified by NIST. This document also assumes that you have selected and obtained a [certified security provider](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules). ## Setting Up a FIPS 140-2 Java Environment Mule relies on the Java runtime to provide a FIPS-compliant security module, which is why the first requirement is to have a FIPS 140-2 Java environment properly set up. If you’re setting up your system for FIPS compliance for the first time and you haven’t already configured a certified security provider, you must first [select and obtain one](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules), then set up your Java environment following the instructions specific to your selected provider. Details for this process vary according to your selected security provider. Refer to the documentation for your security provider for complete instructions. > [!IMPORTANT] Starting with Mule 4.9.8, you configure FIPS 140-2 by installing the FIPS license > that MuleSoft provides in the license `.zip` file. To enable FIPS 140-2 compliance, you must > install the FIPS license from the `.zip` package. The non-FIPS license in the same package isn’t > valid for FIPS mode. ### Setup Instructions Using Bouncy Castle Security Provider These instructions demonstrate how to set up a FIPS 140-2 Java environment. - [Setup Instructions in Java 8](#setupjava8) - [Setup Instructions in Java 11 and Later](#setupjava11) #### Setup Instructions in Java 8 These instructions show how to install and configure Bouncy Castle security provider in Java 8. 1. Verify that you’re using Java 8 and `JAVA_HOME` is set. 2. Download the provider files from [the BouncyCastle web page](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 3. Install the required JAR file into the `$JAVA_HOME/lib/ext` folder. Provider:bc-fips-1.0.2.7 TLS: bctls-fips-1.0.24.jar PKIX: bcpkix-fips-1.0.12.jar 4. Register the security provider in the security properties file in the `$JAVA_HOME/lib/security/java.security` folder so that only the Bouncy Castle providers are set: ![A list of security providers where to modify the provider](/mulesoft/current/en-us/mule-runtime/latest/_images/fips-register-jar.png) 5. Save your changes. #### Setup Instructions in Java 11 and Later These instructions show how to install and configure Bouncy Castle security provider in Java 11 and later. 1. Verify that you’re using Java 11 or later and `JAVA_HOME` is set. 2. Download the provider files from [the BouncyCastle web page](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). Provider:bc-fips-1.0.2.7 TLS: bctls-fips-1.0.24.jar PKIX: bcpkix-fips-1.0.12.jar 3. Register the security provider in the security properties file in the `$JAVA_HOME/conf/security/java.security` folder so that only the Bouncy Castle providers are set. 4. Copy the 3 files downloaded to `/lib/boot` (needed for Mule runtime) and `/mule-agent-plugin/lib` (needed for Runtime Manager agent) folders in Mule runtime. 5. Run `amc_setup` and register Mule runtime. For example, in **Add Server**, you find the registration token `/amc_setup -H d32c4bde-7184-444a-bd87-7a274623e14f---704247 node10 --fips`, where `d32c4bde-7184-444a-bd87-7a274623e14f---704247` is the key from Anypoint Runtime Manager. When configuring Runtime Manager agent, include the `--fips` flag to enable FIPS compliance. If you’re using Government Cloud, also include the `--region us_gov` flag: ./amc\_setup -H --fips --region us\_gov You must pass the `--fips` argument each time you register a Mule runtime in a FIPS-compliant environment. 6. To enable FIPS, update `$MULE_HOME/conf/wrapper.conf`. Add the properties `wrapper.java.additional.=-Dmule.security.model=fips140-2` and `wrapper.java.additional.=-Dmule.cluster.network.encryption.key={someKey}`, where `someKey` is the key from your cluster that needs to be defined if you are using a clustered environment. 7. Get the latest Mule runtime distribution `4.5.x`, which enables providers `BouncyCastleFipsProvider` and `BouncyCastleJsseProvider` and set the algorithms to PKIX. 8. Start Mule runtime. ## Running Mule in FIPS Security Mode After following the steps in [Setting Up a FIPS 140-2 Java Environment](#set_up_environment), set up your Mule instances to work in a FIPS 140-2-compliant environment by updating the configuration of the wrapper that launches the Mule app server. 1. Open your `wrapper.conf` file (located in `$MULE_HOME/conf` folder). 2. Uncomment the line that configures Mule to work in FIPS security mode (as shown). Be sure to replace the `` with the next sequential number in your `wrapper.conf` file. ![A file with configuration settings for enabling FIPS 140-2 mode](/mulesoft/current/en-us/mule-runtime/latest/_images/fips-wrapper-conf-edit.png) 3. For Java 11 and later, also uncomment this line: ![A code string suggests uncommenting for fips mode](/mulesoft/current/en-us/mule-runtime/latest/_images/fips-wrapper-conf-edit-modules.png) 4. Set the approved-only Bouncy Castle property to enforce FIPS compliance. Be sure to replace the ``. ![A string of code showing Bouncy Castle approved only as true](/mulesoft/current/en-us/mule-runtime/latest/_images/fips-approved-only.png) 5. Save your changes. When Mule launches again, the startup readout will indicate that FIPS security mode is enabled. ![A console output showing startup logs for a Mule server with FIPS 140-2 security model enabled](/mulesoft/current/en-us/mule-runtime/latest/_images/fips-startup.png) With FIPS security mode enabled, Mule automatically restricts protocol negotiations to use only the subset of approved cryptographic cipher suites. Any HTTPS connectors and any other connectors that use a TLS security layer will be affected automatically by this restriction. ### Cluster Environment in FIPS mode If you’re running in FIPS mode with a Mule runtime in a clustered environment, define an encryption key for the cluster. See [Cluster reference](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#cluster_fips) for more insight. ## FIPS 140-2 Compliant Cipher Suites This list contains supported FIPS 140-2 compliant cipher suites. To configure the cipher suite used by on-prem Mule installations, see [Fine-Tuning SSL Connectors](#fine-tuning-ssl-connectors). - TLS\_DHE\_DSS\_WITH\_AES\_128\_CBC\_SHA - TLS\_DHE\_DSS\_WITH\_AES\_256\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_DHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDH\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDH\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDH\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDH\_RSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_AES\_128\_GCM\_SHA256 - TLS\_AES\_256\_GCM\_SHA384 - TLS\_AES\_128\_CCM\_SHA256 - TLS\_AES\_128\_CCM\_8\_SHA256 ## FIPS 140-2 Compliant Keystore Formats Keystores or truststores in Mule apps are typically formatted as `PKCS12` or `JKS`. These formats aren’t FIPS compliant. For compliance, convert them to `BCFKS` format. To convert a `JKS` keystore to `BCFKS` format, make sure that you: 1. Use Java 8 or later and make sure that `JAVA_HOME` is set. 2. Download the `bc-fips.jar` file from the [Bouncy Castle website](https://www.bouncycastle.org/download/bouncy-castle-java-fips/). 3. Use this example command to convert a keystore to `BCFKS` format: BC\_FIPS\_JAR=${BC\_PATH}/bc-fips-\*.jar # Replace with a correct path OLD\_KEYSTORE="keystore.jks" # Replace with the keystore to convert OLD\_PASSWD="changeit" # Replace with the keystore password NEW\_KEYSTORE="keystore.bcfks" # Replace with the new keystore NEW\_PASSWD="changeit" # Replace with the new keystore password keytool -importkeystore \\ -providerclass org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider \\ -providerpath ${BC\_FIPS\_JAR} \\ -srckeystore ${OLD\_KEYSTORE} -srcstoretype JKS -srcstorepass ${OLD\_PASSWD} \\ -destkeystore ${NEW\_KEYSTORE} -deststoretype BCFKS -deststorepass ${NEW\_PASSWD} > [!IMPORTANT] If you’re using Java 17 or later, add the > `-J--add-exports=java.base/sun.security.provider=ALL-UNNAMED` parameter to the keytool command > before the `-importkeystore` parameter. 4. To use the new keystore or truststore, update the [TLS configuration](https://docs.mulesoft.com/mule-runtime/latest/tls-configuration) in the Mule configuration file: > [!NOTE] If the source keystore is `PKCS12`, set the parameter `-srcstoretype` to `PKCS12` in the > `keytool` command. ## Fine-Tuning SSL Connectors The Mule conf folder includes two files that allow you to fine-tune the configuration of SSL connectors by manually setting which cipher suites Mule can use and which SSL protocols are allowed: - `tls-default.conf` (Allows fine-tuning when Mule isn’t configured to run in FIPS security mode) - `tls-fips140-2.conf` (Allows fine-tuning when Mule is running in FIPS security mode) Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and SSL protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols. ## Tips and Limitations - The Bouncy Castle security provider bundled with the Mule runtime distribution isn’t FIPS certified. When Mule starts in FIPS security mode, the Bouncy Castle provider isn’t registered or used. - Not all encryption schemes and signatures included in [Mule Cryptography Module](https://docs.mulesoft.com/mule-runtime/latest/securing#cryptography-module) and [Mule Secure Properties](https://docs.mulesoft.com/mule-runtime/latest/secure-configuration-properties) configuration options are FIPS compliant. If your application is using an algorithm that isn’t approved for FIPS use, you will get an error at runtime that reads: Could not find encryption algorithm ''. You are running in FIPS mode, so please verify that the algorithm is compliant with FIPS. - Keep in mind that your different environments might have different security configurations, including different encryption schemes and algorithm selections. So you might see this error in certain environments (but not others), depending on how they are set up. - Similarly, enabling FIPS at the OS level, such as on Red Hat, isn’t supported as it causes cipher suite errors during license validation. ## See Also - [Validated FIPS-2 Cryptographic Modules](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules) - [Approved Cryptographic Algorithms](https://csrc.nist.gov/files/pubs/fips/140-2/upd2/final/docs/fips1402annexa.pdf) --- product: Mule Runtime version: 4.11 keywords: fips, certifications, security, fips-140-3 --- # FIPS 140-3 Compliance Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Run Mule 4 in a Federal Information Processing Standard (FIPS) 140-3 certified environment by enabling approved cryptography providers and runtime settings. Use this guide to install BC-FJA, enable FIPS mode, and configure TLS and keystore formats for compliant deployments. These steps help you meet federal cryptography requirements while keeping runtime behavior predictable across environments. Mule doesn’t run in FIPS security mode by default. To use FIPS security mode: - Install a certified cryptography module in your Java environment. - Adjust Mule runtime settings to run in FIPS security mode. ## Compatibility FIPS 140-3 support requires: - Mule 4.11.4 or later (for earlier versions of Mule runtime, use [FIPS 140-2 Compliance Support](https://docs.mulesoft.com/mule-runtime/4.11/fips-140-2-compliance-support)) - Java 17 or later - FIPS license from the license `.zip` file provided by MuleSoft (the non-FIPS license isn’t valid for FIPS mode) ## Assumptions This document assumes you’re familiar with [FIPS 140-3](https://csrc.nist.gov/publications/detail/fips/140/3/final), the US government security standard that requires that compliant parties use only cryptographic algorithms and techniques that have been certified by NIST. These instructions use BC-FJA, the recommended FIPS 140-3 certified security provider for Mule runtime ([Certificate #4943](https://csrc.nist.gov/projects/cryptographic-module-validation-program/certificate/4943)). If you use a different [certified security provider](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules), refer to that provider’s documentation for configuration instructions. ## Installing BC-FJA Security Provider Mule runtime uses BC-FJA 2.1.2 as its FIPS 140-3 certified cryptography provider. ### Installation Steps These instructions show how to install and configure BC-FJA security provider in Java 17 or later. 1. Verify that you’re using Java 17 or later and `JAVA_HOME` is set. 2. Download the BC-FJA 2.1.2 provider files from [the BouncyCastle website](https://www.bouncycastle.org/fips-java/). 3. Copy the required JAR files to the `${MULE_HOME}/lib/boot` folder: bc-fips-2.1.2.jar bcutil-fips-2.1.5.jar bctls-fips-2.1.22.jar bcpkix-fips-2.1.10.jar 4. Configure the security properties in `java.security`. - Security providers: security.provider.1=org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider fips:BCFIPS > [!NOTE] On ARM64 (AArch64) architectures, register the `SUN` provider. BC-FJA 2.1.2 doesn’t > include a `SecureRandom` implementation for AArch64 (its native cryptographic library > targets x86\_64 only). The JVM’s `securerandom.strongAlgorithms` property defaults to > `NativePRNGBlocking:SUN` and `DRBG:SUN`. Without a provider that supplies these algorithms, > the JVM fails during early bootstrap, before Mule logs initialize. > > Add `SUN` as security provider 3: > > security.provider.1=org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider > security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider fips:BCFIPS > security.provider.3=SUN 5. Set the key manager and trust manager algorithms: ssl.KeyManagerFactory.algorithm=PKIX ssl.TrustManagerFactory.algorithm=PKIX 6. Set the keystore type: keystore.type=FIPS ## Running Mule in FIPS Security Mode After installing the BC-FJA provider, configure Mule to run in FIPS 140-3 mode: 1. Open your `wrapper.conf` file (located in `${MULE_HOME}/conf`). 2. Add these properties. Replace `` with the next sequential number in your file: \# Enable FIPS 140-3 security mode wrapper.java.additional.=-Dmule.security.model=fips140-3 # Enable Bouncy Castle approved-only mode wrapper.java.additional.=-Dorg.bouncycastle.fips.approved\_only=true # Required for Java 17+ module access wrapper.java.additional.=--add-opens=java.base/sun.security.provider=org.bouncycastle.fips.core # Set keystore type to BCFKS wrapper.java.additional.=-Dmule.keystore.type=BCFKS 3. If you’re using a clustered environment, also add the cluster encryption key: wrapper.java.additional.=-Dmule.cluster.network.encryption.key={your-encryption-key} For more information about clustering in FIPS mode, see [Cluster reference](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#cluster_fips). 4. Save your changes and start Mule runtime. > [!IMPORTANT] In FIPS-compliant environments, all keystores and truststores typically require BCFKS > format. To support legacy JKS stores, such as the default Java truststore at > `${JAVA_HOME}/lib/security/cacerts`, see > [FIPS 140-3 Compliant Keystore Formats](#fips-140-3-compliant-keystore-formats) for configuration > options. When Mule launches, the startup logs show that FIPS 140-3 security mode is enabled. Mule automatically restricts protocol negotiations to use only approved cryptographic cipher suites. > [!IMPORTANT] Not all connectors are FIPS 140-3 compliant. Only connectors tagged as > `fips-140-3-verified` in Anypoint Exchange are certified to use in FIPS 140-3 environments. Always > verify compliance in Exchange before deploying. ## FIPS 140-3 Compliant Cipher Suites These cipher suites are enabled by default when running Mule in FIPS 140-3 mode. ### TLS 1.3 Cipher Suites - TLS\_AES\_128\_GCM\_SHA256 - TLS\_AES\_256\_GCM\_SHA384 - TLS\_AES\_128\_CCM\_SHA256 - TLS\_AES\_128\_CCM\_8\_SHA256 ### TLS 1.2 Cipher Suites - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_DHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA > [!NOTE] These cipher suites are configured in the `${MULE_HOME}/conf/tls-fips140-3.conf` file. > FIPS 140-3 requires support for TLS 1.3 and TLS 1.2. Earlier TLS versions aren’t supported. ## FIPS 140-3 Compliant Keystore Formats Keystores or truststores in non-FIPS environments are typically formatted as `PKCS12` or `JKS`. These formats aren’t FIPS-compliant. Convert them to `BCFKS` format. 1. Use this example command to convert a `JKS` keystore to `BCFKS` format. If the source keystore is `PKCS12`, set `-srcstoretype` to `PKCS12` in the `keytool` command: BC\_FIPS\_JAR=${MULE\_HOME}/lib/boot/bc-fips-2.1.2.jar # Replace with a correct path OLD\_KEYSTORE="keystore.jks" # Replace with the keystore to convert OLD\_PASSWD="changeit" # Replace with the keystore password NEW\_KEYSTORE="keystore.bcfks" # Replace with the new keystore NEW\_PASSWD="changeit" # Replace with the new keystore password keytool -importkeystore \\ -providerclass sun.security.provider.Sun \\ -providerclass org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider \\ -providerpath ${BC\_FIPS\_JAR} \\ -srckeystore ${OLD\_KEYSTORE} -srcstoretype JKS -srcstorepass ${OLD\_PASSWD} \\ -destkeystore ${NEW\_KEYSTORE} -deststoretype BCFKS -deststorepass ${NEW\_PASSWD} 2. Update the [TLS configuration](https://docs.mulesoft.com/mule-runtime/4.11/tls-configuration) in your Mule application to use the new keystore or truststore: 3. By default, the JVM truststore at `${JAVA_HOME}/lib/security/cacerts` is a `JKS`. There are two approaches to handle this special case: - Convert to BCFKS - Convert the `JKS` store to `BCFKS` using the `keytool` command as described in [FIPS 140-3 Compliant Keystore Formats](#fips-140-3-compliant-keystore-formats), pointing OLD\_KEYSTORE to `${JAVA_HOME}/lib/security/cacerts` and NEW\_KEYSTORE to `${JAVA_HOME}/lib/security/cacerts.bcfks` - Add these properties to your `wrapper.conf` file: wrapper.java.additional.=-Djavax.net.ssl.trustStore=${JAVA\_HOME}/lib/security/cacerts.bcfks wrapper.java.additional.=-Djavax.net.ssl.trustStorePassword=changeit wrapper.java.additional.=-Djavax.net.ssl.trustStoreType=bcfks - Allow legacy `JKS` store - Add this property to your `wrapper.conf` file: wrapper.java.additional.=-Dorg.bouncycastle.jca.enable\_jks=true ## Connectors Compatibility Only connectors tagged as `fips-140-3-verified` in Anypoint Exchange are certified for use in FIPS 140-3 environments. To check compliance in Exchange before deploying: 1. Open Anypoint Exchange. 2. Search for the connector. 3. Check for the `fips-140-3-verified` tag. ## Tips and Limitations - Not all encryption schemes and signatures are FIPS 140-3 compliant. If your application uses a non-approved algorithm, you get this runtime error: Could not find encryption algorithm ''. You are running in FIPS mode, so please verify that the algorithm is compliant with FIPS. - Different environments can have different security configurations. Test before deploying to production. ## See Also - [Validated FIPS 140-3 Cryptographic Modules](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules) - [FIPS 140-3 Standard](https://csrc.nist.gov/publications/detail/fips/140/3/final) - [FIPS 140-2 Compliance Support](https://docs.mulesoft.com/mule-runtime/4.11/fips-140-2-compliance-support) --- product: Mule Runtime version: 4.12 keywords: fips, certifications, security, fips-140-3 --- # FIPS 140-3 Compliance Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Run Mule 4 in a Federal Information Processing Standard (FIPS) 140-3 certified environment by enabling approved cryptography providers and runtime settings. Use this guide to install BC-FJA, enable FIPS mode, and configure TLS and keystore formats for compliant deployments. These steps help you meet federal cryptography requirements while keeping runtime behavior predictable across environments. Mule doesn’t run in FIPS security mode by default. To use FIPS security mode: - Install a certified cryptography module in your Java environment. - Adjust Mule runtime settings to run in FIPS security mode. ## Compatibility FIPS 140-3 support requires: - Mule 4.11.4 or later (for earlier versions of Mule runtime, use [FIPS 140-2 Compliance Support](https://docs.mulesoft.com/mule-runtime/4.12/fips-140-2-compliance-support)) - Java 17 or later - FIPS license from the license `.zip` file provided by MuleSoft (the non-FIPS license isn’t valid for FIPS mode) ## Assumptions This document assumes you’re familiar with [FIPS 140-3](https://csrc.nist.gov/publications/detail/fips/140/3/final), the US government security standard that requires that compliant parties use only cryptographic algorithms and techniques that have been certified by NIST. These instructions use BC-FJA, the recommended FIPS 140-3 certified security provider for Mule runtime ([Certificate #4943](https://csrc.nist.gov/projects/cryptographic-module-validation-program/certificate/4943)). If you use a different [certified security provider](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules), refer to that provider’s documentation for configuration instructions. ## Installing BC-FJA Security Provider Mule runtime uses BC-FJA 2.1.2 as its FIPS 140-3 certified cryptography provider. ### Installation Steps These instructions show how to install and configure BC-FJA security provider in Java 17 or later. 1. Verify that you’re using Java 17 or later and `JAVA_HOME` is set. 2. Download the BC-FJA 2.1.2 provider files from [the BouncyCastle website](https://www.bouncycastle.org/fips-java/). 3. Copy the required JAR files to the `${MULE_HOME}/lib/boot` folder: bc-fips-2.1.2.jar bcutil-fips-2.1.5.jar bctls-fips-2.1.22.jar bcpkix-fips-2.1.10.jar 4. Configure the security properties in `java.security`. - Security providers: security.provider.1=org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider fips:BCFIPS > [!NOTE] On ARM64 (AArch64) architectures, register the `SUN` provider. BC-FJA 2.1.2 doesn’t > include a `SecureRandom` implementation for AArch64 (its native cryptographic library > targets x86\_64 only). The JVM’s `securerandom.strongAlgorithms` property defaults to > `NativePRNGBlocking:SUN` and `DRBG:SUN`. Without a provider that supplies these algorithms, > the JVM fails during early bootstrap, before Mule logs initialize. > > Add `SUN` as security provider 3: > > security.provider.1=org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider > security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider fips:BCFIPS > security.provider.3=SUN 5. Set the key manager and trust manager algorithms: ssl.KeyManagerFactory.algorithm=PKIX ssl.TrustManagerFactory.algorithm=PKIX 6. Set the keystore type: keystore.type=FIPS ## Running Mule in FIPS Security Mode After installing the BC-FJA provider, configure Mule to run in FIPS 140-3 mode: 1. Open your `wrapper.conf` file (located in `${MULE_HOME}/conf`). 2. Add these properties. Replace `` with the next sequential number in your file: \# Enable FIPS 140-3 security mode wrapper.java.additional.=-Dmule.security.model=fips140-3 # Enable Bouncy Castle approved-only mode wrapper.java.additional.=-Dorg.bouncycastle.fips.approved\_only=true # Required for Java 17+ module access wrapper.java.additional.=--add-opens=java.base/sun.security.provider=org.bouncycastle.fips.core # Set keystore type to BCFKS wrapper.java.additional.=-Dmule.keystore.type=BCFKS 3. If you’re using a clustered environment, also add the cluster encryption key: wrapper.java.additional.=-Dmule.cluster.network.encryption.key={your-encryption-key} For more information about clustering in FIPS mode, see [Cluster reference](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#cluster_fips). 4. Save your changes and start Mule runtime. > [!IMPORTANT] In FIPS-compliant environments, all keystores and truststores typically require BCFKS > format. To support legacy JKS stores, such as the default Java truststore at > `${JAVA_HOME}/lib/security/cacerts`, see > [FIPS 140-3 Compliant Keystore Formats](#fips-140-3-compliant-keystore-formats) for configuration > options. When Mule launches, the startup logs show that FIPS 140-3 security mode is enabled. Mule automatically restricts protocol negotiations to use only approved cryptographic cipher suites. > [!IMPORTANT] Not all connectors are FIPS 140-3 compliant. Only connectors tagged as > `fips-140-3-verified` in Anypoint Exchange are certified to use in FIPS 140-3 environments. Always > verify compliance in Exchange before deploying. ## FIPS 140-3 Compliant Cipher Suites These cipher suites are enabled by default when running Mule in FIPS 140-3 mode. ### TLS 1.3 Cipher Suites - TLS\_AES\_128\_GCM\_SHA256 - TLS\_AES\_256\_GCM\_SHA384 - TLS\_AES\_128\_CCM\_SHA256 - TLS\_AES\_128\_CCM\_8\_SHA256 ### TLS 1.2 Cipher Suites - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_DHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA > [!NOTE] These cipher suites are configured in the `${MULE_HOME}/conf/tls-fips140-3.conf` file. > FIPS 140-3 requires support for TLS 1.3 and TLS 1.2. Earlier TLS versions aren’t supported. ## FIPS 140-3 Compliant Keystore Formats Keystores or truststores in non-FIPS environments are typically formatted as `PKCS12` or `JKS`. These formats aren’t FIPS-compliant. Convert them to `BCFKS` format. 1. Use this example command to convert a `JKS` keystore to `BCFKS` format. If the source keystore is `PKCS12`, set `-srcstoretype` to `PKCS12` in the `keytool` command: BC\_FIPS\_JAR=${MULE\_HOME}/lib/boot/bc-fips-2.1.2.jar # Replace with a correct path OLD\_KEYSTORE="keystore.jks" # Replace with the keystore to convert OLD\_PASSWD="changeit" # Replace with the keystore password NEW\_KEYSTORE="keystore.bcfks" # Replace with the new keystore NEW\_PASSWD="changeit" # Replace with the new keystore password keytool -importkeystore \\ -providerclass sun.security.provider.Sun \\ -providerclass org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider \\ -providerpath ${BC\_FIPS\_JAR} \\ -srckeystore ${OLD\_KEYSTORE} -srcstoretype JKS -srcstorepass ${OLD\_PASSWD} \\ -destkeystore ${NEW\_KEYSTORE} -deststoretype BCFKS -deststorepass ${NEW\_PASSWD} 2. Update the [TLS configuration](https://docs.mulesoft.com/mule-runtime/4.12/tls-configuration) in your Mule application to use the new keystore or truststore: 3. By default, the JVM truststore at `${JAVA_HOME}/lib/security/cacerts` is a `JKS`. There are two approaches to handle this special case: - Convert to BCFKS - Convert the `JKS` store to `BCFKS` using the `keytool` command as described in [FIPS 140-3 Compliant Keystore Formats](#fips-140-3-compliant-keystore-formats), pointing OLD\_KEYSTORE to `${JAVA_HOME}/lib/security/cacerts` and NEW\_KEYSTORE to `${JAVA_HOME}/lib/security/cacerts.bcfks` - Add these properties to your `wrapper.conf` file: wrapper.java.additional.=-Djavax.net.ssl.trustStore=${JAVA\_HOME}/lib/security/cacerts.bcfks wrapper.java.additional.=-Djavax.net.ssl.trustStorePassword=changeit wrapper.java.additional.=-Djavax.net.ssl.trustStoreType=bcfks - Allow legacy `JKS` store - Add this property to your `wrapper.conf` file: wrapper.java.additional.=-Dorg.bouncycastle.jca.enable\_jks=true ## Connectors Compatibility Only connectors tagged as `fips-140-3-verified` in Anypoint Exchange are certified for use in FIPS 140-3 environments. To check compliance in Exchange before deploying: 1. Open Anypoint Exchange. 2. Search for the connector. 3. Check for the `fips-140-3-verified` tag. ## Tips and Limitations - Not all encryption schemes and signatures are FIPS 140-3 compliant. If your application uses a non-approved algorithm, you get this runtime error: Could not find encryption algorithm ''. You are running in FIPS mode, so please verify that the algorithm is compliant with FIPS. - Different environments can have different security configurations. Test before deploying to production. ## See Also - [Validated FIPS 140-3 Cryptographic Modules](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules) - [FIPS 140-3 Standard](https://csrc.nist.gov/publications/detail/fips/140/3/final) - [FIPS 140-2 Compliance Support](https://docs.mulesoft.com/mule-runtime/4.12/fips-140-2-compliance-support) --- product: Mule Runtime version: 4.9 keywords: fips, certifications, security, fips-140-3 --- # FIPS 140-3 Compliance Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Run Mule 4 in a Federal Information Processing Standard (FIPS) 140-3 certified environment by enabling approved cryptography providers and runtime settings. Use this guide to install BC-FJA, enable FIPS mode, and configure TLS and keystore formats for compliant deployments. These steps help you meet federal cryptography requirements while keeping runtime behavior predictable across environments. Mule doesn’t run in FIPS security mode by default. To use FIPS security mode: - Install a certified cryptography module in your Java environment. - Adjust Mule runtime settings to run in FIPS security mode. ## Compatibility FIPS 140-3 support requires: - Mule 4.9.17 or later (for earlier versions of Mule runtime, use [FIPS 140-2 Compliance Support](https://docs.mulesoft.com/mule-runtime/4.9/fips-140-2-compliance-support)) - Java 17 or later - FIPS license from the license `.zip` file provided by MuleSoft (the non-FIPS license isn’t valid for FIPS mode) ## Assumptions This document assumes you’re familiar with [FIPS 140-3](https://csrc.nist.gov/publications/detail/fips/140/3/final), the US government security standard that requires that compliant parties use only cryptographic algorithms and techniques that have been certified by NIST. These instructions use BC-FJA, the recommended FIPS 140-3 certified security provider for Mule runtime ([Certificate #4943](https://csrc.nist.gov/projects/cryptographic-module-validation-program/certificate/4943)). If you use a different [certified security provider](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules), refer to that provider’s documentation for configuration instructions. ## Installing BC-FJA Security Provider Mule runtime uses BC-FJA 2.1.2 as its FIPS 140-3 certified cryptography provider. ### Installation Steps These instructions show how to install and configure BC-FJA security provider in Java 17 or later. 1. Verify that you’re using Java 17 or later and `JAVA_HOME` is set. 2. Download the BC-FJA 2.1.2 provider files from [the BouncyCastle website](https://www.bouncycastle.org/fips-java/). 3. Copy the required JAR files to the `${MULE_HOME}/lib/boot` folder: bc-fips-2.1.2.jar bcutil-fips-2.1.5.jar bctls-fips-2.1.22.jar bcpkix-fips-2.1.10.jar 4. Configure the security properties in `java.security`. - Security providers: security.provider.1=org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider fips:BCFIPS > [!NOTE] On ARM64 (AArch64) architectures, register the `SUN` provider. BC-FJA 2.1.2 doesn’t > include a `SecureRandom` implementation for AArch64 (its native cryptographic library > targets x86\_64 only). The JVM’s `securerandom.strongAlgorithms` property defaults to > `NativePRNGBlocking:SUN` and `DRBG:SUN`. Without a provider that supplies these algorithms, > the JVM fails during early bootstrap, before Mule logs initialize. > > Add `SUN` as security provider 3: > > security.provider.1=org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider > security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider fips:BCFIPS > security.provider.3=SUN 5. Set the key manager and trust manager algorithms: ssl.KeyManagerFactory.algorithm=PKIX ssl.TrustManagerFactory.algorithm=PKIX 6. Set the keystore type: keystore.type=FIPS ## Running Mule in FIPS Security Mode After installing the BC-FJA provider, configure Mule to run in FIPS 140-3 mode: 1. Open your `wrapper.conf` file (located in `${MULE_HOME}/conf`). 2. Add these properties. Replace `` with the next sequential number in your file: \# Enable FIPS 140-3 security mode wrapper.java.additional.=-Dmule.security.model=fips140-3 # Enable Bouncy Castle approved-only mode wrapper.java.additional.=-Dorg.bouncycastle.fips.approved\_only=true # Required for Java 17+ module access wrapper.java.additional.=--add-opens=java.base/sun.security.provider=org.bouncycastle.fips.core # Set keystore type to BCFKS wrapper.java.additional.=-Dmule.keystore.type=BCFKS 3. If you’re using a clustered environment, also add the cluster encryption key: wrapper.java.additional.=-Dmule.cluster.network.encryption.key={your-encryption-key} For more information about clustering in FIPS mode, see [Cluster reference](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#cluster_fips). 4. Save your changes and start Mule runtime. > [!IMPORTANT] In FIPS-compliant environments, all keystores and truststores typically require BCFKS > format. To support legacy JKS stores, such as the default Java truststore at > `${JAVA_HOME}/lib/security/cacerts`, see > [FIPS 140-3 Compliant Keystore Formats](#fips-140-3-compliant-keystore-formats) for configuration > options. When Mule launches, the startup logs show that FIPS 140-3 security mode is enabled. Mule automatically restricts protocol negotiations to use only approved cryptographic cipher suites. > [!IMPORTANT] Not all connectors are FIPS 140-3 compliant. Only connectors tagged as > `fips-140-3-verified` in Anypoint Exchange are certified to use in FIPS 140-3 environments. Always > verify compliance in Exchange before deploying. ## FIPS 140-3 Compliant Cipher Suites These cipher suites are enabled by default when running Mule in FIPS 140-3 mode. ### TLS 1.3 Cipher Suites - TLS\_AES\_128\_GCM\_SHA256 - TLS\_AES\_256\_GCM\_SHA384 - TLS\_AES\_128\_CCM\_SHA256 - TLS\_AES\_128\_CCM\_8\_SHA256 ### TLS 1.2 Cipher Suites - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_DHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA > [!NOTE] These cipher suites are configured in the `${MULE_HOME}/conf/tls-fips140-3.conf` file. > FIPS 140-3 requires support for TLS 1.3 and TLS 1.2. Earlier TLS versions aren’t supported. ## FIPS 140-3 Compliant Keystore Formats Keystores or truststores in non-FIPS environments are typically formatted as `PKCS12` or `JKS`. These formats aren’t FIPS-compliant. Convert them to `BCFKS` format. 1. Use this example command to convert a `JKS` keystore to `BCFKS` format. If the source keystore is `PKCS12`, set `-srcstoretype` to `PKCS12` in the `keytool` command: BC\_FIPS\_JAR=${MULE\_HOME}/lib/boot/bc-fips-2.1.2.jar # Replace with a correct path OLD\_KEYSTORE="keystore.jks" # Replace with the keystore to convert OLD\_PASSWD="changeit" # Replace with the keystore password NEW\_KEYSTORE="keystore.bcfks" # Replace with the new keystore NEW\_PASSWD="changeit" # Replace with the new keystore password keytool -importkeystore \\ -providerclass sun.security.provider.Sun \\ -providerclass org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider \\ -providerpath ${BC\_FIPS\_JAR} \\ -srckeystore ${OLD\_KEYSTORE} -srcstoretype JKS -srcstorepass ${OLD\_PASSWD} \\ -destkeystore ${NEW\_KEYSTORE} -deststoretype BCFKS -deststorepass ${NEW\_PASSWD} 2. Update the [TLS configuration](https://docs.mulesoft.com/mule-runtime/4.9/tls-configuration) in your Mule application to use the new keystore or truststore: 3. By default, the JVM truststore at `${JAVA_HOME}/lib/security/cacerts` is a `JKS`. There are two approaches to handle this special case: - Convert to BCFKS - Convert the `JKS` store to `BCFKS` using the `keytool` command as described in [FIPS 140-3 Compliant Keystore Formats](#fips-140-3-compliant-keystore-formats), pointing OLD\_KEYSTORE to `${JAVA_HOME}/lib/security/cacerts` and NEW\_KEYSTORE to `${JAVA_HOME}/lib/security/cacerts.bcfks` - Add these properties to your `wrapper.conf` file: wrapper.java.additional.=-Djavax.net.ssl.trustStore=${JAVA\_HOME}/lib/security/cacerts.bcfks wrapper.java.additional.=-Djavax.net.ssl.trustStorePassword=changeit wrapper.java.additional.=-Djavax.net.ssl.trustStoreType=bcfks - Allow legacy `JKS` store - Add this property to your `wrapper.conf` file: wrapper.java.additional.=-Dorg.bouncycastle.jca.enable\_jks=true ## Connectors Compatibility Only connectors tagged as `fips-140-3-verified` in Anypoint Exchange are certified for use in FIPS 140-3 environments. To check compliance in Exchange before deploying: 1. Open Anypoint Exchange. 2. Search for the connector. 3. Check for the `fips-140-3-verified` tag. ## Tips and Limitations - Not all encryption schemes and signatures are FIPS 140-3 compliant. If your application uses a non-approved algorithm, you get this runtime error: Could not find encryption algorithm ''. You are running in FIPS mode, so please verify that the algorithm is compliant with FIPS. - Different environments can have different security configurations. Test before deploying to production. ## See Also - [Validated FIPS 140-3 Cryptographic Modules](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules) - [FIPS 140-3 Standard](https://csrc.nist.gov/publications/detail/fips/140/3/final) - [FIPS 140-2 Compliance Support](https://docs.mulesoft.com/mule-runtime/4.9/fips-140-2-compliance-support) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: fips, certifications, security, fips-140-3 --- # FIPS 140-3 Compliance Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Run Mule 4 in a Federal Information Processing Standard (FIPS) 140-3 certified environment by enabling approved cryptography providers and runtime settings. Use this guide to install BC-FJA, enable FIPS mode, and configure TLS and keystore formats for compliant deployments. These steps help you meet federal cryptography requirements while keeping runtime behavior predictable across environments. Mule doesn’t run in FIPS security mode by default. To use FIPS security mode: - Install a certified cryptography module in your Java environment. - Adjust Mule runtime settings to run in FIPS security mode. ## Compatibility FIPS 140-3 support requires: - Mule 4.11.4 or later (for earlier versions of Mule runtime, use [FIPS 140-2 Compliance Support](https://docs.mulesoft.com/mule-runtime/latest/fips-140-2-compliance-support)) - Java 17 or later - FIPS license from the license `.zip` file provided by MuleSoft (the non-FIPS license isn’t valid for FIPS mode) ## Assumptions This document assumes you’re familiar with [FIPS 140-3](https://csrc.nist.gov/publications/detail/fips/140/3/final), the US government security standard that requires that compliant parties use only cryptographic algorithms and techniques that have been certified by NIST. These instructions use BC-FJA, the recommended FIPS 140-3 certified security provider for Mule runtime ([Certificate #4943](https://csrc.nist.gov/projects/cryptographic-module-validation-program/certificate/4943)). If you use a different [certified security provider](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules), refer to that provider’s documentation for configuration instructions. ## Installing BC-FJA Security Provider Mule runtime uses BC-FJA 2.1.2 as its FIPS 140-3 certified cryptography provider. ### Installation Steps These instructions show how to install and configure BC-FJA security provider in Java 17 or later. 1. Verify that you’re using Java 17 or later and `JAVA_HOME` is set. 2. Download the BC-FJA 2.1.2 provider files from [the BouncyCastle website](https://www.bouncycastle.org/fips-java/). 3. Copy the required JAR files to the `${MULE_HOME}/lib/boot` folder: bc-fips-2.1.2.jar bcutil-fips-2.1.5.jar bctls-fips-2.1.22.jar bcpkix-fips-2.1.10.jar 4. Configure the security properties in `java.security`. - Security providers: security.provider.1=org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider fips:BCFIPS > [!NOTE] On ARM64 (AArch64) architectures, register the `SUN` provider. BC-FJA 2.1.2 doesn’t > include a `SecureRandom` implementation for AArch64 (its native cryptographic library > targets x86\_64 only). The JVM’s `securerandom.strongAlgorithms` property defaults to > `NativePRNGBlocking:SUN` and `DRBG:SUN`. Without a provider that supplies these algorithms, > the JVM fails during early bootstrap, before Mule logs initialize. > > Add `SUN` as security provider 3: > > security.provider.1=org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider > security.provider.2=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider fips:BCFIPS > security.provider.3=SUN 5. Set the key manager and trust manager algorithms: ssl.KeyManagerFactory.algorithm=PKIX ssl.TrustManagerFactory.algorithm=PKIX 6. Set the keystore type: keystore.type=FIPS ## Running Mule in FIPS Security Mode After installing the BC-FJA provider, configure Mule to run in FIPS 140-3 mode: 1. Open your `wrapper.conf` file (located in `${MULE_HOME}/conf`). 2. Add these properties. Replace `` with the next sequential number in your file: \# Enable FIPS 140-3 security mode wrapper.java.additional.=-Dmule.security.model=fips140-3 # Enable Bouncy Castle approved-only mode wrapper.java.additional.=-Dorg.bouncycastle.fips.approved\_only=true # Required for Java 17+ module access wrapper.java.additional.=--add-opens=java.base/sun.security.provider=org.bouncycastle.fips.core # Set keystore type to BCFKS wrapper.java.additional.=-Dmule.keystore.type=BCFKS 3. If you’re using a clustered environment, also add the cluster encryption key: wrapper.java.additional.=-Dmule.cluster.network.encryption.key={your-encryption-key} For more information about clustering in FIPS mode, see [Cluster reference](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#cluster_fips). 4. Save your changes and start Mule runtime. > [!IMPORTANT] In FIPS-compliant environments, all keystores and truststores typically require BCFKS > format. To support legacy JKS stores, such as the default Java truststore at > `${JAVA_HOME}/lib/security/cacerts`, see > [FIPS 140-3 Compliant Keystore Formats](#fips-140-3-compliant-keystore-formats) for configuration > options. When Mule launches, the startup logs show that FIPS 140-3 security mode is enabled. Mule automatically restricts protocol negotiations to use only approved cryptographic cipher suites. > [!IMPORTANT] Not all connectors are FIPS 140-3 compliant. Only connectors tagged as > `fips-140-3-verified` in Anypoint Exchange are certified to use in FIPS 140-3 environments. Always > verify compliance in Exchange before deploying. ## FIPS 140-3 Compliant Cipher Suites These cipher suites are enabled by default when running Mule in FIPS 140-3 mode. ### TLS 1.3 Cipher Suites - TLS\_AES\_128\_GCM\_SHA256 - TLS\_AES\_256\_GCM\_SHA384 - TLS\_AES\_128\_CCM\_SHA256 - TLS\_AES\_128\_CCM\_8\_SHA256 ### TLS 1.2 Cipher Suites - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_DHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384 - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA384 - TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA - TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA - TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA > [!NOTE] These cipher suites are configured in the `${MULE_HOME}/conf/tls-fips140-3.conf` file. > FIPS 140-3 requires support for TLS 1.3 and TLS 1.2. Earlier TLS versions aren’t supported. ## FIPS 140-3 Compliant Keystore Formats Keystores or truststores in non-FIPS environments are typically formatted as `PKCS12` or `JKS`. These formats aren’t FIPS-compliant. Convert them to `BCFKS` format. 1. Use this example command to convert a `JKS` keystore to `BCFKS` format. If the source keystore is `PKCS12`, set `-srcstoretype` to `PKCS12` in the `keytool` command: BC\_FIPS\_JAR=${MULE\_HOME}/lib/boot/bc-fips-2.1.2.jar # Replace with a correct path OLD\_KEYSTORE="keystore.jks" # Replace with the keystore to convert OLD\_PASSWD="changeit" # Replace with the keystore password NEW\_KEYSTORE="keystore.bcfks" # Replace with the new keystore NEW\_PASSWD="changeit" # Replace with the new keystore password keytool -importkeystore \\ -providerclass sun.security.provider.Sun \\ -providerclass org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider \\ -providerpath ${BC\_FIPS\_JAR} \\ -srckeystore ${OLD\_KEYSTORE} -srcstoretype JKS -srcstorepass ${OLD\_PASSWD} \\ -destkeystore ${NEW\_KEYSTORE} -deststoretype BCFKS -deststorepass ${NEW\_PASSWD} 2. Update the [TLS configuration](https://docs.mulesoft.com/mule-runtime/latest/tls-configuration) in your Mule application to use the new keystore or truststore: 3. By default, the JVM truststore at `${JAVA_HOME}/lib/security/cacerts` is a `JKS`. There are two approaches to handle this special case: - Convert to BCFKS - Convert the `JKS` store to `BCFKS` using the `keytool` command as described in [FIPS 140-3 Compliant Keystore Formats](#fips-140-3-compliant-keystore-formats), pointing OLD\_KEYSTORE to `${JAVA_HOME}/lib/security/cacerts` and NEW\_KEYSTORE to `${JAVA_HOME}/lib/security/cacerts.bcfks` - Add these properties to your `wrapper.conf` file: wrapper.java.additional.=-Djavax.net.ssl.trustStore=${JAVA\_HOME}/lib/security/cacerts.bcfks wrapper.java.additional.=-Djavax.net.ssl.trustStorePassword=changeit wrapper.java.additional.=-Djavax.net.ssl.trustStoreType=bcfks - Allow legacy `JKS` store - Add this property to your `wrapper.conf` file: wrapper.java.additional.=-Dorg.bouncycastle.jca.enable\_jks=true ## Connectors Compatibility Only connectors tagged as `fips-140-3-verified` in Anypoint Exchange are certified for use in FIPS 140-3 environments. To check compliance in Exchange before deploying: 1. Open Anypoint Exchange. 2. Search for the connector. 3. Check for the `fips-140-3-verified` tag. ## Tips and Limitations - Not all encryption schemes and signatures are FIPS 140-3 compliant. If your application uses a non-approved algorithm, you get this runtime error: Could not find encryption algorithm ''. You are running in FIPS mode, so please verify that the algorithm is compliant with FIPS. - Different environments can have different security configurations. Test before deploying to production. ## See Also - [Validated FIPS 140-3 Cryptographic Modules](https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules) - [FIPS 140-3 Standard](https://csrc.nist.gov/publications/detail/fips/140/3/final) - [FIPS 140-2 Compliance Support](https://docs.mulesoft.com/mule-runtime/latest/fips-140-2-compliance-support) --- product: Mule Runtime version: 4.11 keywords: routers, flows, processor chain, async, aggregator, resequencer --- # First Successful Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The First Successful router iterates through a list of configured processing routes until one of the routes executes successfully. If any processing route fails execution (throws an error), the router executes the next configured route. If none of the configured routes execute successfully, the First Successful router throws an error. ## First Successful Router Configuration Example The following example shows a First Successful router configured with four processing routes: ```xml ``` Execution behavior for the previous example is as follows: 1. The first route executes and fails because it tries to read a file that does not exist. 2. The second route fails because it tries to access a variable that does not exist. 3. The third route executes successfully and sets variable `successfulRoute` with value `3`. 4. The fourth route is not executed because the First Successful router stops executing routes after one of them completes successfully. ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.11/mule-error-concept) - [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.11/error-handling) --- product: Mule Runtime version: 4.12 keywords: routers, flows, processor chain, async, aggregator, resequencer --- # First Successful Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The First Successful router iterates through a list of configured processing routes until one of the routes executes successfully. If any processing route fails execution (throws an error), the router executes the next configured route. If none of the configured routes execute successfully, the First Successful router throws an error. ## First Successful Router Configuration Example The following example shows a First Successful router configured with four processing routes: ```xml ``` Execution behavior for the previous example is as follows: 1. The first route executes and fails because it tries to read a file that does not exist. 2. The second route fails because it tries to access a variable that does not exist. 3. The third route executes successfully and sets variable `successfulRoute` with value `3`. 4. The fourth route is not executed because the First Successful router stops executing routes after one of them completes successfully. ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.12/mule-error-concept) - [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.12/error-handling) --- product: Mule Runtime version: 4.3 keywords: routers, flows, processor chain, async, aggregator, resequencer --- # First Successful Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The First Successful router iterates through a list of configured processing routes until one of the routes executes successfully. If any processing route fails execution (throws an error), the router executes the next configured route. If none of the configured routes execute successfully, the First Successful router throws an error. ## First Successful Router Configuration Example The following example shows a First Successful router configured with four processing routes: ```xml ``` Execution behavior for the previous example is as follows: 1. The first route executes and fails because it tries to read a file that does not exist. 2. The second route fails because it tries to access a variable that does not exist. 3. The third route executes successfully and sets variable `successfulRoute` with value `3`. 4. The fourth route is not executed because the First Successful router stops executing routes after one of them completes successfully. ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.3/mule-error-concept) - [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.3/error-handling) --- product: Mule Runtime version: 4.4 keywords: routers, flows, processor chain, async, aggregator, resequencer --- # First Successful Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The First Successful router iterates through a list of configured processing routes until one of the routes executes successfully. If any processing route fails execution (throws an error), the router executes the next configured route. If none of the configured routes execute successfully, the First Successful router throws an error. ## First Successful Router Configuration Example The following example shows a First Successful router configured with four processing routes: ```xml ``` Execution behavior for the previous example is as follows: 1. The first route executes and fails because it tries to read a file that does not exist. 2. The second route fails because it tries to access a variable that does not exist. 3. The third route executes successfully and sets variable `successfulRoute` with value `3`. 4. The fourth route is not executed because the First Successful router stops executing routes after one of them completes successfully. ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.4/mule-error-concept) - [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.4/error-handling) --- product: Mule Runtime version: 4.6 keywords: routers, flows, processor chain, async, aggregator, resequencer --- # First Successful Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The First Successful router iterates through a list of configured processing routes until one of the routes executes successfully. If any processing route fails execution (throws an error), the router executes the next configured route. If none of the configured routes execute successfully, the First Successful router throws an error. ## First Successful Router Configuration Example The following example shows a First Successful router configured with four processing routes: ```xml ``` Execution behavior for the previous example is as follows: 1. The first route executes and fails because it tries to read a file that does not exist. 2. The second route fails because it tries to access a variable that does not exist. 3. The third route executes successfully and sets variable `successfulRoute` with value `3`. 4. The fourth route is not executed because the First Successful router stops executing routes after one of them completes successfully. ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.6/mule-error-concept) - [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.6/error-handling) --- product: Mule Runtime version: 4.9 keywords: routers, flows, processor chain, async, aggregator, resequencer --- # First Successful Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The First Successful router iterates through a list of configured processing routes until one of the routes executes successfully. If any processing route fails execution (throws an error), the router executes the next configured route. If none of the configured routes execute successfully, the First Successful router throws an error. ## First Successful Router Configuration Example The following example shows a First Successful router configured with four processing routes: ```xml ``` Execution behavior for the previous example is as follows: 1. The first route executes and fails because it tries to read a file that does not exist. 2. The second route fails because it tries to access a variable that does not exist. 3. The third route executes successfully and sets variable `successfulRoute` with value `3`. 4. The fourth route is not executed because the First Successful router stops executing routes after one of them completes successfully. ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.9/mule-error-concept) - [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.9/error-handling) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: routers, flows, processor chain, async, aggregator, resequencer --- # First Successful Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The First Successful router iterates through a list of configured processing routes until one of the routes executes successfully. If any processing route fails execution (throws an error), the router executes the next configured route. If none of the configured routes execute successfully, the First Successful router throws an error. ## First Successful Router Configuration Example The following example shows a First Successful router configured with four processing routes: ```xml ``` Execution behavior for the previous example is as follows: 1. The first route executes and fails because it tries to read a file that does not exist. 2. The second route fails because it tries to access a variable that does not exist. 3. The third route executes successfully and sets variable `successfulRoute` with value `3`. 4. The fourth route is not executed because the First Successful router stops executing routes after one of them completes successfully. ## See Also - [Mule Errors](https://docs.mulesoft.com/mule-runtime/latest/mule-error-concept) - [Error Handlers](https://docs.mulesoft.com/mule-runtime/latest/error-handling) --- product: Mule Runtime version: 4.11 keywords: component, Mule 4 --- # Flow and Subflow Scopes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow and Subflow scopes are components for grouping together a sequence of other Core components and operations (provided by connectors and modules) to help automate integration processes. The Flow component is fundamental to a Mule app. Because all Mule apps must contain at least one flow, Anypoint Studio automatically provides the first Flow component in your Mule app. A Mule app can contain additional flows and subflows, as this example shows: ![A flow including a scheduler, error handling, and multiple subflow references in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/component-flow-subflow.png) Figure 1. Example: Flow with Subflows For a more in-depth discussion of uses, capabilities, and limits of flows and subflows, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.11/about-flows). Note that flows always function synchronously. If you need to achieve asynchronous patterns, such as Fire-and-Forget, you can use the [Async Scope](https://docs.mulesoft.com/mule-runtime/4.11/async-scope-reference) (``). ## Flow Configuration Flows are configurable. For example, you can set them to start or remained stopped when the Mule app starts, place limits on the allowed concurrency, or set up business events. You can also set up error handling for a component (see [Error Handling](#error_handling)).
FieldDescription

Name (name)

Name for the flow. Flows automatically receive an editable name that matches (or partially matches) the project name.

Initial State (initialState)

Values: Started, Stopped. These are Mule runtime settings for the flow. The default, Started (initialState="started", also called Empty in Studio), indicates that the flow is active when you start the app. So it can be triggered by an internal or external Mule event source within the flow (such as an HTTP listener or Scheduler), by a Flow Reference from another flow or subflow, or through a call to the lookup function.

If you set the initial state to Stopped (initialState="stopped"), activate the flow after deployment. For hybrid standalone and Anypoint Platform PCE deployments, use Runtime Manager to activate the flow. For CloudHub and Anypoint Runtime Fabric deployments, flow management through Runtime Manager isn’t supported. To activate the flow, redeploy the application or update the flow configuration to Started. When a flow is deployed with the initial state set to Stopped, the console output looks similar to this: Flow flow_component_ex has not been started (initial state = 'stopped').

For CloudHub deployments, avoid setting initialState="stopped" on flows that contain a Scheduler. The scheduler gets stuck in a permanent "Running" state, and you can’t manage it through Runtime Manager.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that a flow can process. If not set, the container thread pool determines the maximum number of threads the flow can use to optimize the performance when processing messages. While the flow is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the flow to process requests one at a time.

See Back-pressure for details about Mule’s behavior after the maximum concurrency value is reached.

Business Events

Optional: Defaults to false. For Mule apps that you deploy to CloudHub, you can enable business events (XML example: tracking:enable-default-event="true") and add a Transaction ID (XML example: <tracking:transaction id=12345/>). See Business Events.

Metadata

As with many other components, you can set metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## Subflow Configuration Subflow scopes provide a way to edit the name of the subflow and to add metadata. Unlike flows, subflows lack a built-in mechanism for setting up error handling, though you can use error handling provided by the [Try Scope](https://docs.mulesoft.com/mule-runtime/4.11/try-scope-concept) within a subflow if you need to perform error handling.
FieldDescription

Name (name)

Name for the subflow. Subflows automatically receive an editable name that matches (or partially matches) the project name.

Metadata

As with many other components, you can set up metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## XML for Flows and Subflows This example shows the XML for a simple flow (``) that uses a Scheduler as a source to trigger execution of the flow every 10 seconds, and it connects to a subflow (``) through a Flow Ref (``) component. That subflow then connects to another subflow, also using a Flow Ref component. Note that when you configure components through the Studio UI, Studio automatically adds the XML to the Configuration XML for your Mule app. Example: XML for a Flow and Subflows ```xml 9.99 53 398.99 ', 'application/xml') output application/xml --- myXml ]]> { (key) : { dollars: value, localCurrency: value * conversionRate, index_plus_1: index + 1, timer : currentMilliseconds() } }]]> ``` The example produces the following output: Output ```json { "priceList": { "basic": { "dollars": "9.99", "localCurrency": 129.87, "index_plus_1": 1, "timer": 1533024312658 }, "premium": { "dollars": "53", "localCurrency": 689, "index_plus_1": 2, "timer": 1533024312659 }, "vip": { "dollars": "398.99", "localCurrency": 5186.87, "index_plus_1": 3, "timer": 1533024312659 } } } ``` ## Error Handling You can add [error handlers](https://docs.mulesoft.com/mule-runtime/4.11/error-handling) to the Flow components (but not to subflows). In Studio, you can simply expand the Error Handling area at the bottom of the Flow component and drag the error components into the flow. Note that this process automatically places the component into the Error Handler component, so there is no need to add the Error Handler component first. Near the end of this XML example, the flow shows an On Error Continue configuration (``): Example: XML for Flow with On Error Continue Configuration ```xml ', 'application/xml') output application/xml --- myXml ]]> ``` The preceding example produces an error. Notice the following: 1. The variable `var myXml` in `` configures an empty `` tag as the payload. 2. The Logger beside the `` component returns `null` because it is set to log the value of the empty tag. 3. The `` component returns an error because the DataWeave condition `isEmpty(payload.prices)` returns `true`. 4. The Logger (``) within `` configures an error message to print to the console when an error occurs. The resulting error message looks something like this: ```text ERROR 2018-07-30 23:58:45,293 [[MuleRuntime].cpuLight.06: [flow_subflow].flow_subflowFlow.CPU_LITE @1b1529b2] [event: 0-2aba3280-948f-11e8-82d0-f45c898f2549] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: "An Error Occurred" ``` For details about these components, see [On-Error](https://docs.mulesoft.com/mule-runtime/4.11/on-error-scope-concept) error handlers. ## See Also - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.11/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.12 keywords: component, Mule 4 --- # Flow and Subflow Scopes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow and Subflow scopes are components for grouping together a sequence of other Core components and operations (provided by connectors and modules) to help automate integration processes. The Flow component is fundamental to a Mule app. Because all Mule apps must contain at least one flow, Anypoint Studio automatically provides the first Flow component in your Mule app. A Mule app can contain additional flows and subflows, as this example shows: ![A flow including a scheduler, error handling, and multiple subflow references in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/component-flow-subflow.png) Figure 1. Example: Flow with Subflows For a more in-depth discussion of uses, capabilities, and limits of flows and subflows, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.12/about-flows). Note that flows always function synchronously. If you need to achieve asynchronous patterns, such as Fire-and-Forget, you can use the [Async Scope](https://docs.mulesoft.com/mule-runtime/4.12/async-scope-reference) (``). ## Flow Configuration Flows are configurable. For example, you can set them to start or remained stopped when the Mule app starts, place limits on the allowed concurrency, or set up business events. You can also set up error handling for a component (see [Error Handling](#error_handling)).
FieldDescription

Name (name)

Name for the flow. Flows automatically receive an editable name that matches (or partially matches) the project name.

Initial State (initialState)

Values: started, stopped. These are Mule runtime settings for the flow. The default, started (initialState="started", also called Empty in Studio), indicates that the flow is active when you start the app. So it can be triggered by an internal or external Mule event source within the flow (such as an HTTP listener or Scheduler), by a Flow Reference from another flow or subflow, or through a call to the lookup function.

If you set the initial state to stopped (initialState="stopped"), activate the flow after deployment. For hybrid standalone and Anypoint Platform PCE deployments, use Runtime Manager to activate the flow. For CloudHub and Anypoint Runtime Fabric deployments, flow management through Runtime Manager isn’t supported. To activate the flow, redeploy the application or update the flow configuration to started. When a flow is deployed with the initial state set to stopped, the console output looks similar to this: Flow flow_component_ex has not been started (initial state = 'stopped').

For CloudHub deployments, avoid setting initialState="stopped" on flows that contain a Scheduler. The scheduler gets stuck in a permanent "Running" state, and you can’t manage it through Runtime Manager.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that a flow can process. If not set, the container thread pool determines the maximum number of threads the flow can use to optimize the performance when processing messages. While the flow is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the flow to process requests one at a time.

See Back-pressure for details about Mule’s behavior after the maximum concurrency value is reached.

Business Events

Optional: Defaults to false. For Mule apps that you deploy to CloudHub, you can enable business events (XML example: tracking:enable-default-event="true") and add a Transaction ID (XML example: <tracking:transaction id=12345/>). See Business Events.

Metadata

As with many other components, you can set metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## Subflow Configuration Subflow scopes provide a way to edit the name of the subflow and to add metadata. Unlike flows, subflows lack a built-in mechanism for setting up error handling, though you can use error handling provided by the [Try Scope](https://docs.mulesoft.com/mule-runtime/4.12/try-scope-concept) within a subflow if you need to perform error handling.
FieldDescription

Name (name)

Name for the subflow. Subflows automatically receive an editable name that matches (or partially matches) the project name.

Metadata

As with many other components, you can set up metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## XML for Flows and Subflows This example shows the XML for a simple flow (``) that uses a Scheduler as a source to trigger execution of the flow every 10 seconds, and it connects to a subflow (``) through a Flow Ref (``) component. That subflow then connects to another subflow, also using a Flow Ref component. Note that when you configure components through the Studio UI, Studio automatically adds the XML to the Configuration XML for your Mule app. Example: XML for a Flow and Subflows ```xml 9.99 53 398.99 ', 'application/xml') output application/xml --- myXml ]]> { (key) : { dollars: value, localCurrency: value * conversionRate, index_plus_1: index + 1, timer : currentMilliseconds() } }]]> ``` The example produces the following output: Output ```json { "priceList": { "basic": { "dollars": "9.99", "localCurrency": 129.87, "index_plus_1": 1, "timer": 1533024312658 }, "premium": { "dollars": "53", "localCurrency": 689, "index_plus_1": 2, "timer": 1533024312659 }, "vip": { "dollars": "398.99", "localCurrency": 5186.87, "index_plus_1": 3, "timer": 1533024312659 } } } ``` ## Error Handling You can add [error handlers](https://docs.mulesoft.com/mule-runtime/4.12/error-handling) to the Flow components (but not to subflows). In Studio, you can simply expand the Error Handling area at the bottom of the Flow component and drag the error components into the flow. Note that this process automatically places the component into the Error Handler component, so there is no need to add the Error Handler component first. Near the end of this XML example, the flow shows an On Error Continue configuration (``): Example: XML for Flow with On Error Continue Configuration ```xml ', 'application/xml') output application/xml --- myXml ]]> ``` The preceding example produces an error. Notice the following: 1. The variable `var myXml` in `` configures an empty `` tag as the payload. 2. The Logger beside the `` component returns `null` because it is set to log the value of the empty tag. 3. The `` component returns an error because the DataWeave condition `isEmpty(payload.prices)` returns `true`. 4. The Logger (``) within `` configures an error message to print to the console when an error occurs. The resulting error message looks something like this: ```text ERROR 2018-07-30 23:58:45,293 [[MuleRuntime].cpuLight.06: [flow_subflow].flow_subflowFlow.CPU_LITE @1b1529b2] [event: 0-2aba3280-948f-11e8-82d0-f45c898f2549] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: "An Error Occurred" ``` For details about these components, see [On-Error](https://docs.mulesoft.com/mule-runtime/4.12/on-error-scope-concept) error handlers. ## See Also - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.12/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.3 keywords: component, Mule 4 --- # Flow and Subflow Scopes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow and Subflow scopes are components for grouping together a sequence of other Core components and operations (provided by connectors and modules) to help automate integration processes. The Flow component is fundamental to a Mule app. Because all Mule apps must contain at least one flow, Anypoint Studio automatically provides the first Flow component in your Mule app. A Mule app can contain additional flows and subflows, as this example shows: ![Example of Flow with Subflows](/mulesoft/current/en-us/mule-runtime/4.3/_images/component-flow-subflow.png) Figure 1. Example: Flow with Subflows For a more in-depth discussion of uses, capabilities, and limits of flows and subflows, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.3/about-flows). Note that flows always function synchronously. If you need to achieve asynchronous patterns, such as Fire-and-Forget, you can use the [Async Scope](https://docs.mulesoft.com/mule-runtime/4.3/async-scope-reference) (``). ## Flow Configuration Flows are configurable. For example, you can set them to start or remained stopped when the Mule app starts, place limits on the allowed concurrency, or set up business events. You can also set up error handling for a component (see [Error Handling](#error_handling)).
FieldDescription

Name (name)

Name for the flow. Flows automatically receive an editable name that matches (or partially matches) the project name.

Initial State (initialState)

Values: Started, Stopped. These are Mule runtime settings for the flow. The default, Started (initialState="started", also called Empty in Studio), indicates that the flow is active when you start the app. So it can be triggered by an internal or external event source within the flow (such as an HTTP listener or Scheduler), by a Flow Reference from another flow or subflow, or through a call to the lookup function.

If you set the initial state to Stopped (initialState="stopped"), activate the flow after deployment. For hybrid standalone and Anypoint Platform PCE deployments, use Runtime Manager to activate the flow. For CloudHub and Anypoint Runtime Fabric deployments, flow management through Runtime Manager isn’t supported. To activate the flow, redeploy the application or update the flow configuration to Started. When a flow is deployed with the initial state set to Stopped, the console output looks similar to this: Flow flow_component_ex has not been started (initial state = 'stopped').

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that a flow can process. If not set, the container thread pool determines the maximum number of threads the flow can use to optimize the performance when processing messages. While the flow is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the flow to process requests one at a time.

See Back-pressure for details about Mule’s behavior after the the maximum concurrency value is reached.

Business Events

Optional: Defaults to false. For Mule apps that you deploy to CloudHub, you can enable business events (XML example: tracking:enable-default-event="true") and add a Transaction ID (XML example: <tracking:transaction id=12345/>). See Business Events.

Metadata

As with many other components, you can set metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## Subflow Configuration Subflow scopes provide a way to edit the name of the subflow and to add metadata. Unlike flows, subflows lack a built-in mechanism for setting up error handling, though you can use error handling provided by the [Try Scope](https://docs.mulesoft.com/mule-runtime/4.3/try-scope-concept) within a subflow if you need to perform error handling.
FieldDescription

Name (name)

Name for the subflow. Subflows automatically receive an editable name that matches (or partially matches) the project name.

Metadata

As with many other components, you can set up metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## XML for Flows and Subflows This example shows the XML for a simple flow (``) that uses a Scheduler as a source to trigger execution of the flow every 10 seconds, and it connects to a subflow (``) through a Flow Ref (``) component. That subflow then connects to another subflow, also using a Flow Ref component. Note that when you configure components through the Studio UI, Studio automatically adds the XML to the Configuration XML for your Mule app. Example: XML for a Flow and Subflows ```xml 9.99 53 398.99 ', 'application/xml') output application/xml --- myXml ]]> { (key) : { dollars: value, localCurrency: value * conversionRate, index_plus_1: index + 1, timer : currentMilliseconds() } }]]> ``` The example produces the following output: Output ```json { "priceList": { "basic": { "dollars": "9.99", "localCurrency": 129.87, "index_plus_1": 1, "timer": 1533024312658 }, "premium": { "dollars": "53", "localCurrency": 689, "index_plus_1": 2, "timer": 1533024312659 }, "vip": { "dollars": "398.99", "localCurrency": 5186.87, "index_plus_1": 3, "timer": 1533024312659 } } } ``` ## Error Handling You can add [error handlers](https://docs.mulesoft.com/mule-runtime/4.3/error-handling) to the Flow components (but not to subflows). In Studio, you can simply expand the Error Handling area at the bottom of the Flow component and drag the error components into the flow. Note that this process automatically places the component into the Error Handler component, so there is no need to add the Error Handler component first. Near the end of this XML example, the flow shows an On Error Continue configuration (``): Example: XML for Flow with On Error Continue Configuration ```xml ', 'application/xml') output application/xml --- myXml ]]> ``` The preceding example produces an error. Notice the following: 1. The variable `var myXml` in `` configures an empty `` tag as the payload. 2. The Logger beside the `` component returns `null` because it is set to log the value of the empty tag. 3. The `` component returns an error because the DataWeave condition `isEmpty(payload.prices)` returns `true`. 4. The Logger (``) within `` configures an error message to print to the console when an error occurs. The resulting error message looks something like this: ```text ERROR 2018-07-30 23:58:45,293 [[MuleRuntime].cpuLight.06: [flow_subflow].flow_subflowFlow.CPU_LITE @1b1529b2] [event: 0-2aba3280-948f-11e8-82d0-f45c898f2549] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: "An Error Occurred" ``` For details about these components, see [On-Error](https://docs.mulesoft.com/mule-runtime/4.3/on-error-scope-concept) error handlers. ## See Also - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.3/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.4 keywords: component, Mule 4 --- # Flow and Subflow Scopes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow and Subflow scopes are components for grouping together a sequence of other Core components and operations (provided by connectors and modules) to help automate integration processes. The Flow component is fundamental to a Mule app. Because all Mule apps must contain at least one flow, Anypoint Studio automatically provides the first Flow component in your Mule app. A Mule app can contain additional flows and subflows, as this example shows: ![Example of Flow with Subflows](/mulesoft/current/en-us/mule-runtime/4.4/_images/component-flow-subflow.png) Figure 1. Example: Flow with Subflows For a more in-depth discussion of uses, capabilities, and limits of flows and subflows, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.4/about-flows). Note that flows always function synchronously. If you need to achieve asynchronous patterns, such as Fire-and-Forget, you can use the [Async Scope](https://docs.mulesoft.com/mule-runtime/4.4/async-scope-reference) (``). ## Flow Configuration Flows are configurable. For example, you can set them to start or remained stopped when the Mule app starts, place limits on the allowed concurrency, or set up business events. You can also set up error handling for a component (see [Error Handling](#error_handling)).
FieldDescription

Name (name)

Name for the flow. Flows automatically receive an editable name that matches (or partially matches) the project name.

Initial State (initialState)

Values: Started, Stopped. These are Mule runtime settings for the flow. The default, Started (initialState="started", also called Empty in Studio), indicates that the flow is active when you start the app. So it can be triggered by an internal or external Mule event source within the flow (such as an HTTP listener or Scheduler), by a Flow Reference from another flow or subflow, or through a call to the lookup function.

If you set the initial state to Stopped (initialState="stopped"), activate the flow after deployment. For hybrid standalone and Anypoint Platform PCE deployments, use Runtime Manager to activate the flow. For CloudHub and Anypoint Runtime Fabric deployments, flow management through Runtime Manager isn’t supported. To activate the flow, redeploy the application or update the flow configuration to Started. When a flow is deployed with the initial state set to Stopped, the console output looks similar to this: Flow flow_component_ex has not been started (initial state = 'stopped').

For CloudHub deployments, avoid setting initialState="stopped" on flows that contain a Scheduler. The scheduler gets stuck in a permanent "Running" state, and you can’t manage it through Runtime Manager.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that a flow can process. If not set, the container thread pool determines the maximum number of threads the flow can use to optimize the performance when processing messages. While the flow is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the flow to process requests one at a time.

See Back-pressure for details about Mule’s behavior after the the maximum concurrency value is reached.

Business Events

Optional: Defaults to false. For Mule apps that you deploy to CloudHub, you can enable business events (XML example: tracking:enable-default-event="true") and add a Transaction ID (XML example: <tracking:transaction id=12345/>). See Business Events.

Metadata

As with many other components, you can set metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## Subflow Configuration Subflow scopes provide a way to edit the name of the subflow and to add metadata. Unlike flows, subflows lack a built-in mechanism for setting up error handling, though you can use error handling provided by the [Try Scope](https://docs.mulesoft.com/mule-runtime/4.4/try-scope-concept) within a subflow if you need to perform error handling.
FieldDescription

Name (name)

Name for the subflow. Subflows automatically receive an editable name that matches (or partially matches) the project name.

Metadata

As with many other components, you can set up metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## XML for Flows and Subflows This example shows the XML for a simple flow (``) that uses a Scheduler as a source to trigger execution of the flow every 10 seconds, and it connects to a subflow (``) through a Flow Ref (``) component. That subflow then connects to another subflow, also using a Flow Ref component. Note that when you configure components through the Studio UI, Studio automatically adds the XML to the Configuration XML for your Mule app. Example: XML for a Flow and Subflows ```xml 9.99 53 398.99 ', 'application/xml') output application/xml --- myXml ]]> { (key) : { dollars: value, localCurrency: value * conversionRate, index_plus_1: index + 1, timer : currentMilliseconds() } }]]> ``` The example produces the following output: Output ```json { "priceList": { "basic": { "dollars": "9.99", "localCurrency": 129.87, "index_plus_1": 1, "timer": 1533024312658 }, "premium": { "dollars": "53", "localCurrency": 689, "index_plus_1": 2, "timer": 1533024312659 }, "vip": { "dollars": "398.99", "localCurrency": 5186.87, "index_plus_1": 3, "timer": 1533024312659 } } } ``` ## Error Handling You can add [error handlers](https://docs.mulesoft.com/mule-runtime/4.4/error-handling) to the Flow components (but not to subflows). In Studio, you can simply expand the Error Handling area at the bottom of the Flow component and drag the error components into the flow. Note that this process automatically places the component into the Error Handler component, so there is no need to add the Error Handler component first. Near the end of this XML example, the flow shows an On Error Continue configuration (``): Example: XML for Flow with On Error Continue Configuration ```xml ', 'application/xml') output application/xml --- myXml ]]> ``` The preceding example produces an error. Notice the following: 1. The variable `var myXml` in `` configures an empty `` tag as the payload. 2. The Logger beside the `` component returns `null` because it is set to log the value of the empty tag. 3. The `` component returns an error because the DataWeave condition `isEmpty(payload.prices)` returns `true`. 4. The Logger (``) within `` configures an error message to print to the console when an error occurs. The resulting error message looks something like this: ```text ERROR 2018-07-30 23:58:45,293 [[MuleRuntime].cpuLight.06: [flow_subflow].flow_subflowFlow.CPU_LITE @1b1529b2] [event: 0-2aba3280-948f-11e8-82d0-f45c898f2549] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: "An Error Occurred" ``` For details about these components, see [On-Error](https://docs.mulesoft.com/mule-runtime/4.4/on-error-scope-concept) error handlers. ## See Also - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.4/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.6 keywords: component, Mule 4 --- # Flow and Subflow Scopes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow and Subflow scopes are components for grouping together a sequence of other Core components and operations (provided by connectors and modules) to help automate integration processes. The Flow component is fundamental to a Mule app. Because all Mule apps must contain at least one flow, Anypoint Studio automatically provides the first Flow component in your Mule app. A Mule app can contain additional flows and subflows, as this example shows: ![Example of Flow with Subflows](/mulesoft/current/en-us/mule-runtime/4.6/_images/component-flow-subflow.png) Figure 1. Example: Flow with Subflows For a more in-depth discussion of uses, capabilities, and limits of flows and subflows, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.6/about-flows). Note that flows always function synchronously. If you need to achieve asynchronous patterns, such as Fire-and-Forget, you can use the [Async Scope](https://docs.mulesoft.com/mule-runtime/4.6/async-scope-reference) (``). ## Flow Configuration Flows are configurable. For example, you can set them to start or remained stopped when the Mule app starts, place limits on the allowed concurrency, or set up business events. You can also set up error handling for a component (see [Error Handling](#error_handling)).
FieldDescription

Name (name)

Name for the flow. Flows automatically receive an editable name that matches (or partially matches) the project name.

Initial State (initialState)

Values: Started, Stopped. These are Mule runtime settings for the flow. The default, Started (initialState="started", also called Empty in Studio), indicates that the flow is active when you start the app. So it can be triggered by an internal or external Mule event source within the flow (such as an HTTP listener or Scheduler), by a Flow Reference from another flow or subflow, or through a call to the lookup function.

If you set the initial state to Stopped (initialState="stopped"), activate the flow after deployment. For hybrid standalone and Anypoint Platform PCE deployments, use Runtime Manager to activate the flow. For CloudHub and Anypoint Runtime Fabric deployments, flow management through Runtime Manager isn’t supported. To activate the flow, redeploy the application or update the flow configuration to Started. When a flow is deployed with the initial state set to Stopped, the console output looks similar to this: Flow flow_component_ex has not been started (initial state = 'stopped').

For CloudHub deployments, avoid setting initialState="stopped" on flows that contain a Scheduler. The scheduler gets stuck in a permanent "Running" state, and you can’t manage it through Runtime Manager.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that a flow can process. If not set, the container thread pool determines the maximum number of threads the flow can use to optimize the performance when processing messages. While the flow is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the flow to process requests one at a time.

See Back-pressure for details about Mule’s behavior after the the maximum concurrency value is reached.

Business Events

Optional: Defaults to false. For Mule apps that you deploy to CloudHub, you can enable business events (XML example: tracking:enable-default-event="true") and add a Transaction ID (XML example: <tracking:transaction id=12345/>). See Business Events.

Metadata

As with many other components, you can set metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## Subflow Configuration Subflow scopes provide a way to edit the name of the subflow and to add metadata. Unlike flows, subflows lack a built-in mechanism for setting up error handling, though you can use error handling provided by the [Try Scope](https://docs.mulesoft.com/mule-runtime/4.6/try-scope-concept) within a subflow if you need to perform error handling.
FieldDescription

Name (name)

Name for the subflow. Subflows automatically receive an editable name that matches (or partially matches) the project name.

Metadata

As with many other components, you can set up metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## XML for Flows and Subflows This example shows the XML for a simple flow (``) that uses a Scheduler as a source to trigger execution of the flow every 10 seconds, and it connects to a subflow (``) through a Flow Ref (``) component. That subflow then connects to another subflow, also using a Flow Ref component. Note that when you configure components through the Studio UI, Studio automatically adds the XML to the Configuration XML for your Mule app. Example: XML for a Flow and Subflows ```xml 9.99 53 398.99 ', 'application/xml') output application/xml --- myXml ]]> { (key) : { dollars: value, localCurrency: value * conversionRate, index_plus_1: index + 1, timer : currentMilliseconds() } }]]> ``` The example produces the following output: Output ```json { "priceList": { "basic": { "dollars": "9.99", "localCurrency": 129.87, "index_plus_1": 1, "timer": 1533024312658 }, "premium": { "dollars": "53", "localCurrency": 689, "index_plus_1": 2, "timer": 1533024312659 }, "vip": { "dollars": "398.99", "localCurrency": 5186.87, "index_plus_1": 3, "timer": 1533024312659 } } } ``` ## Error Handling You can add [error handlers](https://docs.mulesoft.com/mule-runtime/4.6/error-handling) to the Flow components (but not to subflows). In Studio, you can simply expand the Error Handling area at the bottom of the Flow component and drag the error components into the flow. Note that this process automatically places the component into the Error Handler component, so there is no need to add the Error Handler component first. Near the end of this XML example, the flow shows an On Error Continue configuration (``): Example: XML for Flow with On Error Continue Configuration ```xml ', 'application/xml') output application/xml --- myXml ]]> ``` The preceding example produces an error. Notice the following: 1. The variable `var myXml` in `` configures an empty `` tag as the payload. 2. The Logger beside the `` component returns `null` because it is set to log the value of the empty tag. 3. The `` component returns an error because the DataWeave condition `isEmpty(payload.prices)` returns `true`. 4. The Logger (``) within `` configures an error message to print to the console when an error occurs. The resulting error message looks something like this: ```text ERROR 2018-07-30 23:58:45,293 [[MuleRuntime].cpuLight.06: [flow_subflow].flow_subflowFlow.CPU_LITE @1b1529b2] [event: 0-2aba3280-948f-11e8-82d0-f45c898f2549] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: "An Error Occurred" ``` For details about these components, see [On-Error](https://docs.mulesoft.com/mule-runtime/4.6/on-error-scope-concept) error handlers. ## See Also - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.6/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.9 keywords: component, Mule 4 --- # Flow and Subflow Scopes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow and Subflow scopes are components for grouping together a sequence of other Core components and operations (provided by connectors and modules) to help automate integration processes. The Flow component is fundamental to a Mule app. Because all Mule apps must contain at least one flow, Anypoint Studio automatically provides the first Flow component in your Mule app. A Mule app can contain additional flows and subflows, as this example shows: ![A flow including a scheduler, error handling, and multiple subflow references in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/component-flow-subflow.png) Figure 1. Example: Flow with Subflows For a more in-depth discussion of uses, capabilities, and limits of flows and subflows, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.9/about-flows). Note that flows always function synchronously. If you need to achieve asynchronous patterns, such as Fire-and-Forget, you can use the [Async Scope](https://docs.mulesoft.com/mule-runtime/4.9/async-scope-reference) (``). ## Flow Configuration Flows are configurable. For example, you can set them to start or remained stopped when the Mule app starts, place limits on the allowed concurrency, or set up business events. You can also set up error handling for a component (see [Error Handling](#error_handling)).
FieldDescription

Name (name)

Name for the flow. Flows automatically receive an editable name that matches (or partially matches) the project name.

Initial State (initialState)

Values: Started, Stopped. These are Mule runtime settings for the flow. The default, Started (initialState="started", also called Empty in Studio), indicates that the flow is active when you start the app. So it can be triggered by an internal or external Mule event source within the flow (such as an HTTP listener or Scheduler), by a Flow Reference from another flow or subflow, or through a call to the lookup function.

If you set the initial state to Stopped (initialState="stopped"), activate the flow after deployment. For hybrid standalone and Anypoint Platform PCE deployments, use Runtime Manager to activate the flow. For CloudHub and Anypoint Runtime Fabric deployments, flow management through Runtime Manager isn’t supported. To activate the flow, redeploy the application or update the flow configuration to Started. When a flow is deployed with the initial state set to Stopped, the console output looks similar to this: Flow flow_component_ex has not been started (initial state = 'stopped').

For CloudHub deployments, avoid setting initialState="stopped" on flows that contain a Scheduler. The scheduler gets stuck in a permanent "Running" state, and you can’t manage it through Runtime Manager.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that a flow can process. If not set, the container thread pool determines the maximum number of threads the flow can use to optimize the performance when processing messages. While the flow is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the flow to process requests one at a time.

See Back-pressure for details about Mule’s behavior after the maximum concurrency value is reached.

Business Events

Optional: Defaults to false. For Mule apps that you deploy to CloudHub, you can enable business events (XML example: tracking:enable-default-event="true") and add a Transaction ID (XML example: <tracking:transaction id=12345/>). See Business Events.

Metadata

As with many other components, you can set metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## Subflow Configuration Subflow scopes provide a way to edit the name of the subflow and to add metadata. Unlike flows, subflows lack a built-in mechanism for setting up error handling, though you can use error handling provided by the [Try Scope](https://docs.mulesoft.com/mule-runtime/4.9/try-scope-concept) within a subflow if you need to perform error handling.
FieldDescription

Name (name)

Name for the subflow. Subflows automatically receive an editable name that matches (or partially matches) the project name.

Metadata

As with many other components, you can set up metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## XML for Flows and Subflows This example shows the XML for a simple flow (``) that uses a Scheduler as a source to trigger execution of the flow every 10 seconds, and it connects to a subflow (``) through a Flow Ref (``) component. That subflow then connects to another subflow, also using a Flow Ref component. Note that when you configure components through the Studio UI, Studio automatically adds the XML to the Configuration XML for your Mule app. Example: XML for a Flow and Subflows ```xml 9.99 53 398.99 ', 'application/xml') output application/xml --- myXml ]]> { (key) : { dollars: value, localCurrency: value * conversionRate, index_plus_1: index + 1, timer : currentMilliseconds() } }]]> ``` The example produces the following output: Output ```json { "priceList": { "basic": { "dollars": "9.99", "localCurrency": 129.87, "index_plus_1": 1, "timer": 1533024312658 }, "premium": { "dollars": "53", "localCurrency": 689, "index_plus_1": 2, "timer": 1533024312659 }, "vip": { "dollars": "398.99", "localCurrency": 5186.87, "index_plus_1": 3, "timer": 1533024312659 } } } ``` ## Error Handling You can add [error handlers](https://docs.mulesoft.com/mule-runtime/4.9/error-handling) to the Flow components (but not to subflows). In Studio, you can simply expand the Error Handling area at the bottom of the Flow component and drag the error components into the flow. Note that this process automatically places the component into the Error Handler component, so there is no need to add the Error Handler component first. Near the end of this XML example, the flow shows an On Error Continue configuration (``): Example: XML for Flow with On Error Continue Configuration ```xml ', 'application/xml') output application/xml --- myXml ]]> ``` The preceding example produces an error. Notice the following: 1. The variable `var myXml` in `` configures an empty `` tag as the payload. 2. The Logger beside the `` component returns `null` because it is set to log the value of the empty tag. 3. The `` component returns an error because the DataWeave condition `isEmpty(payload.prices)` returns `true`. 4. The Logger (``) within `` configures an error message to print to the console when an error occurs. The resulting error message looks something like this: ```text ERROR 2018-07-30 23:58:45,293 [[MuleRuntime].cpuLight.06: [flow_subflow].flow_subflowFlow.CPU_LITE @1b1529b2] [event: 0-2aba3280-948f-11e8-82d0-f45c898f2549] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: "An Error Occurred" ``` For details about these components, see [On-Error](https://docs.mulesoft.com/mule-runtime/4.9/on-error-scope-concept) error handlers. ## See Also - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/4.9/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: component, Mule 4 --- # Flow and Subflow Scopes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow and Subflow scopes are components for grouping together a sequence of other Core components and operations (provided by connectors and modules) to help automate integration processes. The Flow component is fundamental to a Mule app. Because all Mule apps must contain at least one flow, Anypoint Studio automatically provides the first Flow component in your Mule app. A Mule app can contain additional flows and subflows, as this example shows: ![A flow including a scheduler, error handling, and multiple subflow references in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/component-flow-subflow.png) Figure 1. Example: Flow with Subflows For a more in-depth discussion of uses, capabilities, and limits of flows and subflows, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/latest/about-flows). Note that flows always function synchronously. If you need to achieve asynchronous patterns, such as Fire-and-Forget, you can use the [Async Scope](https://docs.mulesoft.com/mule-runtime/latest/async-scope-reference) (``). ## Flow Configuration Flows are configurable. For example, you can set them to start or remained stopped when the Mule app starts, place limits on the allowed concurrency, or set up business events. You can also set up error handling for a component (see [Error Handling](#error_handling)).
FieldDescription

Name (name)

Name for the flow. Flows automatically receive an editable name that matches (or partially matches) the project name.

Initial State (initialState)

Values: started, stopped. These are Mule runtime settings for the flow. The default, started (initialState="started", also called Empty in Studio), indicates that the flow is active when you start the app. So it can be triggered by an internal or external Mule event source within the flow (such as an HTTP listener or Scheduler), by a Flow Reference from another flow or subflow, or through a call to the lookup function.

If you set the initial state to stopped (initialState="stopped"), activate the flow after deployment. For hybrid standalone and Anypoint Platform PCE deployments, use Runtime Manager to activate the flow. For CloudHub and Anypoint Runtime Fabric deployments, flow management through Runtime Manager isn’t supported. To activate the flow, redeploy the application or update the flow configuration to started. When a flow is deployed with the initial state set to stopped, the console output looks similar to this: Flow flow_component_ex has not been started (initial state = 'stopped').

For CloudHub deployments, avoid setting initialState="stopped" on flows that contain a Scheduler. The scheduler gets stuck in a permanent "Running" state, and you can’t manage it through Runtime Manager.

Max Concurrency (maxConcurrency)

Optional. Sets the maximum number of concurrent messages that a flow can process. If not set, the container thread pool determines the maximum number of threads the flow can use to optimize the performance when processing messages. While the flow is processing the maximum number of concurrent messages, it cannot receive additional requests.

Set maxConcurrency to 1 to cause the flow to process requests one at a time.

See Back-pressure for details about Mule’s behavior after the maximum concurrency value is reached.

Business Events

Optional: Defaults to false. For Mule apps that you deploy to CloudHub, you can enable business events (XML example: tracking:enable-default-event="true") and add a Transaction ID (XML example: <tracking:transaction id=12345/>). See Business Events.

Metadata

As with many other components, you can set metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## Subflow Configuration Subflow scopes provide a way to edit the name of the subflow and to add metadata. Unlike flows, subflows lack a built-in mechanism for setting up error handling, though you can use error handling provided by the [Try Scope](https://docs.mulesoft.com/mule-runtime/latest/try-scope-concept) within a subflow if you need to perform error handling.
FieldDescription

Name (name)

Name for the subflow. Subflows automatically receive an editable name that matches (or partially matches) the project name.

Metadata

As with many other components, you can set up metadata for this component. For more on this topic, see the Studio document Metadata Editor.

## XML for Flows and Subflows This example shows the XML for a simple flow (``) that uses a Scheduler as a source to trigger execution of the flow every 10 seconds, and it connects to a subflow (``) through a Flow Ref (``) component. That subflow then connects to another subflow, also using a Flow Ref component. Note that when you configure components through the Studio UI, Studio automatically adds the XML to the Configuration XML for your Mule app. Example: XML for a Flow and Subflows ```xml 9.99 53 398.99 ', 'application/xml') output application/xml --- myXml ]]> { (key) : { dollars: value, localCurrency: value * conversionRate, index_plus_1: index + 1, timer : currentMilliseconds() } }]]> ``` The example produces the following output: Output ```json { "priceList": { "basic": { "dollars": "9.99", "localCurrency": 129.87, "index_plus_1": 1, "timer": 1533024312658 }, "premium": { "dollars": "53", "localCurrency": 689, "index_plus_1": 2, "timer": 1533024312659 }, "vip": { "dollars": "398.99", "localCurrency": 5186.87, "index_plus_1": 3, "timer": 1533024312659 } } } ``` ## Error Handling You can add [error handlers](https://docs.mulesoft.com/mule-runtime/latest/error-handling) to the Flow components (but not to subflows). In Studio, you can simply expand the Error Handling area at the bottom of the Flow component and drag the error components into the flow. Note that this process automatically places the component into the Error Handler component, so there is no need to add the Error Handler component first. Near the end of this XML example, the flow shows an On Error Continue configuration (``): Example: XML for Flow with On Error Continue Configuration ```xml ', 'application/xml') output application/xml --- myXml ]]> ``` The preceding example produces an error. Notice the following: 1. The variable `var myXml` in `` configures an empty `` tag as the payload. 2. The Logger beside the `` component returns `null` because it is set to log the value of the empty tag. 3. The `` component returns an error because the DataWeave condition `isEmpty(payload.prices)` returns `true`. 4. The Logger (``) within `` configures an error message to print to the console when an error occurs. The resulting error message looks something like this: ```text ERROR 2018-07-30 23:58:45,293 [[MuleRuntime].cpuLight.06: [flow_subflow].flow_subflowFlow.CPU_LITE @1b1529b2] [event: 0-2aba3280-948f-11e8-82d0-f45c898f2549] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: "An Error Occurred" ``` For details about these components, see [On-Error](https://docs.mulesoft.com/mule-runtime/latest/on-error-scope-concept) error handlers. ## See Also - [Back-Pressure and MaxConcurrency](https://docs.mulesoft.com/mule-runtime/latest/tuning-backpressure-maxconcurrency) --- product: Mule Runtime version: 4.11 keywords: email, connector, send, retrieve, manage, match, matcher, smtp, pop3, imap --- # Flow Reference Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow Reference routes the Mule event to another flow or subflow, executes all processors in the referenced flow, and then routes the event back within the same Mule application. The following diagram shows the order of processing when one flow references another: ![A main flow and its referenced subflow with multiple steps](/mulesoft/current/en-us/mule-runtime/4.11/_images/flowref-about-8b5d1.png) When the main flow is triggered, the Mule event travels through and executes the flow until the event reaches the Flow Reference. The event then travels through and executes the referenced flow from beginning to end, and then returns to the main flow. This process enables you to treat the entire referenced flow like a single component in your current flow. Flow Reference breaks the Mule application into discrete and reusable units. For example, a flow that lists files on a regular basis might reference another flow that processes the output of the List operation. Instead of appending all the processing steps to the flow that lists the files, you can append a Flow Reference that points to the processing flow. ## Configure a Flow Reference To configure a Flow Reference component, follow these steps in Anypoint Studio: 1. Drag the Flow Reference component from **Mule Palette** to the point in your flow where you want to create the call to the referenced flow: ![A flow showing main flow and secondary flow with variable and payload settings](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-flow-ref-create.png) 2. Open the Flow Reference properties and specify the flow you want to reference in **Flow name**: ![A configuration panel for a secondary flow showing settings for flow name and target](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-flow-ref-config.png) > [!WARNING] Use actual flow names to define the **Flow name** (`name`) attribute. Using dynamic > values (DataWeave expressions, variables) to specify the referenced flow negatively affects > performance. Also, MUnit tests and application analyzing tools cannot work on dynamic references. ## Enrich Content with a Flow Reference Target Variable Sometimes you need to execute a flow that uses the current payload and variables, but you want the Mule message to remain unchanged after such process. In this case, you can use a target variable to store the results of the referenced flow processing without changing the original message. You can store the result of a Flow Reference call in a target variable by configuring the following fields in your Flow Reference properties: - **Target**: Name of the variable that the Flow Reference creates to store the result of the processed message. - **Target Value**: An expression that evaluates against the operation’s output. The result of this evaluation is stored in the defined target variable. ### Considerations when Using a Target Variable Setting the `target` variable in a Flow Reference component causes the original message to remain unchanged. This means that any modification to the payload or to the variables that occur in the referenced flow revert after the referenced flow finishes executing its processors, returning the payload and variables to their original values. Alternatively, if you do not define a `target` variable, any modification that occurs to the payload or to the variables in the referenced flow persist after the referenced flow finishes its execution, changing the original value of the payload or variables. ## Error Handling Behavior in Referenced Flows When an error occurs inside a flow that is referenced by a Flow Reference component, the execution of the referenced flow stops and the process transfers to the referenced flow’s error handler. If the referenced flow does not have a configured error handler, the error is propagated to the flow that contains the Flow Reference call so this flow’s configured Error Handler component processes the error. Target variables are not set when an error occurs because the execution of the flow stops and does not end successfully. ## XML Example of Flow Reference The following XML code represents the project created in [Configure a Flow Reference](#configure-flow-ref), adding the target variable `flowReferenceVar,` which stores the result of the secondary flow called by the Flow Reference component. This variable is then used in the main flow by logging `vars.flowReferenceVar`: ```xml ``` The following log represents the output of the example application after its execution: INFO LoggerMessageProcessor: Payload = Original payload INFO LoggerMessageProcessor: myVar = 1 INFO LoggerMessageProcessor: flowReferenceVar = Modified payload If you remove `target="flowReferenceVar"` from the Flow Reference component, the application returns the following output: INFO LoggerMessageProcessor: Payload = Modified payload INFO LoggerMessageProcessor: myVar = 2 INFO LoggerMessageProcessor: flowReferenceVar = null The logs are shortened to improve readability. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-event) - [Enrich Data with Target Variables](https://docs.mulesoft.com/mule-runtime/4.11/target-variables) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.11/transaction-management#tx_scopes_routers) --- product: Mule Runtime version: 4.12 keywords: email, connector, send, retrieve, manage, match, matcher, smtp, pop3, imap --- # Flow Reference Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow Reference routes the Mule event to another flow or subflow, executes all processors in the referenced flow, and then routes the event back within the same Mule application. The following diagram shows the order of processing when one flow references another: ![A main flow and its referenced subflow with multiple steps](/mulesoft/current/en-us/mule-runtime/4.12/_images/flowref-about-8b5d1.png) When the main flow is triggered, the Mule event travels through and executes the flow until the event reaches the Flow Reference. The event then travels through and executes the referenced flow from beginning to end, and then returns to the main flow. This process enables you to treat the entire referenced flow like a single component in your current flow. Flow Reference breaks the Mule application into discrete and reusable units. For example, a flow that lists files on a regular basis might reference another flow that processes the output of the List operation. Instead of appending all the processing steps to the flow that lists the files, you can append a Flow Reference that points to the processing flow. ## Configure a Flow Reference To configure a Flow Reference component, follow these steps in Anypoint Studio: 1. Drag the Flow Reference component from **Mule Palette** to the point in your flow where you want to create the call to the referenced flow: ![A flow showing main flow and secondary flow with variable and payload settings](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-flow-ref-create.png) 2. Open the Flow Reference properties and specify the flow you want to reference in **Flow name**: ![A configuration panel for a secondary flow showing settings for flow name and target](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-flow-ref-config.png) > [!WARNING] Use actual flow names to define the **Flow name** (`name`) attribute. Using dynamic > values (DataWeave expressions, variables) to specify the referenced flow negatively affects > performance. Also, MUnit tests and application analyzing tools cannot work on dynamic references. ## Enrich Content with a Flow Reference Target Variable Sometimes you need to execute a flow that uses the current payload and variables, but you want the Mule message to remain unchanged after such process. In this case, you can use a target variable to store the results of the referenced flow processing without changing the original message. You can store the result of a Flow Reference call in a target variable by configuring the following fields in your Flow Reference properties: - **Target**: Name of the variable that the Flow Reference creates to store the result of the processed message. - **Target Value**: An expression that evaluates against the operation’s output. The result of this evaluation is stored in the defined target variable. ### Considerations when Using a Target Variable Setting the `target` variable in a Flow Reference component causes the original message to remain unchanged. This means that any modification to the payload or to the variables that occur in the referenced flow revert after the referenced flow finishes executing its processors, returning the payload and variables to their original values. Alternatively, if you do not define a `target` variable, any modification that occurs to the payload or to the variables in the referenced flow persist after the referenced flow finishes its execution, changing the original value of the payload or variables. ## Error Handling Behavior in Referenced Flows When an error occurs inside a flow that is referenced by a Flow Reference component, the execution of the referenced flow stops and the process transfers to the referenced flow’s error handler. If the referenced flow does not have a configured error handler, the error is propagated to the flow that contains the Flow Reference call so this flow’s configured Error Handler component processes the error. Target variables are not set when an error occurs because the execution of the flow stops and does not end successfully. ## XML Example of Flow Reference The following XML code represents the project created in [Configure a Flow Reference](#configure-flow-ref), adding the target variable `flowReferenceVar,` which stores the result of the secondary flow called by the Flow Reference component. This variable is then used in the main flow by logging `vars.flowReferenceVar`: ```xml ``` The following log represents the output of the example application after its execution: INFO LoggerMessageProcessor: Payload = Original payload INFO LoggerMessageProcessor: myVar = 1 INFO LoggerMessageProcessor: flowReferenceVar = Modified payload If you remove `target="flowReferenceVar"` from the Flow Reference component, the application returns the following output: INFO LoggerMessageProcessor: Payload = Modified payload INFO LoggerMessageProcessor: myVar = 2 INFO LoggerMessageProcessor: flowReferenceVar = null The logs are shortened to improve readability. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-event) - [Enrich Data with Target Variables](https://docs.mulesoft.com/mule-runtime/4.12/target-variables) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.12/transaction-management#tx_scopes_routers) --- product: Mule Runtime version: 4.3 keywords: email, connector, send, retrieve, manage, match, matcher, smtp, pop3, imap --- # Flow Reference Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow Reference routes the Mule event to another flow or subflow, executes all processors in the referenced flow, and then routes the event back within the same Mule application. The following diagram shows the order of processing when one flow references another: ![flowref about 8b5d1](/mulesoft/current/en-us/mule-runtime/4.3/_images/flowref-about-8b5d1.png) When the main flow is triggered, the Mule event travels through and executes the flow until the event reaches the Flow Reference. The event then travels through and executes the referenced flow from beginning to end, and then returns to the main flow. This process enables you to treat the entire referenced flow like a single component in your current flow. Flow Reference breaks the Mule application into discrete and reusable units. For example, a flow that lists files on a regular basis might reference another flow that processes the output of the List operation. Instead of appending all the processing steps to the flow that lists the files, you can append a Flow Reference that points to the processing flow. ## Configure a Flow Reference To configure a Flow Reference component, follow these steps in Anypoint Studio: 1. Drag the Flow Reference component from **Mule Palette** to the point in your flow where you want to create the call to the referenced flow: ![flow-ref-create](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-flow-ref-create.png) 2. Open the Flow Reference properties and specify the flow you want to reference in **Flow name**: ![flow-ref-config](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-flow-ref-config.png) > [!WARNING] Use actual flow names to define the **Flow name** (`name`) attribute. Using dynamic > values (DataWeave expressions, variables) to specify the referenced flow negatively affects > performance. Also, MUnit tests and application analyzing tools cannot work on dynamic references. ## Enrich Content with a Flow Reference Target Variable Sometimes you need to execute a flow that uses the current payload and variables, but you want the Mule message to remain unchanged after such process. In this case, you can use a target variable to store the results of the referenced flow processing without changing the original message. You can store the result of a Flow Reference call in a target variable by configuring the following fields in your Flow Reference properties: - **Target**: Name of the variable that the Flow Reference creates to store the result of the processed message. - **Target Value**: An expression that evaluates against the operation’s output. The result of this evaluation is stored in the defined target variable. ### Considerations when Using a Target Variable Setting the `target` variable in a Flow Reference component causes the original message to remain unchanged. This means that any modification to the payload or to the variables that occur in the referenced flow revert after the referenced flow finishes executing its processors, returning the payload and variables to their original values. Alternatively, if you do not define a `target` variable, any modification that occurs to the payload or to the variables in the referenced flow persist after the referenced flow finishes its execution, changing the original value of the payload or variables. ### XML Example of Flow Reference The following XML code represents the project created in [Configure a Flow Reference](#configure-flow-ref), adding the target variable `flowReferenceVar,` which stores the result of the secondary flow called by the Flow Reference component. This variable is then used in the main flow by logging `vars.flowReferenceVar`: ```xml ``` The following log represents the output of the example application after its execution: INFO LoggerMessageProcessor: Payload = Original payload INFO LoggerMessageProcessor: myVar = 1 INFO LoggerMessageProcessor: flowReferenceVar = Modified payload If you remove `target="flowReferenceVar"` from the Flow Reference component, the application returns the following output: INFO LoggerMessageProcessor: Payload = Modified payload INFO LoggerMessageProcessor: myVar = 2 INFO LoggerMessageProcessor: flowReferenceVar = null The logs are shortened to improve readability. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-event) - [Enrich Data with Target Variables](https://docs.mulesoft.com/mule-runtime/4.3/target-variables) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.3/transaction-management#tx_scopes_routers) --- product: Mule Runtime version: 4.4 keywords: email, connector, send, retrieve, manage, match, matcher, smtp, pop3, imap --- # Flow Reference Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow Reference routes the Mule event to another flow or subflow, executes all processors in the referenced flow, and then routes the event back within the same Mule application. The following diagram shows the order of processing when one flow references another: ![flowref about 8b5d1](/mulesoft/current/en-us/mule-runtime/4.4/_images/flowref-about-8b5d1.png) When the main flow is triggered, the Mule event travels through and executes the flow until the event reaches the Flow Reference. The event then travels through and executes the referenced flow from beginning to end, and then returns to the main flow. This process enables you to treat the entire referenced flow like a single component in your current flow. Flow Reference breaks the Mule application into discrete and reusable units. For example, a flow that lists files on a regular basis might reference another flow that processes the output of the List operation. Instead of appending all the processing steps to the flow that lists the files, you can append a Flow Reference that points to the processing flow. ## Configure a Flow Reference To configure a Flow Reference component, follow these steps in Anypoint Studio: 1. Drag the Flow Reference component from **Mule Palette** to the point in your flow where you want to create the call to the referenced flow: ![flow-ref-create](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-flow-ref-create.png) 2. Open the Flow Reference properties and specify the flow you want to reference in **Flow name**: ![flow-ref-config](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-flow-ref-config.png) > [!WARNING] Use actual flow names to define the **Flow name** (`name`) attribute. Using dynamic > values (DataWeave expressions, variables) to specify the referenced flow negatively affects > performance. Also, MUnit tests and application analyzing tools cannot work on dynamic references. ## Enrich Content with a Flow Reference Target Variable Sometimes you need to execute a flow that uses the current payload and variables, but you want the Mule message to remain unchanged after such process. In this case, you can use a target variable to store the results of the referenced flow processing without changing the original message. You can store the result of a Flow Reference call in a target variable by configuring the following fields in your Flow Reference properties: - **Target**: Name of the variable that the Flow Reference creates to store the result of the processed message. - **Target Value**: An expression that evaluates against the operation’s output. The result of this evaluation is stored in the defined target variable. ### Considerations when Using a Target Variable Setting the `target` variable in a Flow Reference component causes the original message to remain unchanged. This means that any modification to the payload or to the variables that occur in the referenced flow revert after the referenced flow finishes executing its processors, returning the payload and variables to their original values. Alternatively, if you do not define a `target` variable, any modification that occurs to the payload or to the variables in the referenced flow persist after the referenced flow finishes its execution, changing the original value of the payload or variables. ## Error Handling Behavior in Referenced Flows When an error occurs inside a flow that is referenced by a Flow Reference component, the execution of the referenced flow stops and the process transfers to the referenced flow’s error handler. If the referenced flow does not have a configured error handler, the error is propagated to the flow that contains the Flow Reference call so this flow’s configured Error Handler component processes the error. Target variables are not set when an error occurs because the execution of the flow stops and does not end successfully. ## XML Example of Flow Reference The following XML code represents the project created in [Configure a Flow Reference](#configure-flow-ref), adding the target variable `flowReferenceVar,` which stores the result of the secondary flow called by the Flow Reference component. This variable is then used in the main flow by logging `vars.flowReferenceVar`: ```xml ``` The following log represents the output of the example application after its execution: INFO LoggerMessageProcessor: Payload = Original payload INFO LoggerMessageProcessor: myVar = 1 INFO LoggerMessageProcessor: flowReferenceVar = Modified payload If you remove `target="flowReferenceVar"` from the Flow Reference component, the application returns the following output: INFO LoggerMessageProcessor: Payload = Modified payload INFO LoggerMessageProcessor: myVar = 2 INFO LoggerMessageProcessor: flowReferenceVar = null The logs are shortened to improve readability. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-event) - [Enrich Data with Target Variables](https://docs.mulesoft.com/mule-runtime/4.4/target-variables) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.4/transaction-management#tx_scopes_routers) --- product: Mule Runtime version: 4.6 keywords: email, connector, send, retrieve, manage, match, matcher, smtp, pop3, imap --- # Flow Reference Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow Reference routes the Mule event to another flow or subflow, executes all processors in the referenced flow, and then routes the event back within the same Mule application. The following diagram shows the order of processing when one flow references another: ![flowref about 8b5d1](/mulesoft/current/en-us/mule-runtime/4.6/_images/flowref-about-8b5d1.png) When the main flow is triggered, the Mule event travels through and executes the flow until the event reaches the Flow Reference. The event then travels through and executes the referenced flow from beginning to end, and then returns to the main flow. This process enables you to treat the entire referenced flow like a single component in your current flow. Flow Reference breaks the Mule application into discrete and reusable units. For example, a flow that lists files on a regular basis might reference another flow that processes the output of the List operation. Instead of appending all the processing steps to the flow that lists the files, you can append a Flow Reference that points to the processing flow. ## Configure a Flow Reference To configure a Flow Reference component, follow these steps in Anypoint Studio: 1. Drag the Flow Reference component from **Mule Palette** to the point in your flow where you want to create the call to the referenced flow: ![flow-ref-create](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-flow-ref-create.png) 2. Open the Flow Reference properties and specify the flow you want to reference in **Flow name**: ![flow-ref-config](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-flow-ref-config.png) > [!WARNING] Use actual flow names to define the **Flow name** (`name`) attribute. Using dynamic > values (DataWeave expressions, variables) to specify the referenced flow negatively affects > performance. Also, MUnit tests and application analyzing tools cannot work on dynamic references. ## Enrich Content with a Flow Reference Target Variable Sometimes you need to execute a flow that uses the current payload and variables, but you want the Mule message to remain unchanged after such process. In this case, you can use a target variable to store the results of the referenced flow processing without changing the original message. You can store the result of a Flow Reference call in a target variable by configuring the following fields in your Flow Reference properties: - **Target**: Name of the variable that the Flow Reference creates to store the result of the processed message. - **Target Value**: An expression that evaluates against the operation’s output. The result of this evaluation is stored in the defined target variable. ### Considerations when Using a Target Variable Setting the `target` variable in a Flow Reference component causes the original message to remain unchanged. This means that any modification to the payload or to the variables that occur in the referenced flow revert after the referenced flow finishes executing its processors, returning the payload and variables to their original values. Alternatively, if you do not define a `target` variable, any modification that occurs to the payload or to the variables in the referenced flow persist after the referenced flow finishes its execution, changing the original value of the payload or variables. ## Error Handling Behavior in Referenced Flows When an error occurs inside a flow that is referenced by a Flow Reference component, the execution of the referenced flow stops and the process transfers to the referenced flow’s error handler. If the referenced flow does not have a configured error handler, the error is propagated to the flow that contains the Flow Reference call so this flow’s configured Error Handler component processes the error. Target variables are not set when an error occurs because the execution of the flow stops and does not end successfully. ## XML Example of Flow Reference The following XML code represents the project created in [Configure a Flow Reference](#configure-flow-ref), adding the target variable `flowReferenceVar,` which stores the result of the secondary flow called by the Flow Reference component. This variable is then used in the main flow by logging `vars.flowReferenceVar`: ```xml ``` The following log represents the output of the example application after its execution: INFO LoggerMessageProcessor: Payload = Original payload INFO LoggerMessageProcessor: myVar = 1 INFO LoggerMessageProcessor: flowReferenceVar = Modified payload If you remove `target="flowReferenceVar"` from the Flow Reference component, the application returns the following output: INFO LoggerMessageProcessor: Payload = Modified payload INFO LoggerMessageProcessor: myVar = 2 INFO LoggerMessageProcessor: flowReferenceVar = null The logs are shortened to improve readability. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-event) - [Enrich Data with Target Variables](https://docs.mulesoft.com/mule-runtime/4.6/target-variables) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.6/transaction-management#tx_scopes_routers) --- product: Mule Runtime version: 4.9 keywords: email, connector, send, retrieve, manage, match, matcher, smtp, pop3, imap --- # Flow Reference Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow Reference routes the Mule event to another flow or subflow, executes all processors in the referenced flow, and then routes the event back within the same Mule application. The following diagram shows the order of processing when one flow references another: ![A main flow and its referenced subflow with multiple steps](/mulesoft/current/en-us/mule-runtime/4.9/_images/flowref-about-8b5d1.png) When the main flow is triggered, the Mule event travels through and executes the flow until the event reaches the Flow Reference. The event then travels through and executes the referenced flow from beginning to end, and then returns to the main flow. This process enables you to treat the entire referenced flow like a single component in your current flow. Flow Reference breaks the Mule application into discrete and reusable units. For example, a flow that lists files on a regular basis might reference another flow that processes the output of the List operation. Instead of appending all the processing steps to the flow that lists the files, you can append a Flow Reference that points to the processing flow. ## Configure a Flow Reference To configure a Flow Reference component, follow these steps in Anypoint Studio: 1. Drag the Flow Reference component from **Mule Palette** to the point in your flow where you want to create the call to the referenced flow: ![A flow showing main flow and secondary flow with variable and payload settings](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-flow-ref-create.png) 2. Open the Flow Reference properties and specify the flow you want to reference in **Flow name**: ![A configuration panel for a secondary flow showing settings for flow name and target](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-flow-ref-config.png) > [!WARNING] Use actual flow names to define the **Flow name** (`name`) attribute. Using dynamic > values (DataWeave expressions, variables) to specify the referenced flow negatively affects > performance. Also, MUnit tests and application analyzing tools cannot work on dynamic references. ## Enrich Content with a Flow Reference Target Variable Sometimes you need to execute a flow that uses the current payload and variables, but you want the Mule message to remain unchanged after such process. In this case, you can use a target variable to store the results of the referenced flow processing without changing the original message. You can store the result of a Flow Reference call in a target variable by configuring the following fields in your Flow Reference properties: - **Target**: Name of the variable that the Flow Reference creates to store the result of the processed message. - **Target Value**: An expression that evaluates against the operation’s output. The result of this evaluation is stored in the defined target variable. ### Considerations when Using a Target Variable Setting the `target` variable in a Flow Reference component causes the original message to remain unchanged. This means that any modification to the payload or to the variables that occur in the referenced flow revert after the referenced flow finishes executing its processors, returning the payload and variables to their original values. Alternatively, if you do not define a `target` variable, any modification that occurs to the payload or to the variables in the referenced flow persist after the referenced flow finishes its execution, changing the original value of the payload or variables. ## Error Handling Behavior in Referenced Flows When an error occurs inside a flow that is referenced by a Flow Reference component, the execution of the referenced flow stops and the process transfers to the referenced flow’s error handler. If the referenced flow does not have a configured error handler, the error is propagated to the flow that contains the Flow Reference call so this flow’s configured Error Handler component processes the error. Target variables are not set when an error occurs because the execution of the flow stops and does not end successfully. ## XML Example of Flow Reference The following XML code represents the project created in [Configure a Flow Reference](#configure-flow-ref), adding the target variable `flowReferenceVar,` which stores the result of the secondary flow called by the Flow Reference component. This variable is then used in the main flow by logging `vars.flowReferenceVar`: ```xml ``` The following log represents the output of the example application after its execution: INFO LoggerMessageProcessor: Payload = Original payload INFO LoggerMessageProcessor: myVar = 1 INFO LoggerMessageProcessor: flowReferenceVar = Modified payload If you remove `target="flowReferenceVar"` from the Flow Reference component, the application returns the following output: INFO LoggerMessageProcessor: Payload = Modified payload INFO LoggerMessageProcessor: myVar = 2 INFO LoggerMessageProcessor: flowReferenceVar = null The logs are shortened to improve readability. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-event) - [Enrich Data with Target Variables](https://docs.mulesoft.com/mule-runtime/4.9/target-variables) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/4.9/transaction-management#tx_scopes_routers) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: email, connector, send, retrieve, manage, match, matcher, smtp, pop3, imap --- # Flow Reference Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Flow Reference routes the Mule event to another flow or subflow, executes all processors in the referenced flow, and then routes the event back within the same Mule application. The following diagram shows the order of processing when one flow references another: ![A main flow and its referenced subflow with multiple steps](/mulesoft/current/en-us/mule-runtime/latest/_images/flowref-about-8b5d1.png) When the main flow is triggered, the Mule event travels through and executes the flow until the event reaches the Flow Reference. The event then travels through and executes the referenced flow from beginning to end, and then returns to the main flow. This process enables you to treat the entire referenced flow like a single component in your current flow. Flow Reference breaks the Mule application into discrete and reusable units. For example, a flow that lists files on a regular basis might reference another flow that processes the output of the List operation. Instead of appending all the processing steps to the flow that lists the files, you can append a Flow Reference that points to the processing flow. ## Configure a Flow Reference To configure a Flow Reference component, follow these steps in Anypoint Studio: 1. Drag the Flow Reference component from **Mule Palette** to the point in your flow where you want to create the call to the referenced flow: ![A flow showing main flow and secondary flow with variable and payload settings](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-flow-ref-create.png) 2. Open the Flow Reference properties and specify the flow you want to reference in **Flow name**: ![A configuration panel for a secondary flow showing settings for flow name and target](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-flow-ref-config.png) > [!WARNING] Use actual flow names to define the **Flow name** (`name`) attribute. Using dynamic > values (DataWeave expressions, variables) to specify the referenced flow negatively affects > performance. Also, MUnit tests and application analyzing tools cannot work on dynamic references. ## Enrich Content with a Flow Reference Target Variable Sometimes you need to execute a flow that uses the current payload and variables, but you want the Mule message to remain unchanged after such process. In this case, you can use a target variable to store the results of the referenced flow processing without changing the original message. You can store the result of a Flow Reference call in a target variable by configuring the following fields in your Flow Reference properties: - **Target**: Name of the variable that the Flow Reference creates to store the result of the processed message. - **Target Value**: An expression that evaluates against the operation’s output. The result of this evaluation is stored in the defined target variable. ### Considerations when Using a Target Variable Setting the `target` variable in a Flow Reference component causes the original message to remain unchanged. This means that any modification to the payload or to the variables that occur in the referenced flow revert after the referenced flow finishes executing its processors, returning the payload and variables to their original values. Alternatively, if you do not define a `target` variable, any modification that occurs to the payload or to the variables in the referenced flow persist after the referenced flow finishes its execution, changing the original value of the payload or variables. ## Error Handling Behavior in Referenced Flows When an error occurs inside a flow that is referenced by a Flow Reference component, the execution of the referenced flow stops and the process transfers to the referenced flow’s error handler. If the referenced flow does not have a configured error handler, the error is propagated to the flow that contains the Flow Reference call so this flow’s configured Error Handler component processes the error. Target variables are not set when an error occurs because the execution of the flow stops and does not end successfully. ## XML Example of Flow Reference The following XML code represents the project created in [Configure a Flow Reference](#configure-flow-ref), adding the target variable `flowReferenceVar,` which stores the result of the secondary flow called by the Flow Reference component. This variable is then used in the main flow by logging `vars.flowReferenceVar`: ```xml ``` The following log represents the output of the example application after its execution: INFO LoggerMessageProcessor: Payload = Original payload INFO LoggerMessageProcessor: myVar = 1 INFO LoggerMessageProcessor: flowReferenceVar = Modified payload If you remove `target="flowReferenceVar"` from the Flow Reference component, the application returns the following output: INFO LoggerMessageProcessor: Payload = Modified payload INFO LoggerMessageProcessor: myVar = 2 INFO LoggerMessageProcessor: flowReferenceVar = null The logs are shortened to improve readability. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/latest/about-mule-event) - [Enrich Data with Target Variables](https://docs.mulesoft.com/mule-runtime/latest/target-variables) - [How Transactions Affect Scopes and Routers](https://docs.mulesoft.com/mule-runtime/latest/transaction-management#tx_scopes_routers) --- product: Mule Runtime version: 4.11 keywords: anypoint studio, studio, mule esb, orchestration --- # Flows and Subflows > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule apps process messages and other parts of Mule events through Mule components, connectors, and modules that are set up within the scope of Flow and Subflow components within an app. An app can consist of a single flow, or it can break up processing into discrete flows and subflows that you add to the app and connect together. Mule apps in production environments typically use multiple flows and subflows to divide the app into functional modules or for [error handling](#error_handling) purposes. For example, one flow might receive a record and transform data into a given format that another flow processes in some special way. You can connect and trigger their execution with [Flow Reference](https://docs.mulesoft.com/mule-runtime/4.11/flowref-about) components or by using the DataWeave `lookup` function within expressions and transformations. The function passes the current event to another flow for further event processing. You can think of a Flow Reference as a function call that accepts an event as input and then returns the modified event. ## Using Flows Flows can have Mule Sources (such as an HTTP listener receiving a request) that trigger the execution of a flow. For cases where you do not want a source to start a flow right away, you can configure your flow as initially stopped and start it later through [Runtime Manager](https://docs.mulesoft.com/runtime-manager/flow-management). Like functions or methods in other programming languages, it is a best practice to focus your flows on specific (perhaps reusable) activities, such as receiving an API request from a web client, processing the event, then returning an appropriate response. If the event processing gets complicated, or must call out to other services, you might factor out that behavior into other flows. ## Using Subflows A _subflow_ is a scope that enables you to group event processors in a manner similar to that of a flow, but with certain differences and limitations: - Subflows do not have Mule event sources. - Subflows do not have an error handling scope. - During design, subflows work as macros that replace the Flow Reference components that call them. When you build the application, all Flow Reference components that call a subflow are replaced by the contents of the referenced subflow. - Referencing subflows results in better performance than referencing a flow. ### Limitations Because the contents of a subflow replace each Flow Reference component that references that subflow, several instances of the event processors inside that subflow exist in the application at runtime. This behavior can cause issues with event processors that depend on unique IDs or instances to execute, such as batch processors. For example, configuring a batch job inside a subflow causes the application to fail during deployment if the subflow is referenced from more than one Flow Reference component. The application fails to deploy because multiple instances of a batch job with the same job instance ID exist, which is not allowed. ## Error Handling Each flow (but not subflow) can have its own error handling. One reason for calling a flow through a Flow Reference component is to isolate the error handling to different contexts. For example, a parent flow that receives web client requests might define HTTP-related error handling. If the parent flow then calls a JMS queue for further processing, you can put the JMS event processors in a separate child flow and call that flow with a Flow Reference component. This child flow can then define its own JMS-related error handling. This practice is similar to the way you handle or propagate errors in other programming languages, like Java. Like a flow or subflow, a [Try scope](https://docs.mulesoft.com/mule-runtime/4.11/try-scope-concept) also groups together a sequence of event processors with its own error handling. You can place a Try scope inside a flow or subflow to isolate error handling inside a flow without the need to create a separate flow or subflow. The trade-off is that error handling through a Try scope occurs inline inside the flow, which makes it harder to reuse between other flows or subflows. In both cases, calling a flow or including a Try scope isolates the error handling, similar to the use of Try-Catch blocks inside Java code. For example, placing JMS queue event processing (described above) in its own flow or within a Try scope results in exactly the same error handling behavior, but the event processors in a Try scope cannot be called from another flow. ## Branching Event Processing Some scopes are available for a flow to branch event processing into separate threads and to allow asynchronous processing of the event at a specific point in the flow, for example, the [Scatter-Gather](https://docs.mulesoft.com/mule-runtime/4.11/scatter-gather-concept) and [Async](https://docs.mulesoft.com/mule-runtime/4.11/async-scope-reference) scopes. A [Choice](https://docs.mulesoft.com/mule-runtime/4.11/choice-router-concept) router enables you to change the downstream sequence of event processors based on some condition. ## See Also - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/4.11/flow-component) - [Mule Runtime](https://docs.mulesoft.com/mule-runtime/4.11/) --- product: Mule Runtime version: 4.12 keywords: anypoint studio, studio, mule esb, orchestration --- # Flows and Subflows > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule apps process messages and other parts of Mule events through Mule components, connectors, and modules that are set up within the scope of Flow and Subflow components within an app. An app can consist of a single flow, or it can break up processing into discrete flows and subflows that you add to the app and connect together. Mule apps in production environments typically use multiple flows and subflows to divide the app into functional modules or for [error handling](#error_handling) purposes. For example, one flow might receive a record and transform data into a given format that another flow processes in some special way. You can connect and trigger their execution with [Flow Reference](https://docs.mulesoft.com/mule-runtime/4.12/flowref-about) components or by using the DataWeave `lookup` function within expressions and transformations. The function passes the current event to another flow for further event processing. You can think of a Flow Reference as a function call that accepts an event as input and then returns the modified event. ## Using Flows Flows can have Mule Sources (such as an HTTP listener receiving a request) that trigger the execution of a flow. For cases where you do not want a source to start a flow right away, you can configure your flow as initially stopped and start it later through [Runtime Manager](https://docs.mulesoft.com/runtime-manager/flow-management). Like functions or methods in other programming languages, it is a best practice to focus your flows on specific (perhaps reusable) activities, such as receiving an API request from a web client, processing the event, then returning an appropriate response. If the event processing gets complicated, or must call out to other services, you might factor out that behavior into other flows. ## Using Subflows A _subflow_ is a scope that enables you to group event processors in a manner similar to that of a flow, but with certain differences and limitations: - Subflows do not have Mule event sources. - Subflows do not have an error handling scope. - During design, subflows work as macros that replace the Flow Reference components that call them. When you build the application, all Flow Reference components that call a subflow are replaced by the contents of the referenced subflow. - Referencing subflows results in better performance than referencing a flow. ### Limitations Because the contents of a subflow replace each Flow Reference component that references that subflow, several instances of the event processors inside that subflow exist in the application at runtime. This behavior can cause issues with event processors that depend on unique IDs or instances to execute, such as batch processors. For example, configuring a batch job inside a subflow causes the application to fail during deployment if the subflow is referenced from more than one Flow Reference component. The application fails to deploy because multiple instances of a batch job with the same job instance ID exist, which is not allowed. ## Error Handling Each flow (but not subflow) can have its own error handling. One reason for calling a flow through a Flow Reference component is to isolate the error handling to different contexts. For example, a parent flow that receives web client requests might define HTTP-related error handling. If the parent flow then calls a JMS queue for further processing, you can put the JMS event processors in a separate child flow and call that flow with a Flow Reference component. This child flow can then define its own JMS-related error handling. This practice is similar to the way you handle or propagate errors in other programming languages, like Java. Like a flow or subflow, a [Try scope](https://docs.mulesoft.com/mule-runtime/4.12/try-scope-concept) also groups together a sequence of event processors with its own error handling. You can place a Try scope inside a flow or subflow to isolate error handling inside a flow without the need to create a separate flow or subflow. The trade-off is that error handling through a Try scope occurs inline inside the flow, which makes it harder to reuse between other flows or subflows. In both cases, calling a flow or including a Try scope isolates the error handling, similar to the use of Try-Catch blocks inside Java code. For example, placing JMS queue event processing (described above) in its own flow or within a Try scope results in exactly the same error handling behavior, but the event processors in a Try scope cannot be called from another flow. ## Branching Event Processing Some scopes are available for a flow to branch event processing into separate threads and to allow asynchronous processing of the event at a specific point in the flow, for example, the [Scatter-Gather](https://docs.mulesoft.com/mule-runtime/4.12/scatter-gather-concept) and [Async](https://docs.mulesoft.com/mule-runtime/4.12/async-scope-reference) scopes. A [Choice](https://docs.mulesoft.com/mule-runtime/4.12/choice-router-concept) router enables you to change the downstream sequence of event processors based on some condition. ## See Also - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/4.12/flow-component) - [Mule Runtime](https://docs.mulesoft.com/mule-runtime/4.12/) --- product: Mule Runtime version: 4.3 keywords: anypoint studio, studio, mule esb, orchestration --- # Flows and Subflows > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule apps process messages and other parts of Mule events through Mule components, connectors, and modules that are set up within the scope of Flow and Subflow components within an app. An app can consist of a single flow, or it can break up processing into discrete flows and subflows that you add to the app and connect together. Mule apps in production environments typically use multiple flows and subflows to divide the app into functional modules or for [error handling](#error_handling) purposes. For example, one flow might receive a record and transform data into a given format that another flow processes in some special way. You can connect and trigger their execution with [Flow Reference](https://docs.mulesoft.com/mule-runtime/4.3/flowref-about) components or by using the DataWeave `lookup` function within expressions and transformations. The function passes the current event to another flow for further event processing. You can think of a Flow Reference as a function call that accepts an event as input and then returns the modified event. ## Using Flows Flows can have Mule Sources (such as an HTTP listener receiving a request) that trigger the execution of a flow. For cases where you do not want a source to start a flow right away, you can configure your flow as initially stopped and start it later through [Runtime Manager](https://docs.mulesoft.com/runtime-manager/flow-management). Like functions or methods in other programming languages, it is a best practice to focus your flows on specific (perhaps reusable) activities, such as receiving an API request from a web client, processing the event, then returning an appropriate response. If the event processing gets complicated, or must call out to other services, you might factor out that behavior into other flows. ## Using Subflows A _subflow_ is a scope that enables you to group event processors in a manner similar to that of a flow, but with certain differences and limitations: - Subflows do not have event sources. - Subflows do not have an error handling scope. - During design, subflows work as macros that replace the Flow Reference components that call them. When you build the application, all Flow Reference components that call a subflow are replaced by the contents of the referenced subflow. - Referencing subflows results in better performance than referencing a flow. ### Limitations Because the contents of a subflow replace each Flow Reference component that references that subflow, several instances of the event processors inside that subflow exist in the application at runtime. This behavior can cause issues with event processors that depend on unique IDs or instances to execute, such as batch processors. For example, configuring a batch job inside a subflow causes the application to fail during deployment if the subflow is referenced from more than one Flow Reference component. The application fails to deploy because multiple instances of a batch job with the same job instance ID exist, which is not allowed. ## Error Handling Each flow (but not subflow) can have its own error handling. One reason for calling a flow through a Flow Reference component is to isolate the error handling to different contexts. For example, a parent flow that receives web client requests might define HTTP-related error handling. If the parent flow then calls a JMS queue for further processing, you can put the JMS event processors in a separate child flow and call that flow with a Flow Reference component. This child flow can then define its own JMS-related error handling. This practice is similar to the way you handle or propagate errors in other programming languages, like Java. Like a flow or subflow, a [Try scope](https://docs.mulesoft.com/mule-runtime/4.3/try-scope-concept) also groups together a sequence of event processors with its own error handling. You can place a Try scope inside a flow or subflow to isolate error handling inside a flow without the need to create a separate flow or subflow. The trade-off is that error handling through a Try scope occurs inline inside the flow, which makes it harder to reuse between other flows or subflows. In both cases, calling a flow or including a Try scope isolates the error handling, similar to the use of Try-Catch blocks inside Java code. For example, placing JMS queue event processing (described above) in its own flow or within a Try scope results in exactly the same error handling behavior, but the event processors in a Try scope cannot be called from another flow. ## Branching Event Processing Some scopes are available for a flow to branch event processing into separate threads and to allow asynchronous processing of the event at a specific point in the flow, for example, the [Scatter-Gather](https://docs.mulesoft.com/mule-runtime/4.3/scatter-gather-concept) and [Async](https://docs.mulesoft.com/mule-runtime/4.3/async-scope-reference) scopes. A [Choice](https://docs.mulesoft.com/mule-runtime/4.3/choice-router-concept) router enables you to change the downstream sequence of event processors based on some condition. ## See Also - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/4.3/flow-component) - [Mule Runtime](https://docs.mulesoft.com/mule-runtime/4.3/) --- product: Mule Runtime version: 4.4 keywords: anypoint studio, studio, mule esb, orchestration --- # Flows and Subflows > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule apps process messages and other parts of Mule events through Mule components, connectors, and modules that are set up within the scope of Flow and Subflow components within an app. An app can consist of a single flow, or it can break up processing into discrete flows and subflows that you add to the app and connect together. Mule apps in production environments typically use multiple flows and subflows to divide the app into functional modules or for [error handling](#error_handling) purposes. For example, one flow might receive a record and transform data into a given format that another flow processes in some special way. You can connect and trigger their execution with [Flow Reference](https://docs.mulesoft.com/mule-runtime/4.4/flowref-about) components or by using the DataWeave `lookup` function within expressions and transformations. The function passes the current event to another flow for further event processing. You can think of a Flow Reference as a function call that accepts an event as input and then returns the modified event. ## Using Flows Flows can have Mule Sources (such as an HTTP listener receiving a request) that trigger the execution of a flow. For cases where you do not want a source to start a flow right away, you can configure your flow as initially stopped and start it later through [Runtime Manager](https://docs.mulesoft.com/runtime-manager/flow-management). Like functions or methods in other programming languages, it is a best practice to focus your flows on specific (perhaps reusable) activities, such as receiving an API request from a web client, processing the event, then returning an appropriate response. If the event processing gets complicated, or must call out to other services, you might factor out that behavior into other flows. ## Using Subflows A _subflow_ is a scope that enables you to group event processors in a manner similar to that of a flow, but with certain differences and limitations: - Subflows do not have Mule event sources. - Subflows do not have an error handling scope. - During design, subflows work as macros that replace the Flow Reference components that call them. When you build the application, all Flow Reference components that call a subflow are replaced by the contents of the referenced subflow. - Referencing subflows results in better performance than referencing a flow. ### Limitations Because the contents of a subflow replace each Flow Reference component that references that subflow, several instances of the event processors inside that subflow exist in the application at runtime. This behavior can cause issues with event processors that depend on unique IDs or instances to execute, such as batch processors. For example, configuring a batch job inside a subflow causes the application to fail during deployment if the subflow is referenced from more than one Flow Reference component. The application fails to deploy because multiple instances of a batch job with the same job instance ID exist, which is not allowed. ## Error Handling Each flow (but not subflow) can have its own error handling. One reason for calling a flow through a Flow Reference component is to isolate the error handling to different contexts. For example, a parent flow that receives web client requests might define HTTP-related error handling. If the parent flow then calls a JMS queue for further processing, you can put the JMS event processors in a separate child flow and call that flow with a Flow Reference component. This child flow can then define its own JMS-related error handling. This practice is similar to the way you handle or propagate errors in other programming languages, like Java. Like a flow or subflow, a [Try scope](https://docs.mulesoft.com/mule-runtime/4.4/try-scope-concept) also groups together a sequence of event processors with its own error handling. You can place a Try scope inside a flow or subflow to isolate error handling inside a flow without the need to create a separate flow or subflow. The trade-off is that error handling through a Try scope occurs inline inside the flow, which makes it harder to reuse between other flows or subflows. In both cases, calling a flow or including a Try scope isolates the error handling, similar to the use of Try-Catch blocks inside Java code. For example, placing JMS queue event processing (described above) in its own flow or within a Try scope results in exactly the same error handling behavior, but the event processors in a Try scope cannot be called from another flow. ## Branching Event Processing Some scopes are available for a flow to branch event processing into separate threads and to allow asynchronous processing of the event at a specific point in the flow, for example, the [Scatter-Gather](https://docs.mulesoft.com/mule-runtime/4.4/scatter-gather-concept) and [Async](https://docs.mulesoft.com/mule-runtime/4.4/async-scope-reference) scopes. A [Choice](https://docs.mulesoft.com/mule-runtime/4.4/choice-router-concept) router enables you to change the downstream sequence of event processors based on some condition. ## See Also - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/4.4/flow-component) - [Mule Runtime](https://docs.mulesoft.com/mule-runtime/4.4/) --- product: Mule Runtime version: 4.6 keywords: anypoint studio, studio, mule esb, orchestration --- # Flows and Subflows > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule apps process messages and other parts of Mule events through Mule components, connectors, and modules that are set up within the scope of Flow and Subflow components within an app. An app can consist of a single flow, or it can break up processing into discrete flows and subflows that you add to the app and connect together. Mule apps in production environments typically use multiple flows and subflows to divide the app into functional modules or for [error handling](#error_handling) purposes. For example, one flow might receive a record and transform data into a given format that another flow processes in some special way. You can connect and trigger their execution with [Flow Reference](https://docs.mulesoft.com/mule-runtime/4.6/flowref-about) components or by using the DataWeave `lookup` function within expressions and transformations. The function passes the current event to another flow for further event processing. You can think of a Flow Reference as a function call that accepts an event as input and then returns the modified event. ## Using Flows Flows can have Mule Sources (such as an HTTP listener receiving a request) that trigger the execution of a flow. For cases where you do not want a source to start a flow right away, you can configure your flow as initially stopped and start it later through [Runtime Manager](https://docs.mulesoft.com/runtime-manager/flow-management). Like functions or methods in other programming languages, it is a best practice to focus your flows on specific (perhaps reusable) activities, such as receiving an API request from a web client, processing the event, then returning an appropriate response. If the event processing gets complicated, or must call out to other services, you might factor out that behavior into other flows. ## Using Subflows A _subflow_ is a scope that enables you to group event processors in a manner similar to that of a flow, but with certain differences and limitations: - Subflows do not have Mule event sources. - Subflows do not have an error handling scope. - During design, subflows work as macros that replace the Flow Reference components that call them. When you build the application, all Flow Reference components that call a subflow are replaced by the contents of the referenced subflow. - Referencing subflows results in better performance than referencing a flow. ### Limitations Because the contents of a subflow replace each Flow Reference component that references that subflow, several instances of the event processors inside that subflow exist in the application at runtime. This behavior can cause issues with event processors that depend on unique IDs or instances to execute, such as batch processors. For example, configuring a batch job inside a subflow causes the application to fail during deployment if the subflow is referenced from more than one Flow Reference component. The application fails to deploy because multiple instances of a batch job with the same job instance ID exist, which is not allowed. ## Error Handling Each flow (but not subflow) can have its own error handling. One reason for calling a flow through a Flow Reference component is to isolate the error handling to different contexts. For example, a parent flow that receives web client requests might define HTTP-related error handling. If the parent flow then calls a JMS queue for further processing, you can put the JMS event processors in a separate child flow and call that flow with a Flow Reference component. This child flow can then define its own JMS-related error handling. This practice is similar to the way you handle or propagate errors in other programming languages, like Java. Like a flow or subflow, a [Try scope](https://docs.mulesoft.com/mule-runtime/4.6/try-scope-concept) also groups together a sequence of event processors with its own error handling. You can place a Try scope inside a flow or subflow to isolate error handling inside a flow without the need to create a separate flow or subflow. The trade-off is that error handling through a Try scope occurs inline inside the flow, which makes it harder to reuse between other flows or subflows. In both cases, calling a flow or including a Try scope isolates the error handling, similar to the use of Try-Catch blocks inside Java code. For example, placing JMS queue event processing (described above) in its own flow or within a Try scope results in exactly the same error handling behavior, but the event processors in a Try scope cannot be called from another flow. ## Branching Event Processing Some scopes are available for a flow to branch event processing into separate threads and to allow asynchronous processing of the event at a specific point in the flow, for example, the [Scatter-Gather](https://docs.mulesoft.com/mule-runtime/4.6/scatter-gather-concept) and [Async](https://docs.mulesoft.com/mule-runtime/4.6/async-scope-reference) scopes. A [Choice](https://docs.mulesoft.com/mule-runtime/4.6/choice-router-concept) router enables you to change the downstream sequence of event processors based on some condition. ## See Also - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/4.6/flow-component) - [Mule Runtime](https://docs.mulesoft.com/mule-runtime/4.6/) --- product: Mule Runtime version: 4.9 keywords: anypoint studio, studio, mule esb, orchestration --- # Flows and Subflows > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule apps process messages and other parts of Mule events through Mule components, connectors, and modules that are set up within the scope of Flow and Subflow components within an app. An app can consist of a single flow, or it can break up processing into discrete flows and subflows that you add to the app and connect together. Mule apps in production environments typically use multiple flows and subflows to divide the app into functional modules or for [error handling](#error_handling) purposes. For example, one flow might receive a record and transform data into a given format that another flow processes in some special way. You can connect and trigger their execution with [Flow Reference](https://docs.mulesoft.com/mule-runtime/4.9/flowref-about) components or by using the DataWeave `lookup` function within expressions and transformations. The function passes the current event to another flow for further event processing. You can think of a Flow Reference as a function call that accepts an event as input and then returns the modified event. ## Using Flows Flows can have Mule Sources (such as an HTTP listener receiving a request) that trigger the execution of a flow. For cases where you do not want a source to start a flow right away, you can configure your flow as initially stopped and start it later through [Runtime Manager](https://docs.mulesoft.com/runtime-manager/flow-management). Like functions or methods in other programming languages, it is a best practice to focus your flows on specific (perhaps reusable) activities, such as receiving an API request from a web client, processing the event, then returning an appropriate response. If the event processing gets complicated, or must call out to other services, you might factor out that behavior into other flows. ## Using Subflows A _subflow_ is a scope that enables you to group event processors in a manner similar to that of a flow, but with certain differences and limitations: - Subflows do not have Mule event sources. - Subflows do not have an error handling scope. - During design, subflows work as macros that replace the Flow Reference components that call them. When you build the application, all Flow Reference components that call a subflow are replaced by the contents of the referenced subflow. - Referencing subflows results in better performance than referencing a flow. ### Limitations Because the contents of a subflow replace each Flow Reference component that references that subflow, several instances of the event processors inside that subflow exist in the application at runtime. This behavior can cause issues with event processors that depend on unique IDs or instances to execute, such as batch processors. For example, configuring a batch job inside a subflow causes the application to fail during deployment if the subflow is referenced from more than one Flow Reference component. The application fails to deploy because multiple instances of a batch job with the same job instance ID exist, which is not allowed. ## Error Handling Each flow (but not subflow) can have its own error handling. One reason for calling a flow through a Flow Reference component is to isolate the error handling to different contexts. For example, a parent flow that receives web client requests might define HTTP-related error handling. If the parent flow then calls a JMS queue for further processing, you can put the JMS event processors in a separate child flow and call that flow with a Flow Reference component. This child flow can then define its own JMS-related error handling. This practice is similar to the way you handle or propagate errors in other programming languages, like Java. Like a flow or subflow, a [Try scope](https://docs.mulesoft.com/mule-runtime/4.9/try-scope-concept) also groups together a sequence of event processors with its own error handling. You can place a Try scope inside a flow or subflow to isolate error handling inside a flow without the need to create a separate flow or subflow. The trade-off is that error handling through a Try scope occurs inline inside the flow, which makes it harder to reuse between other flows or subflows. In both cases, calling a flow or including a Try scope isolates the error handling, similar to the use of Try-Catch blocks inside Java code. For example, placing JMS queue event processing (described above) in its own flow or within a Try scope results in exactly the same error handling behavior, but the event processors in a Try scope cannot be called from another flow. ## Branching Event Processing Some scopes are available for a flow to branch event processing into separate threads and to allow asynchronous processing of the event at a specific point in the flow, for example, the [Scatter-Gather](https://docs.mulesoft.com/mule-runtime/4.9/scatter-gather-concept) and [Async](https://docs.mulesoft.com/mule-runtime/4.9/async-scope-reference) scopes. A [Choice](https://docs.mulesoft.com/mule-runtime/4.9/choice-router-concept) router enables you to change the downstream sequence of event processors based on some condition. ## See Also - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/4.9/flow-component) - [Mule Runtime](https://docs.mulesoft.com/mule-runtime/4.9/) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: anypoint studio, studio, mule esb, orchestration --- # Flows and Subflows > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule apps process messages and other parts of Mule events through Mule components, connectors, and modules that are set up within the scope of Flow and Subflow components within an app. An app can consist of a single flow, or it can break up processing into discrete flows and subflows that you add to the app and connect together. Mule apps in production environments typically use multiple flows and subflows to divide the app into functional modules or for [error handling](#error_handling) purposes. For example, one flow might receive a record and transform data into a given format that another flow processes in some special way. You can connect and trigger their execution with [Flow Reference](https://docs.mulesoft.com/mule-runtime/latest/flowref-about) components or by using the DataWeave `lookup` function within expressions and transformations. The function passes the current event to another flow for further event processing. You can think of a Flow Reference as a function call that accepts an event as input and then returns the modified event. ## Using Flows Flows can have Mule Sources (such as an HTTP listener receiving a request) that trigger the execution of a flow. For cases where you do not want a source to start a flow right away, you can configure your flow as initially stopped and start it later through [Runtime Manager](https://docs.mulesoft.com/runtime-manager/flow-management). Like functions or methods in other programming languages, it is a best practice to focus your flows on specific (perhaps reusable) activities, such as receiving an API request from a web client, processing the event, then returning an appropriate response. If the event processing gets complicated, or must call out to other services, you might factor out that behavior into other flows. ## Using Subflows A _subflow_ is a scope that enables you to group event processors in a manner similar to that of a flow, but with certain differences and limitations: - Subflows do not have Mule event sources. - Subflows do not have an error handling scope. - During design, subflows work as macros that replace the Flow Reference components that call them. When you build the application, all Flow Reference components that call a subflow are replaced by the contents of the referenced subflow. - Referencing subflows results in better performance than referencing a flow. ### Limitations Because the contents of a subflow replace each Flow Reference component that references that subflow, several instances of the event processors inside that subflow exist in the application at runtime. This behavior can cause issues with event processors that depend on unique IDs or instances to execute, such as batch processors. For example, configuring a batch job inside a subflow causes the application to fail during deployment if the subflow is referenced from more than one Flow Reference component. The application fails to deploy because multiple instances of a batch job with the same job instance ID exist, which is not allowed. ## Error Handling Each flow (but not subflow) can have its own error handling. One reason for calling a flow through a Flow Reference component is to isolate the error handling to different contexts. For example, a parent flow that receives web client requests might define HTTP-related error handling. If the parent flow then calls a JMS queue for further processing, you can put the JMS event processors in a separate child flow and call that flow with a Flow Reference component. This child flow can then define its own JMS-related error handling. This practice is similar to the way you handle or propagate errors in other programming languages, like Java. Like a flow or subflow, a [Try scope](https://docs.mulesoft.com/mule-runtime/latest/try-scope-concept) also groups together a sequence of event processors with its own error handling. You can place a Try scope inside a flow or subflow to isolate error handling inside a flow without the need to create a separate flow or subflow. The trade-off is that error handling through a Try scope occurs inline inside the flow, which makes it harder to reuse between other flows or subflows. In both cases, calling a flow or including a Try scope isolates the error handling, similar to the use of Try-Catch blocks inside Java code. For example, placing JMS queue event processing (described above) in its own flow or within a Try scope results in exactly the same error handling behavior, but the event processors in a Try scope cannot be called from another flow. ## Branching Event Processing Some scopes are available for a flow to branch event processing into separate threads and to allow asynchronous processing of the event at a specific point in the flow, for example, the [Scatter-Gather](https://docs.mulesoft.com/mule-runtime/latest/scatter-gather-concept) and [Async](https://docs.mulesoft.com/mule-runtime/latest/async-scope-reference) scopes. A [Choice](https://docs.mulesoft.com/mule-runtime/latest/choice-router-concept) router enables you to change the downstream sequence of event processors based on some condition. ## See Also - [Flow and Subflow Scopes](https://docs.mulesoft.com/mule-runtime/latest/flow-component) - [Mule Runtime](https://docs.mulesoft.com/mule-runtime/latest/) --- product: Mule Runtime version: 4.11 --- # For Each Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The For Each scope splits a payload into elements and processes them one by one through the components that you place in the scope. It is similar to a `for-each`/`for` loop code block in most programming languages and can process any collection, including lists and arrays. The collection can be any supported content type, such as `application/json`, `application/java`, or `application/xml`. General considerations about the For Each scope: - By default, For Each tries to split the payload. If the payload is a simple Java collection, the For Each scope can split it without any configuration. The payload inside the For Each scope is each of the split elements. Attributes within the original message are ignored because they are related to the entire message. - For Each does not modify the current payload. The output payload is the same as the input. - For non-Java collections, such as XML or JSON, use a DataWeave expression to split data. Use the **Collection** field for this purpose. In the following example, the **Collection** field in For Each is set to iterate over an array stored in `payload.topics`: ![A For Each component showing a flow with settings](/mulesoft/current/en-us/mule-runtime/4.11/_images/component-foreach-example.png) The For Each scope stores each item of the collection in `payload` during each iteration. You can also split an array into batches to enable quicker processing. Each batch is treated as a separate Mule message. For example, if a collection has 200 elements and you set **Batch Size** to `50`, the For Each scope iteratively processes 4 batches of 50 elements, each as a separate Mule message. ## Example XML This is an example XML based on the For Each scope configuration detailed above: ```xml ... ... ``` ## Variable Propagation Every execution of the For Each scope starts with the variables and values from the previous execution of the block. New variables or modifications to existing variables that take place when processing one element are visible during the processing of another element. These changes to variables continue to be available outside the For Each scope. ```xml ``` After aggregation, the variables are: ```json { "var1": "var1", "var2": "newValue", "var3": "otherVal", "var4": "val4" } ``` ## Error Handling If one of the elements in a collection throws an exception, the For Each scope stops processing that collection and invokes the error handler. ## Example Projects There are several example projects in Anypoint Exchange that you can open in Anypoint Studio to learn more about how to use the For Each scope: - _Authenticating Salesforce using OAuth2_ - _Import contacts into Microsoft Dynamics CRM_ - _Importing a CSV file into mongoDB_ - _Importing an Email Attachment using the IMAP Connector_ - _Importing Email Attachments using the POP3 Connector_ - _Querying a Database and Attaching Results to an Email_ To download and open an example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## XML Reference For Each scopes open and close with a `` tag. Components that are affected by this scope are defined as child elements of the `` tag. ### Configurable Variables
VariableDefaultDescription

collection

payload

An expression that returns a Java collection, object array, map, or DOM nodes.

counterVariableName

counter

Name of the variable that stores the number of messages over which it iterates.

batchSize

1

Partitions the collection into sub-collections of the specified size. For example, if a collection has 200 elements and you set the batch size to 50, it processes 4 batches of 50 elements each.

rootMessageVariableName

rootMessage

Name of the variable that stores the parent message. The parent is the complete, non-split message.

## Differences between For Each and Parallel For Each Scopes Both For Each and Parallel For Each split the defined collection, and the components within the scope process each element in the collection. Also, in both cases, each route runs with the same initial context. The difference between these two scopes are: - For Each works sequentially, while the Parallel For Each processes in parallel. This difference affects _error handling_: Because of the processing differences, the execution of For Each execution is interrupted when an error is raised (and the Error Handler is invoked), while Parallel For Each processes every route before invoking the Error Handler with a `MULE:COMPOSITE_ROUTE` error type. - For Each does not modify the payload, while the Parallel For Each outputs a collection of the output messages from each iteration. See [Parallel For Each Scope](https://docs.mulesoft.com/mule-runtime/4.11/parallel-foreach-scope). ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-event) - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-message) --- product: Mule Runtime version: 4.12 --- # For Each Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The For Each scope splits a payload into elements and processes them one by one through the components that you place in the scope. It is similar to a `for-each`/`for` loop code block in most programming languages and can process any collection, including lists and arrays. The collection can be any supported content type, such as `application/json`, `application/java`, or `application/xml`. General considerations about the For Each scope: - By default, For Each tries to split the payload. If the payload is a simple Java collection, the For Each scope can split it without any configuration. The payload inside the For Each scope is each of the split elements. Attributes within the original message are ignored because they are related to the entire message. - For Each does not modify the current payload. The output payload is the same as the input. - For non-Java collections, such as XML or JSON, use a DataWeave expression to split data. Use the **Collection** field for this purpose. In the following example, the **Collection** field in For Each is set to iterate over an array stored in `payload.topics`: ![A For Each component showing a flow with settings](/mulesoft/current/en-us/mule-runtime/4.12/_images/component-foreach-example.png) The For Each scope stores each item of the collection in `payload` during each iteration. You can also split an array into batches to enable quicker processing. Each batch is treated as a separate Mule message. For example, if a collection has 200 elements and you set **Batch Size** to `50`, the For Each scope iteratively processes 4 batches of 50 elements, each as a separate Mule message. ## Example XML This is an example XML based on the For Each scope configuration detailed above: ```xml ... ... ``` ## Variable Propagation Every execution of the For Each scope starts with the variables and values from the previous execution of the block. New variables or modifications to existing variables that take place when processing one element are visible during the processing of another element. These changes to variables continue to be available outside the For Each scope. ```xml ``` After aggregation, the variables are: ```json { "var1": "var1", "var2": "newValue", "var3": "otherVal", "var4": "val4" } ``` ## Error Handling If one of the elements in a collection throws an exception, the For Each scope stops processing that collection and invokes the error handler. ## Example Projects There are several example projects in Anypoint Exchange that you can open in Anypoint Studio to learn more about how to use the For Each scope: - _Authenticating Salesforce using OAuth2_ - _Import contacts into Microsoft Dynamics CRM_ - _Importing a CSV file into mongoDB_ - _Importing an Email Attachment using the IMAP Connector_ - _Importing Email Attachments using the POP3 Connector_ - _Querying a Database and Attaching Results to an Email_ To download and open an example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## XML Reference For Each scopes open and close with a `` tag. Components that are affected by this scope are defined as child elements of the `` tag. ### Configurable Variables
VariableDefaultDescription

collection

payload

An expression that returns a Java collection, object array, map, or DOM nodes.

counterVariableName

counter

Name of the variable that stores the number of messages over which it iterates.

batchSize

1

Partitions the collection into sub-collections of the specified size. For example, if a collection has 200 elements and you set the batch size to 50, it processes 4 batches of 50 elements each.

rootMessageVariableName

rootMessage

Name of the variable that stores the parent message. The parent is the complete, non-split message.

## Differences between For Each and Parallel For Each Scopes Both For Each and Parallel For Each split the defined collection, and the components within the scope process each element in the collection. Also, in both cases, each route runs with the same initial context. The difference between these two scopes are: - For Each works sequentially, while the Parallel For Each processes in parallel. This difference affects _error handling_: Because of the processing differences, the execution of For Each execution is interrupted when an error is raised (and the Error Handler is invoked), while Parallel For Each processes every route before invoking the Error Handler with a `MULE:COMPOSITE_ROUTE` error type. - For Each does not modify the payload, while the Parallel For Each outputs a collection of the output messages from each iteration. See [Parallel For Each Scope](https://docs.mulesoft.com/mule-runtime/4.12/parallel-foreach-scope). ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-event) - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-message) --- product: Mule Runtime version: 4.3 --- # For Each Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The For Each scope splits a payload into elements and processes them one by one through the components that you place in the scope. It is similar to a `for-each`/`for` loop code block in most programming languages and can process any collection, including lists and arrays. The collection can be any supported content type, such as `application/json`, `application/java`, or `application/xml`. General considerations about the For Each scope: - By default, For Each tries to split the payload. If the payload is a simple Java collection, the For Each scope can split it without any configuration. The payload inside the For Each scope is each of the split elements. Attributes within the original message are ignored because they are related to the entire message. - For Each does not modify the current payload. The output payload is the same as the input. - For non-Java collections, such as XML or JSON, use a DataWeave expression to split data. Use the **Collection** field for this purpose. In the following example, the **Collection** field in For Each is set to iterate over an array stored in `payload.topics`: ![For Each Component](/mulesoft/current/en-us/mule-runtime/4.3/_images/component-foreach-example.png) The For Each scope stores each item of the collection in `payload` during each iteration. You can also split an array into batches to enable quicker processing. Each batch is treated as a separate Mule message. For example, if a collection has 200 elements and you set **Batch Size** to `50`, the For Each scope iteratively processes 4 batches of 50 elements, each as a separate Mule message. ## Example XML This is an example XML based on the For Each scope configuration detailed above: ```xml ... ... ``` ## Variable Propagation Every execution of the For Each scope starts with the variables and values from the previous execution of the block. New variables or modifications to existing variables that take place when processing one element are visible during the processing of another element. These changes to variables continue to be available outside the For Each scope. ```xml ``` After aggregation, the variables are: ```json { "var1": "var1", "var2": "newValue", "var3": "otherVal", "var4": "val4" } ``` ## Error Handling If one of the elements in a collection throws an exception, the For Each scope stops processing that collection and invokes the error handler. ## Example Projects There are several example projects in Anypoint Exchange that you can open in Anypoint Studio to learn more about how to use the For Each scope: - _Authenticating Salesforce using OAuth2_ - _Import contacts into Microsoft Dynamics CRM_ - _Importing a CSV file into mongoDB_ - _Importing an Email Attachment using the IMAP Connector_ - _Importing Email Attachments using the POP3 Connector_ - _Querying a Database and Attaching Results to an Email_ To download and open an example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## XML Reference For Each scopes open and close with a `` tag. Components that are affected by this scope are defined as child elements of the `` tag. ### Configurable Variables
VariableDefaultDescription

collection

payload

An expression that returns a Java collection, object array, map, or DOM nodes.

counterVariableName

counter

Name of the variable that stores the number of messages over which it iterates.

batchSize

1

Partitions the collection into sub-collections of the specified size. For example, if a collection has 200 elements and you set the batch size to 50, it processes 4 batches of 50 elements each.

rootMessageVariableName

rootMessage

Name of the variable that stores the parent message. The parent is the complete, non-split message.

## Differences between For Each and Parallel For Each Scopes Both For Each and Parallel For Each split the defined collection, and the components within the scope process each element in the collection. Also, in both cases, each route runs with the same initial context. The difference between these two scopes are: - For Each works sequentially, while the Parallel For Each processes in parallel. This difference affects _error handling_: Because of the processing differences, the execution of For Each execution is interrupted when an error is raised (and the Error Handler is invoked), while Parallel For Each processes every route before invoking the Error Handler with a `MULE:COMPOSITE_ROUTE` error type. - For Each does not modify the payload, while the Parallel For Each outputs a collection of the output messages from each iteration. See [Parallel For Each Scope](https://docs.mulesoft.com/mule-runtime/4.3/parallel-foreach-scope). ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-event) - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-message) --- product: Mule Runtime version: 4.4 --- # For Each Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The For Each scope splits a payload into elements and processes them one by one through the components that you place in the scope. It is similar to a `for-each`/`for` loop code block in most programming languages and can process any collection, including lists and arrays. The collection can be any supported content type, such as `application/json`, `application/java`, or `application/xml`. General considerations about the For Each scope: - By default, For Each tries to split the payload. If the payload is a simple Java collection, the For Each scope can split it without any configuration. The payload inside the For Each scope is each of the split elements. Attributes within the original message are ignored because they are related to the entire message. - For Each does not modify the current payload. The output payload is the same as the input. - For non-Java collections, such as XML or JSON, use a DataWeave expression to split data. Use the **Collection** field for this purpose. In the following example, the **Collection** field in For Each is set to iterate over an array stored in `payload.topics`: ![For Each Component](/mulesoft/current/en-us/mule-runtime/4.4/_images/component-foreach-example.png) The For Each scope stores each item of the collection in `payload` during each iteration. You can also split an array into batches to enable quicker processing. Each batch is treated as a separate Mule message. For example, if a collection has 200 elements and you set **Batch Size** to `50`, the For Each scope iteratively processes 4 batches of 50 elements, each as a separate Mule message. ## Example XML This is an example XML based on the For Each scope configuration detailed above: ```xml ... ... ``` ## Variable Propagation Every execution of the For Each scope starts with the variables and values from the previous execution of the block. New variables or modifications to existing variables that take place when processing one element are visible during the processing of another element. These changes to variables continue to be available outside the For Each scope. ```xml ``` After aggregation, the variables are: ```json { "var1": "var1", "var2": "newValue", "var3": "otherVal", "var4": "val4" } ``` ## Error Handling If one of the elements in a collection throws an exception, the For Each scope stops processing that collection and invokes the error handler. ## Example Projects There are several example projects in Anypoint Exchange that you can open in Anypoint Studio to learn more about how to use the For Each scope: - _Authenticating Salesforce using OAuth2_ - _Import contacts into Microsoft Dynamics CRM_ - _Importing a CSV file into mongoDB_ - _Importing an Email Attachment using the IMAP Connector_ - _Importing Email Attachments using the POP3 Connector_ - _Querying a Database and Attaching Results to an Email_ To download and open an example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## XML Reference For Each scopes open and close with a `` tag. Components that are affected by this scope are defined as child elements of the `` tag. ### Configurable Variables
VariableDefaultDescription

collection

payload

An expression that returns a Java collection, object array, map, or DOM nodes.

counterVariableName

counter

Name of the variable that stores the number of messages over which it iterates.

batchSize

1

Partitions the collection into sub-collections of the specified size. For example, if a collection has 200 elements and you set the batch size to 50, it processes 4 batches of 50 elements each.

rootMessageVariableName

rootMessage

Name of the variable that stores the parent message. The parent is the complete, non-split message.

## Differences between For Each and Parallel For Each Scopes Both For Each and Parallel For Each split the defined collection, and the components within the scope process each element in the collection. Also, in both cases, each route runs with the same initial context. The difference between these two scopes are: - For Each works sequentially, while the Parallel For Each processes in parallel. This difference affects _error handling_: Because of the processing differences, the execution of For Each execution is interrupted when an error is raised (and the Error Handler is invoked), while Parallel For Each processes every route before invoking the Error Handler with a `MULE:COMPOSITE_ROUTE` error type. - For Each does not modify the payload, while the Parallel For Each outputs a collection of the output messages from each iteration. See [Parallel For Each Scope](https://docs.mulesoft.com/mule-runtime/4.4/parallel-foreach-scope). ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-event) - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-message) --- product: Mule Runtime version: 4.6 --- # For Each Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The For Each scope splits a payload into elements and processes them one by one through the components that you place in the scope. It is similar to a `for-each`/`for` loop code block in most programming languages and can process any collection, including lists and arrays. The collection can be any supported content type, such as `application/json`, `application/java`, or `application/xml`. General considerations about the For Each scope: - By default, For Each tries to split the payload. If the payload is a simple Java collection, the For Each scope can split it without any configuration. The payload inside the For Each scope is each of the split elements. Attributes within the original message are ignored because they are related to the entire message. - For Each does not modify the current payload. The output payload is the same as the input. - For non-Java collections, such as XML or JSON, use a DataWeave expression to split data. Use the **Collection** field for this purpose. In the following example, the **Collection** field in For Each is set to iterate over an array stored in `payload.topics`: ![For Each Component](/mulesoft/current/en-us/mule-runtime/4.6/_images/component-foreach-example.png) The For Each scope stores each item of the collection in `payload` during each iteration. You can also split an array into batches to enable quicker processing. Each batch is treated as a separate Mule message. For example, if a collection has 200 elements and you set **Batch Size** to `50`, the For Each scope iteratively processes 4 batches of 50 elements, each as a separate Mule message. ## Example XML This is an example XML based on the For Each scope configuration detailed above: ```xml ... ... ``` ## Variable Propagation Every execution of the For Each scope starts with the variables and values from the previous execution of the block. New variables or modifications to existing variables that take place when processing one element are visible during the processing of another element. These changes to variables continue to be available outside the For Each scope. ```xml ``` After aggregation, the variables are: ```json { "var1": "var1", "var2": "newValue", "var3": "otherVal", "var4": "val4" } ``` ## Error Handling If one of the elements in a collection throws an exception, the For Each scope stops processing that collection and invokes the error handler. ## Example Projects There are several example projects in Anypoint Exchange that you can open in Anypoint Studio to learn more about how to use the For Each scope: - _Authenticating Salesforce using OAuth2_ - _Import contacts into Microsoft Dynamics CRM_ - _Importing a CSV file into mongoDB_ - _Importing an Email Attachment using the IMAP Connector_ - _Importing Email Attachments using the POP3 Connector_ - _Querying a Database and Attaching Results to an Email_ To download and open an example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## XML Reference For Each scopes open and close with a `` tag. Components that are affected by this scope are defined as child elements of the `` tag. ### Configurable Variables
VariableDefaultDescription

collection

payload

An expression that returns a Java collection, object array, map, or DOM nodes.

counterVariableName

counter

Name of the variable that stores the number of messages over which it iterates.

batchSize

1

Partitions the collection into sub-collections of the specified size. For example, if a collection has 200 elements and you set the batch size to 50, it processes 4 batches of 50 elements each.

rootMessageVariableName

rootMessage

Name of the variable that stores the parent message. The parent is the complete, non-split message.

## Differences between For Each and Parallel For Each Scopes Both For Each and Parallel For Each split the defined collection, and the components within the scope process each element in the collection. Also, in both cases, each route runs with the same initial context. The difference between these two scopes are: - For Each works sequentially, while the Parallel For Each processes in parallel. This difference affects _error handling_: Because of the processing differences, the execution of For Each execution is interrupted when an error is raised (and the Error Handler is invoked), while Parallel For Each processes every route before invoking the Error Handler with a `MULE:COMPOSITE_ROUTE` error type. - For Each does not modify the payload, while the Parallel For Each outputs a collection of the output messages from each iteration. See [Parallel For Each Scope](https://docs.mulesoft.com/mule-runtime/4.6/parallel-foreach-scope). ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-event) - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-message) --- product: Mule Runtime version: 4.9 --- # For Each Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The For Each scope splits a payload into elements and processes them one by one through the components that you place in the scope. It is similar to a `for-each`/`for` loop code block in most programming languages and can process any collection, including lists and arrays. The collection can be any supported content type, such as `application/json`, `application/java`, or `application/xml`. General considerations about the For Each scope: - By default, For Each tries to split the payload. If the payload is a simple Java collection, the For Each scope can split it without any configuration. The payload inside the For Each scope is each of the split elements. Attributes within the original message are ignored because they are related to the entire message. - For Each does not modify the current payload. The output payload is the same as the input. - For non-Java collections, such as XML or JSON, use a DataWeave expression to split data. Use the **Collection** field for this purpose. In the following example, the **Collection** field in For Each is set to iterate over an array stored in `payload.topics`: ![A For Each component showing a flow with settings](/mulesoft/current/en-us/mule-runtime/4.9/_images/component-foreach-example.png) The For Each scope stores each item of the collection in `payload` during each iteration. You can also split an array into batches to enable quicker processing. Each batch is treated as a separate Mule message. For example, if a collection has 200 elements and you set **Batch Size** to `50`, the For Each scope iteratively processes 4 batches of 50 elements, each as a separate Mule message. ## Example XML This is an example XML based on the For Each scope configuration detailed above: ```xml ... ... ``` ## Variable Propagation Every execution of the For Each scope starts with the variables and values from the previous execution of the block. New variables or modifications to existing variables that take place when processing one element are visible during the processing of another element. These changes to variables continue to be available outside the For Each scope. ```xml ``` After aggregation, the variables are: ```json { "var1": "var1", "var2": "newValue", "var3": "otherVal", "var4": "val4" } ``` ## Error Handling If one of the elements in a collection throws an exception, the For Each scope stops processing that collection and invokes the error handler. ## Example Projects There are several example projects in Anypoint Exchange that you can open in Anypoint Studio to learn more about how to use the For Each scope: - _Authenticating Salesforce using OAuth2_ - _Import contacts into Microsoft Dynamics CRM_ - _Importing a CSV file into mongoDB_ - _Importing an Email Attachment using the IMAP Connector_ - _Importing Email Attachments using the POP3 Connector_ - _Querying a Database and Attaching Results to an Email_ To download and open an example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## XML Reference For Each scopes open and close with a `` tag. Components that are affected by this scope are defined as child elements of the `` tag. ### Configurable Variables
VariableDefaultDescription

collection

payload

An expression that returns a Java collection, object array, map, or DOM nodes.

counterVariableName

counter

Name of the variable that stores the number of messages over which it iterates.

batchSize

1

Partitions the collection into sub-collections of the specified size. For example, if a collection has 200 elements and you set the batch size to 50, it processes 4 batches of 50 elements each.

rootMessageVariableName

rootMessage

Name of the variable that stores the parent message. The parent is the complete, non-split message.

## Differences between For Each and Parallel For Each Scopes Both For Each and Parallel For Each split the defined collection, and the components within the scope process each element in the collection. Also, in both cases, each route runs with the same initial context. The difference between these two scopes are: - For Each works sequentially, while the Parallel For Each processes in parallel. This difference affects _error handling_: Because of the processing differences, the execution of For Each execution is interrupted when an error is raised (and the Error Handler is invoked), while Parallel For Each processes every route before invoking the Error Handler with a `MULE:COMPOSITE_ROUTE` error type. - For Each does not modify the payload, while the Parallel For Each outputs a collection of the output messages from each iteration. See [Parallel For Each Scope](https://docs.mulesoft.com/mule-runtime/4.9/parallel-foreach-scope). ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-event) - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-message) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # For Each Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The For Each scope splits a payload into elements and processes them one by one through the components that you place in the scope. It is similar to a `for-each`/`for` loop code block in most programming languages and can process any collection, including lists and arrays. The collection can be any supported content type, such as `application/json`, `application/java`, or `application/xml`. General considerations about the For Each scope: - By default, For Each tries to split the payload. If the payload is a simple Java collection, the For Each scope can split it without any configuration. The payload inside the For Each scope is each of the split elements. Attributes within the original message are ignored because they are related to the entire message. - For Each does not modify the current payload. The output payload is the same as the input. - For non-Java collections, such as XML or JSON, use a DataWeave expression to split data. Use the **Collection** field for this purpose. In the following example, the **Collection** field in For Each is set to iterate over an array stored in `payload.topics`: ![A For Each component showing a flow with settings](/mulesoft/current/en-us/mule-runtime/latest/_images/component-foreach-example.png) The For Each scope stores each item of the collection in `payload` during each iteration. You can also split an array into batches to enable quicker processing. Each batch is treated as a separate Mule message. For example, if a collection has 200 elements and you set **Batch Size** to `50`, the For Each scope iteratively processes 4 batches of 50 elements, each as a separate Mule message. ## Example XML This is an example XML based on the For Each scope configuration detailed above: ```xml ... ... ``` ## Variable Propagation Every execution of the For Each scope starts with the variables and values from the previous execution of the block. New variables or modifications to existing variables that take place when processing one element are visible during the processing of another element. These changes to variables continue to be available outside the For Each scope. ```xml ``` After aggregation, the variables are: ```json { "var1": "var1", "var2": "newValue", "var3": "otherVal", "var4": "val4" } ``` ## Error Handling If one of the elements in a collection throws an exception, the For Each scope stops processing that collection and invokes the error handler. ## Example Projects There are several example projects in Anypoint Exchange that you can open in Anypoint Studio to learn more about how to use the For Each scope: - _Authenticating Salesforce using OAuth2_ - _Import contacts into Microsoft Dynamics CRM_ - _Importing a CSV file into mongoDB_ - _Importing an Email Attachment using the IMAP Connector_ - _Importing Email Attachments using the POP3 Connector_ - _Querying a Database and Attaching Results to an Email_ To download and open an example project while you are in Anypoint Studio, click the Exchange icon in the upper-left corner. Then, in the window that opens, log into Anypoint Exchange and search on the name of the project. ## XML Reference For Each scopes open and close with a `` tag. Components that are affected by this scope are defined as child elements of the `` tag. ### Configurable Variables
VariableDefaultDescription

collection

payload

An expression that returns a Java collection, object array, map, or DOM nodes.

counterVariableName

counter

Name of the variable that stores the number of messages over which it iterates.

batchSize

1

Partitions the collection into sub-collections of the specified size. For example, if a collection has 200 elements and you set the batch size to 50, it processes 4 batches of 50 elements each.

rootMessageVariableName

rootMessage

Name of the variable that stores the parent message. The parent is the complete, non-split message.

## Differences between For Each and Parallel For Each Scopes Both For Each and Parallel For Each split the defined collection, and the components within the scope process each element in the collection. Also, in both cases, each route runs with the same initial context. The difference between these two scopes are: - For Each works sequentially, while the Parallel For Each processes in parallel. This difference affects _error handling_: Because of the processing differences, the execution of For Each execution is interrupted when an error is raised (and the Error Handler is invoked), while Parallel For Each processes every route before invoking the Error Handler with a `MULE:COMPOSITE_ROUTE` error type. - For Each does not modify the payload, while the Parallel For Each outputs a collection of the output messages from each iteration. See [Parallel For Each Scope](https://docs.mulesoft.com/mule-runtime/latest/parallel-foreach-scope). ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/latest/about-mule-event) - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/latest/about-mule-message) --- product: Mule Runtime version: 4.11 keywords: configure, finetune, global, global settings --- # Global Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Global configurations for a mule application such as the default transaction timeout or default error handler can be configured in the `` element of the root level of the [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-configuration). ## Create a Global Configuration from Studio To create a global configuration: 1. In Studio, select the **Global Elements** tab and click **Create**: ![A configuration panel for creating global settings with fields for HTTP listener configuration](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-global-settings-create.png) 2. Select **Global Configurations** > **Configuration**: ![A menu for choosing types of global configurations including caching and scheduler settings](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-global-configurations.png) 3. Configure the **Default Error Handler** and the **HA Profile** values. ## Create a Global Configuration by Editing the XML The following example defines a global error handler, and then a global configuration that specifies a default transaction timeout and references the global error handler as the default: ```xml ... ... ... ``` ## Global Configurations Reference The following table shows all attributes of the `` element:
NameTypeRequiredDefaultDescription

defaultResponseTimeout

string

no

10000

The default period (ms) to wait for a synchronous response.

defaultTransactionTimeout

string

no

30000

The default timeout (ms) for transactions. This can also be configured on transactions, in which case the transaction configuration is used instead of this default.

defaultErrorHandler-ref

string

no

none

The default error handler for every flow. This must be a reference to a global error handler.

shutdownTimeout

integer

no

5000

(As of Mule 2.2.2) The time in milliseconds to wait for any in-progress messages to finish processing before Mule shuts down. After this threshold has been reached, Mule starts interrupting threads, and messages can be lost. If you have a very large number of services in the same Mule instance, if you have components that take more than a couple seconds to process, or if you are using large payloads and/or slower transports, you should increase this value to allow more time for graceful shutdown. The value you specify is applied to services and separately to dispatchers, so the default value of 5000 milliseconds specifies that Mule has five seconds to process and dispatch messages gracefully after shutdown is initiated.

maxQueueTransactionFilesSize

integer

no

500

The approximated maximum space in megabytes used by the transaction log files for transactional persistent queues. Take into account that this number applies both to the set of transaction log files for XA and for local transactions. If both type of transactions are used then the approximated maximum space used will be twice the configured value.

defaultObjectSerializer-ref

string

no

none

An optional reference to an ObjectSerializer to be used as the application’s default.

### Child Elements of
NameDescription

dynamic-config-expiration

Optional. The default expiration settings for dynamic configurations, used by connectors. This can also be configured on connectors, in which case the connector configuration is used instead of this default.
For configuration details, see: Dynamic Configuration Expiration.

cluster-config

Optional. Mule application cluster configuration.
For configuration details, see: Clustering for High Performance.

## See Also - [Error Handling](https://docs.mulesoft.com/mule-runtime/4.11/error-handling) - [Dynamic Configurations](https://docs.mulesoft.com/mule-sdk/latest/static-dynamic-configs) - [Mule High Availability Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.12 keywords: configure, finetune, global, global settings --- # Global Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Global configurations for a mule application such as the default transaction timeout or default error handler can be configured in the `` element of the root level of the [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-configuration). ## Create a Global Configuration from Studio To create a global configuration: 1. In Studio, select the **Global Elements** tab and click **Create**: ![A configuration panel for creating global settings with fields for HTTP listener configuration](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-global-settings-create.png) 2. Select **Global Configurations** > **Configuration**: ![A menu for choosing types of global configurations including caching and scheduler settings](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-global-configurations.png) 3. Configure the **Default Error Handler** and the **HA Profile** values. ## Create a Global Configuration by Editing the XML The following example defines a global error handler, and then a global configuration that specifies a default transaction timeout and references the global error handler as the default: ```xml ... ... ... ``` ## Global Configurations Reference The following table shows all attributes of the `` element:
NameTypeRequiredDefaultDescription

defaultResponseTimeout

string

no

10000

The default period (ms) to wait for a synchronous response.

defaultTransactionTimeout

string

no

30000

The default timeout (ms) for transactions. This can also be configured on transactions, in which case the transaction configuration is used instead of this default.

defaultErrorHandler-ref

string

no

none

The default error handler for every flow. This must be a reference to a global error handler.

shutdownTimeout

integer

no

5000

(As of Mule 2.2.2) The time in milliseconds to wait for any in-progress messages to finish processing before Mule shuts down. After this threshold has been reached, Mule starts interrupting threads, and messages can be lost. If you have a very large number of services in the same Mule instance, if you have components that take more than a couple seconds to process, or if you are using large payloads and/or slower transports, you should increase this value to allow more time for graceful shutdown. The value you specify is applied to services and separately to dispatchers, so the default value of 5000 milliseconds specifies that Mule has five seconds to process and dispatch messages gracefully after shutdown is initiated.

maxQueueTransactionFilesSize

integer

no

500

The approximated maximum space in megabytes used by the transaction log files for transactional persistent queues. Take into account that this number applies both to the set of transaction log files for XA and for local transactions. If both type of transactions are used then the approximated maximum space used will be twice the configured value.

defaultObjectSerializer-ref

string

no

none

An optional reference to an ObjectSerializer to be used as the application’s default.

### Child Elements of
NameDescription

dynamic-config-expiration

Optional. The default expiration settings for dynamic configurations, used by connectors. This can also be configured on connectors, in which case the connector configuration is used instead of this default.
For configuration details, see: Dynamic Configuration Expiration.

cluster-config

Optional. Mule application cluster configuration.
For configuration details, see: Clustering for High Performance.

## See Also - [Error Handling](https://docs.mulesoft.com/mule-runtime/4.12/error-handling) - [Dynamic Configurations](https://docs.mulesoft.com/mule-sdk/latest/static-dynamic-configs) - [Mule High Availability Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.3 keywords: configure, finetune, global, global settings --- # Global Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Global configurations for a mule application such as the default transaction timeout or default error handler can be configured in the `` element of the root level of the [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-configuration). ## Create a Global Configuration from Studio To create a global configuration: 1. In Studio, select the **Global Elements** tab and click **Create**: ![create-global-settings](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-global-settings-create.png) 2. Select **Global Configurations** > **Configuration**: ![configure-global-settings](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-global-configurations.png) 3. Configure the **Default Error Handler** and the **HA Profile** values. ## Create a Global Configuration by Editing the XML The following example defines a global error handler, and then a global configuration that specifies a default transaction timeout and references the global error handler as the default: ```xml ... ... ... ``` ## Global Configurations Reference The following table shows all attributes of the `` element:
NameTypeRequiredDefaultDescription

defaultResponseTimeout

string

no

10000

The default period (ms) to wait for a synchronous response.

defaultTransactionTimeout

string

no

30000

The default timeout (ms) for transactions. This can also be configured on transactions, in which case the transaction configuration is used instead of this default.

defaultErrorHandler-ref

string

no

none

The default error handler for every flow. This must be a reference to a global error handler.

shutdownTimeout

integer

no

5000

(As of Mule 2.2.2) The time in milliseconds to wait for any in-progress messages to finish processing before Mule shuts down. After this threshold has been reached, Mule starts interrupting threads, and messages can be lost. If you have a very large number of services in the same Mule instance, if you have components that take more than a couple seconds to process, or if you are using large payloads and/or slower transports, you should increase this value to allow more time for graceful shutdown. The value you specify is applied to services and separately to dispatchers, so the default value of 5000 milliseconds specifies that Mule has ten seconds to process and dispatch messages gracefully after shutdown is initiated.

maxQueueTransactionFilesSize

integer

no

500

The approximated maximum space in megabytes used by the transaction log files for transactional persistent queues. Take into account that this number applies both to the set of transaction log files for XA and for local transactions. If both type of transactions are used then the approximated maximum space used will be twice the configured value.

defaultObjectSerializer-ref

string

no

none

An optional reference to an ObjectSerializer to be used as the application’s default.

### Child Elements of
NameDescription

dynamic-config-expiration

Optional. The default expiration settings for dynamic configurations, used by connectors. This can also be configured on connectors, in which case the connector configuration is used instead of this default.
For configuration details, see: Dynamic Configuration Expiration.

cluster-config

Optional. Mule application cluster configuration.
For configuration details, see: Clustering for High Performance.

## See Also - [Error Handling](https://docs.mulesoft.com/mule-runtime/4.3/error-handling) - [Dynamic Configurations](https://docs.mulesoft.com/mule-sdk/latest/static-dynamic-configs) - [Mule High Availability Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.4 keywords: configure, finetune, global, global settings --- # Global Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Global configurations for a mule application such as the default transaction timeout or default error handler can be configured in the `` element of the root level of the [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-configuration). ## Create a Global Configuration from Studio To create a global configuration: 1. In Studio, select the **Global Elements** tab and click **Create**: ![create-global-settings](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-global-settings-create.png) 2. Select **Global Configurations** > **Configuration**: ![configure-global-settings](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-global-configurations.png) 3. Configure the **Default Error Handler** and the **HA Profile** values. ## Create a Global Configuration by Editing the XML The following example defines a global error handler, and then a global configuration that specifies a default transaction timeout and references the global error handler as the default: ```xml ... ... ... ``` ## Global Configurations Reference The following table shows all attributes of the `` element:
NameTypeRequiredDefaultDescription

defaultResponseTimeout

string

no

10000

The default period (ms) to wait for a synchronous response.

defaultTransactionTimeout

string

no

30000

The default timeout (ms) for transactions. This can also be configured on transactions, in which case the transaction configuration is used instead of this default.

defaultErrorHandler-ref

string

no

none

The default error handler for every flow. This must be a reference to a global error handler.

shutdownTimeout

integer

no

5000

(As of Mule 2.2.2) The time in milliseconds to wait for any in-progress messages to finish processing before Mule shuts down. After this threshold has been reached, Mule starts interrupting threads, and messages can be lost. If you have a very large number of services in the same Mule instance, if you have components that take more than a couple seconds to process, or if you are using large payloads and/or slower transports, you should increase this value to allow more time for graceful shutdown. The value you specify is applied to services and separately to dispatchers, so the default value of 5000 milliseconds specifies that Mule has five seconds to process and dispatch messages gracefully after shutdown is initiated.

maxQueueTransactionFilesSize

integer

no

500

The approximated maximum space in megabytes used by the transaction log files for transactional persistent queues. Take into account that this number applies both to the set of transaction log files for XA and for local transactions. If both type of transactions are used then the approximated maximum space used will be twice the configured value.

defaultObjectSerializer-ref

string

no

none

An optional reference to an ObjectSerializer to be used as the application’s default.

### Child Elements of
NameDescription

dynamic-config-expiration

Optional. The default expiration settings for dynamic configurations, used by connectors. This can also be configured on connectors, in which case the connector configuration is used instead of this default.
For configuration details, see: Dynamic Configuration Expiration.

cluster-config

Optional. Mule application cluster configuration.
For configuration details, see: Clustering for High Performance.

## See Also - [Error Handling](https://docs.mulesoft.com/mule-runtime/4.4/error-handling) - [Dynamic Configurations](https://docs.mulesoft.com/mule-sdk/latest/static-dynamic-configs) - [Mule High Availability Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.6 keywords: configure, finetune, global, global settings --- # Global Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Global configurations for a mule application such as the default transaction timeout or default error handler can be configured in the `` element of the root level of the [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-configuration). ## Create a Global Configuration from Studio To create a global configuration: 1. In Studio, select the **Global Elements** tab and click **Create**: ![create-global-settings](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-global-settings-create.png) 2. Select **Global Configurations** > **Configuration**: ![configure-global-settings](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-global-configurations.png) 3. Configure the **Default Error Handler** and the **HA Profile** values. ## Create a Global Configuration by Editing the XML The following example defines a global error handler, and then a global configuration that specifies a default transaction timeout and references the global error handler as the default: ```xml ... ... ... ``` ## Global Configurations Reference The following table shows all attributes of the `` element:
NameTypeRequiredDefaultDescription

defaultResponseTimeout

string

no

10000

The default period (ms) to wait for a synchronous response.

defaultTransactionTimeout

string

no

30000

The default timeout (ms) for transactions. This can also be configured on transactions, in which case the transaction configuration is used instead of this default.

defaultErrorHandler-ref

string

no

none

The default error handler for every flow. This must be a reference to a global error handler.

shutdownTimeout

integer

no

5000

(As of Mule 2.2.2) The time in milliseconds to wait for any in-progress messages to finish processing before Mule shuts down. After this threshold has been reached, Mule starts interrupting threads, and messages can be lost. If you have a very large number of services in the same Mule instance, if you have components that take more than a couple seconds to process, or if you are using large payloads and/or slower transports, you should increase this value to allow more time for graceful shutdown. The value you specify is applied to services and separately to dispatchers, so the default value of 5000 milliseconds specifies that Mule has five seconds to process and dispatch messages gracefully after shutdown is initiated.

maxQueueTransactionFilesSize

integer

no

500

The approximated maximum space in megabytes used by the transaction log files for transactional persistent queues. Take into account that this number applies both to the set of transaction log files for XA and for local transactions. If both type of transactions are used then the approximated maximum space used will be twice the configured value.

defaultObjectSerializer-ref

string

no

none

An optional reference to an ObjectSerializer to be used as the application’s default.

### Child Elements of
NameDescription

dynamic-config-expiration

Optional. The default expiration settings for dynamic configurations, used by connectors. This can also be configured on connectors, in which case the connector configuration is used instead of this default.
For configuration details, see: Dynamic Configuration Expiration.

cluster-config

Optional. Mule application cluster configuration.
For configuration details, see: Clustering for High Performance.

## See Also - [Error Handling](https://docs.mulesoft.com/mule-runtime/4.6/error-handling) - [Dynamic Configurations](https://docs.mulesoft.com/mule-sdk/latest/static-dynamic-configs) - [Mule High Availability Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.9 keywords: configure, finetune, global, global settings --- # Global Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Global configurations for a mule application such as the default transaction timeout or default error handler can be configured in the `` element of the root level of the [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-configuration). ## Create a Global Configuration from Studio To create a global configuration: 1. In Studio, select the **Global Elements** tab and click **Create**: ![A configuration panel for creating global settings with fields for HTTP listener configuration](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-global-settings-create.png) 2. Select **Global Configurations** > **Configuration**: ![A menu for choosing types of global configurations including caching and scheduler settings](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-global-configurations.png) 3. Configure the **Default Error Handler** and the **HA Profile** values. ## Create a Global Configuration by Editing the XML The following example defines a global error handler, and then a global configuration that specifies a default transaction timeout and references the global error handler as the default: ```xml ... ... ... ``` ## Global Configurations Reference The following table shows all attributes of the `` element:
NameTypeRequiredDefaultDescription

defaultResponseTimeout

string

no

10000

The default period (ms) to wait for a synchronous response.

defaultTransactionTimeout

string

no

30000

The default timeout (ms) for transactions. This can also be configured on transactions, in which case the transaction configuration is used instead of this default.

defaultErrorHandler-ref

string

no

none

The default error handler for every flow. This must be a reference to a global error handler.

shutdownTimeout

integer

no

5000

(As of Mule 2.2.2) The time in milliseconds to wait for any in-progress messages to finish processing before Mule shuts down. After this threshold has been reached, Mule starts interrupting threads, and messages can be lost. If you have a very large number of services in the same Mule instance, if you have components that take more than a couple seconds to process, or if you are using large payloads and/or slower transports, you should increase this value to allow more time for graceful shutdown. The value you specify is applied to services and separately to dispatchers, so the default value of 5000 milliseconds specifies that Mule has five seconds to process and dispatch messages gracefully after shutdown is initiated.

maxQueueTransactionFilesSize

integer

no

500

The approximated maximum space in megabytes used by the transaction log files for transactional persistent queues. Take into account that this number applies both to the set of transaction log files for XA and for local transactions. If both type of transactions are used then the approximated maximum space used will be twice the configured value.

defaultObjectSerializer-ref

string

no

none

An optional reference to an ObjectSerializer to be used as the application’s default.

### Child Elements of
NameDescription

dynamic-config-expiration

Optional. The default expiration settings for dynamic configurations, used by connectors. This can also be configured on connectors, in which case the connector configuration is used instead of this default.
For configuration details, see: Dynamic Configuration Expiration.

cluster-config

Optional. Mule application cluster configuration.
For configuration details, see: Clustering for High Performance.

## See Also - [Error Handling](https://docs.mulesoft.com/mule-runtime/4.9/error-handling) - [Dynamic Configurations](https://docs.mulesoft.com/mule-sdk/latest/static-dynamic-configs) - [Mule High Availability Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: configure, finetune, global, global settings --- # Global Configurations > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Global configurations for a mule application such as the default transaction timeout or default error handler can be configured in the `` element of the root level of the [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/latest/about-mule-configuration). ## Create a Global Configuration from Studio To create a global configuration: 1. In Studio, select the **Global Elements** tab and click **Create**: ![A configuration panel for creating global settings with fields for HTTP listener configuration](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-global-settings-create.png) 2. Select **Global Configurations** > **Configuration**: ![A menu for choosing types of global configurations including caching and scheduler settings](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-global-configurations.png) 3. Configure the **Default Error Handler** and the **HA Profile** values. ## Create a Global Configuration by Editing the XML The following example defines a global error handler, and then a global configuration that specifies a default transaction timeout and references the global error handler as the default: ```xml ... ... ... ``` ## Global Configurations Reference The following table shows all attributes of the `` element:
NameTypeRequiredDefaultDescription

defaultResponseTimeout

string

no

10000

The default period (ms) to wait for a synchronous response.

defaultTransactionTimeout

string

no

30000

The default timeout (ms) for transactions. This can also be configured on transactions, in which case the transaction configuration is used instead of this default.

defaultErrorHandler-ref

string

no

none

The default error handler for every flow. This must be a reference to a global error handler.

shutdownTimeout

integer

no

5000

(As of Mule 2.2.2) The time in milliseconds to wait for any in-progress messages to finish processing before Mule shuts down. After this threshold has been reached, Mule starts interrupting threads, and messages can be lost. If you have a very large number of services in the same Mule instance, if you have components that take more than a couple seconds to process, or if you are using large payloads and/or slower transports, you should increase this value to allow more time for graceful shutdown. The value you specify is applied to services and separately to dispatchers, so the default value of 5000 milliseconds specifies that Mule has five seconds to process and dispatch messages gracefully after shutdown is initiated.

maxQueueTransactionFilesSize

integer

no

500

The approximated maximum space in megabytes used by the transaction log files for transactional persistent queues. Take into account that this number applies both to the set of transaction log files for XA and for local transactions. If both type of transactions are used then the approximated maximum space used will be twice the configured value.

defaultObjectSerializer-ref

string

no

none

An optional reference to an ObjectSerializer to be used as the application’s default.

### Child Elements of
NameDescription

dynamic-config-expiration

Optional. The default expiration settings for dynamic configurations, used by connectors. This can also be configured on connectors, in which case the connector configuration is used instead of this default.
For configuration details, see: Dynamic Configuration Expiration.

cluster-config

Optional. Mule application cluster configuration.
For configuration details, see: Clustering for High Performance.

## See Also - [Error Handling](https://docs.mulesoft.com/mule-runtime/latest/error-handling) - [Dynamic Configurations](https://docs.mulesoft.com/mule-sdk/latest/static-dynamic-configs) - [Mule High Availability Cluster](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters) --- product: Mule Runtime version: 4.11 keywords: studio, server, components, connectors, elements, palette, global elements, configuration elements --- # Global Elements > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A global element is a reusable object containing parameters that any number of elements in a flow can share. You reference a global element from Anypoint Connectors or components in your Mule application. Use the global element to apply configuration details to multiple local elements in flows. Create one global element that defines parameters and configuration details, and then reference the global element from any flow element that uses this configuration. This practice enables you to ensure consistency across flow elements. Note that some components require their properties stored in a global element. ## Benefits Global elements provide many benefits to you as a Mule application developer: reusability, efficiency, and flexibility. - Reusability You can configure a global element once and then share that configuration among processors of the same type. Configuring global elements is particularly useful when you have to define the connection details and login credentials for an external source, such as a SaaS application or database. - Efficiency You don’t have to change the same configuration multiple times for different processors in the flow if they all share a global element. For example, if you have multiple connectors that connect to the same service using one set of credentials, you can change the configuration in the global element and the changes apply to all flow elements that reference the global element. - Flexibility An element in a flow can apply a global element’s configuration exactly as defined, or it can apply modifications to the global configuration properties. ## Before You Start Review the features of the [Anypoint Studio visual editor](https://docs.mulesoft.com/studio/) to learn more about developing Mule applications using the Anypoint Studio graphical user interface and to understand the context in which you use global elements. ## Create a Global Element You can create global elements in two ways: - From the **Global Elements** tab in the Anypoint Studio canvas - From the properties panel of any connector or module that supports global elements ### From the Anypoint Studio Canvas 1. In the Anypoint Studio visual editor, click the **Global Elements** tab to access a list of all global elements in an application: ![A menu for creating and managing global configuration elements in Mule](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-new-global-element.png) 2. Click **Create** to add a new global element. 3. In the **Choose Global Type** wizard, navigate the directories or use the filter to select the type of global element you want to create, and then click **OK**. 4. Define the configurable parameters of your global element in the **Global Element Properties** window. 5. Click **OK** to save. ### From the Properties Panel of a Connector or Module To create a new global element from within a local component you placed in your flow: 1. Click the component you want to create a global element for: ![A basic flow component setup with error handling](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-global-element-component.png) 2. In the properties panel, click the Add icon next to the **Connector Configuration**: ![An interface for creating a new global element in Mule](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-global-element-create.png) 3. Complete the required fields for the type of global element you want to create. ## See Also - [Global Configurations](https://docs.mulesoft.com/mule-runtime/4.11/global-settings-configuration) --- product: Mule Runtime version: 4.12 keywords: studio, server, components, connectors, elements, palette, global elements, configuration elements --- # Global Elements > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A global element is a reusable object containing parameters that any number of elements in a flow can share. You reference a global element from Anypoint Connectors or components in your Mule application. Use the global element to apply configuration details to multiple local elements in flows. Create one global element that defines parameters and configuration details, and then reference the global element from any flow element that uses this configuration. This practice enables you to ensure consistency across flow elements. Note that some components require their properties stored in a global element. ## Benefits Global elements provide many benefits to you as a Mule application developer: reusability, efficiency, and flexibility. - Reusability You can configure a global element once and then share that configuration among processors of the same type. Configuring global elements is particularly useful when you have to define the connection details and login credentials for an external source, such as a SaaS application or database. - Efficiency You don’t have to change the same configuration multiple times for different processors in the flow if they all share a global element. For example, if you have multiple connectors that connect to the same service using one set of credentials, you can change the configuration in the global element and the changes apply to all flow elements that reference the global element. - Flexibility An element in a flow can apply a global element’s configuration exactly as defined, or it can apply modifications to the global configuration properties. ## Before You Start Review the features of the [Anypoint Studio visual editor](https://docs.mulesoft.com/studio/) to learn more about developing Mule applications using the Anypoint Studio graphical user interface and to understand the context in which you use global elements. ## Create a Global Element You can create global elements in two ways: - From the **Global Elements** tab in the Anypoint Studio canvas - From the properties panel of any connector or module that supports global elements ### From the Anypoint Studio Canvas 1. In the Anypoint Studio visual editor, click the **Global Elements** tab to access a list of all global elements in an application: ![A menu for creating and managing global configuration elements in Mule](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-new-global-element.png) 2. Click **Create** to add a new global element. 3. In the **Choose Global Type** wizard, navigate the directories or use the filter to select the type of global element you want to create, and then click **OK**. 4. Define the configurable parameters of your global element in the **Global Element Properties** window. 5. Click **OK** to save. ### From the Properties Panel of a Connector or Module To create a new global element from within a local component you placed in your flow: 1. Click the component you want to create a global element for: ![A basic flow component setup with error handling](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-global-element-component.png) 2. In the properties panel, click the Add icon next to the **Connector Configuration**: ![An interface for creating a new global element in Mule](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-global-element-create.png) 3. Complete the required fields for the type of global element you want to create. ## See Also - [Global Configurations](https://docs.mulesoft.com/mule-runtime/4.12/global-settings-configuration) --- product: Mule Runtime version: 4.3 keywords: studio, server, components, connectors, elements, palette, global elements, configuration elements --- # Global Elements > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A global element is a reusable object containing parameters that any number of elements in a flow can share. You reference a global element from Anypoint Connectors or components in your Mule application. Use the global element to apply configuration details to multiple local elements in flows. Create one global element that defines parameters and configuration details, and then reference the global element from any flow element that uses this configuration. This practice enables you to ensure consistency across flow elements. Note that some components require their properties stored in a global element. ## Benefits Global elements provide many benefits to you as a Mule application developer: reusability, efficiency, and flexibility. - Reusability You can configure a global element once and then share that configuration among processors of the same type. Configuring global elements is particularly useful when you have to define the connection details and login credentials for an external source, such as a SaaS application or database. - Efficiency You don’t have to change the same configuration multiple times for different processors in the flow if they all share a global element. For example, if you have multiple connectors that connect to the same service using one set of credentials, you can change the configuration in the global element and the changes apply to all flow elements that reference the global element. - Flexibility An element in a flow can apply a global element’s configuration exactly as defined, or it can apply modifications to the global configuration properties. ## Before You Start Review the features of the [Anypoint Studio visual editor](https://docs.mulesoft.com/studio/) to learn more about developing Mule applications using the Anypoint Studio graphical user interface and to understand the context in which you use global elements. ## Create a Global Element You can create global elements in two ways: - From the **Global Elements** tab in the Anypoint Studio canvas - From the properties panel of any connector or module that supports global elements ### From the Anypoint Studio Canvas 1. In the Anypoint Studio visual editor, click the **Global Elements** tab to access a list of all global elements in an application: ![new-global-element](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-new-global-element.png) 2. Click **Create** to add a new global element. 3. In the **Choose Global Type** wizard, navigate the directories or use the filter to select the type of global element you want to create, and then click **OK**. 4. Define the configurable parameters of your global element in the **Global Element Properties** window. 5. Click **OK** to save. ### From the Properties Panel of a Connector or Module To create a new global element from within a local component you placed in your flow: 1. Click the component you want to create a global element for: ![select-component-global-element](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-global-element-component.png) 2. In the properties panel, click the Add icon next to the **Connector Configuration**: ![create-config-global-element](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-global-element-create.png) 3. Complete the required fields for the type of global element you want to create. ## See Also - [Global Configurations](https://docs.mulesoft.com/mule-runtime/4.3/global-settings-configuration) --- product: Mule Runtime version: 4.4 keywords: studio, server, components, connectors, elements, palette, global elements, configuration elements --- # Global Elements > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A global element is a reusable object containing parameters that any number of elements in a flow can share. You reference a global element from Anypoint Connectors or components in your Mule application. Use the global element to apply configuration details to multiple local elements in flows. Create one global element that defines parameters and configuration details, and then reference the global element from any flow element that uses this configuration. This practice enables you to ensure consistency across flow elements. Note that some components require their properties stored in a global element. ## Benefits Global elements provide many benefits to you as a Mule application developer: reusability, efficiency, and flexibility. - Reusability You can configure a global element once and then share that configuration among processors of the same type. Configuring global elements is particularly useful when you have to define the connection details and login credentials for an external source, such as a SaaS application or database. - Efficiency You don’t have to change the same configuration multiple times for different processors in the flow if they all share a global element. For example, if you have multiple connectors that connect to the same service using one set of credentials, you can change the configuration in the global element and the changes apply to all flow elements that reference the global element. - Flexibility An element in a flow can apply a global element’s configuration exactly as defined, or it can apply modifications to the global configuration properties. ## Before You Start Review the features of the [Anypoint Studio visual editor](https://docs.mulesoft.com/studio/) to learn more about developing Mule applications using the Anypoint Studio graphical user interface and to understand the context in which you use global elements. ## Create a Global Element You can create global elements in two ways: - From the **Global Elements** tab in the Anypoint Studio canvas - From the properties panel of any connector or module that supports global elements ### From the Anypoint Studio Canvas 1. In the Anypoint Studio visual editor, click the **Global Elements** tab to access a list of all global elements in an application: ![new-global-element](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-new-global-element.png) 2. Click **Create** to add a new global element. 3. In the **Choose Global Type** wizard, navigate the directories or use the filter to select the type of global element you want to create, and then click **OK**. 4. Define the configurable parameters of your global element in the **Global Element Properties** window. 5. Click **OK** to save. ### From the Properties Panel of a Connector or Module To create a new global element from within a local component you placed in your flow: 1. Click the component you want to create a global element for: ![select-component-global-element](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-global-element-component.png) 2. In the properties panel, click the Add icon next to the **Connector Configuration**: ![create-config-global-element](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-global-element-create.png) 3. Complete the required fields for the type of global element you want to create. ## See Also - [Global Configurations](https://docs.mulesoft.com/mule-runtime/4.4/global-settings-configuration) --- product: Mule Runtime version: 4.6 keywords: studio, server, components, connectors, elements, palette, global elements, configuration elements --- # Global Elements > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A global element is a reusable object containing parameters that any number of elements in a flow can share. You reference a global element from Anypoint Connectors or components in your Mule application. Use the global element to apply configuration details to multiple local elements in flows. Create one global element that defines parameters and configuration details, and then reference the global element from any flow element that uses this configuration. This practice enables you to ensure consistency across flow elements. Note that some components require their properties stored in a global element. ## Benefits Global elements provide many benefits to you as a Mule application developer: reusability, efficiency, and flexibility. - Reusability You can configure a global element once and then share that configuration among processors of the same type. Configuring global elements is particularly useful when you have to define the connection details and login credentials for an external source, such as a SaaS application or database. - Efficiency You don’t have to change the same configuration multiple times for different processors in the flow if they all share a global element. For example, if you have multiple connectors that connect to the same service using one set of credentials, you can change the configuration in the global element and the changes apply to all flow elements that reference the global element. - Flexibility An element in a flow can apply a global element’s configuration exactly as defined, or it can apply modifications to the global configuration properties. ## Before You Start Review the features of the [Anypoint Studio visual editor](https://docs.mulesoft.com/studio/) to learn more about developing Mule applications using the Anypoint Studio graphical user interface and to understand the context in which you use global elements. ## Create a Global Element You can create global elements in two ways: - From the **Global Elements** tab in the Anypoint Studio canvas - From the properties panel of any connector or module that supports global elements ### From the Anypoint Studio Canvas 1. In the Anypoint Studio visual editor, click the **Global Elements** tab to access a list of all global elements in an application: ![new-global-element](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-new-global-element.png) 2. Click **Create** to add a new global element. 3. In the **Choose Global Type** wizard, navigate the directories or use the filter to select the type of global element you want to create, and then click **OK**. 4. Define the configurable parameters of your global element in the **Global Element Properties** window. 5. Click **OK** to save. ### From the Properties Panel of a Connector or Module To create a new global element from within a local component you placed in your flow: 1. Click the component you want to create a global element for: ![select-component-global-element](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-global-element-component.png) 2. In the properties panel, click the Add icon next to the **Connector Configuration**: ![create-config-global-element](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-global-element-create.png) 3. Complete the required fields for the type of global element you want to create. ## See Also - [Global Configurations](https://docs.mulesoft.com/mule-runtime/4.6/global-settings-configuration) --- product: Mule Runtime version: 4.9 keywords: studio, server, components, connectors, elements, palette, global elements, configuration elements --- # Global Elements > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A global element is a reusable object containing parameters that any number of elements in a flow can share. You reference a global element from Anypoint Connectors or components in your Mule application. Use the global element to apply configuration details to multiple local elements in flows. Create one global element that defines parameters and configuration details, and then reference the global element from any flow element that uses this configuration. This practice enables you to ensure consistency across flow elements. Note that some components require their properties stored in a global element. ## Benefits Global elements provide many benefits to you as a Mule application developer: reusability, efficiency, and flexibility. - Reusability You can configure a global element once and then share that configuration among processors of the same type. Configuring global elements is particularly useful when you have to define the connection details and login credentials for an external source, such as a SaaS application or database. - Efficiency You don’t have to change the same configuration multiple times for different processors in the flow if they all share a global element. For example, if you have multiple connectors that connect to the same service using one set of credentials, you can change the configuration in the global element and the changes apply to all flow elements that reference the global element. - Flexibility An element in a flow can apply a global element’s configuration exactly as defined, or it can apply modifications to the global configuration properties. ## Before You Start Review the features of the [Anypoint Studio visual editor](https://docs.mulesoft.com/studio/) to learn more about developing Mule applications using the Anypoint Studio graphical user interface and to understand the context in which you use global elements. ## Create a Global Element You can create global elements in two ways: - From the **Global Elements** tab in the Anypoint Studio canvas - From the properties panel of any connector or module that supports global elements ### From the Anypoint Studio Canvas 1. In the Anypoint Studio visual editor, click the **Global Elements** tab to access a list of all global elements in an application: ![A menu for creating and managing global configuration elements in Mule](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-new-global-element.png) 2. Click **Create** to add a new global element. 3. In the **Choose Global Type** wizard, navigate the directories or use the filter to select the type of global element you want to create, and then click **OK**. 4. Define the configurable parameters of your global element in the **Global Element Properties** window. 5. Click **OK** to save. ### From the Properties Panel of a Connector or Module To create a new global element from within a local component you placed in your flow: 1. Click the component you want to create a global element for: ![A basic flow component setup with error handling](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-global-element-component.png) 2. In the properties panel, click the Add icon next to the **Connector Configuration**: ![An interface for creating a new global element in Mule](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-global-element-create.png) 3. Complete the required fields for the type of global element you want to create. ## See Also - [Global Configurations](https://docs.mulesoft.com/mule-runtime/4.9/global-settings-configuration) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: studio, server, components, connectors, elements, palette, global elements, configuration elements --- # Global Elements > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A global element is a reusable object containing parameters that any number of elements in a flow can share. You reference a global element from Anypoint Connectors or components in your Mule application. Use the global element to apply configuration details to multiple local elements in flows. Create one global element that defines parameters and configuration details, and then reference the global element from any flow element that uses this configuration. This practice enables you to ensure consistency across flow elements. Note that some components require their properties stored in a global element. ## Benefits Global elements provide many benefits to you as a Mule application developer: reusability, efficiency, and flexibility. - Reusability You can configure a global element once and then share that configuration among processors of the same type. Configuring global elements is particularly useful when you have to define the connection details and login credentials for an external source, such as a SaaS application or database. - Efficiency You don’t have to change the same configuration multiple times for different processors in the flow if they all share a global element. For example, if you have multiple connectors that connect to the same service using one set of credentials, you can change the configuration in the global element and the changes apply to all flow elements that reference the global element. - Flexibility An element in a flow can apply a global element’s configuration exactly as defined, or it can apply modifications to the global configuration properties. ## Before You Start Review the features of the [Anypoint Studio visual editor](https://docs.mulesoft.com/studio/) to learn more about developing Mule applications using the Anypoint Studio graphical user interface and to understand the context in which you use global elements. ## Create a Global Element You can create global elements in two ways: - From the **Global Elements** tab in the Anypoint Studio canvas - From the properties panel of any connector or module that supports global elements ### From the Anypoint Studio Canvas 1. In the Anypoint Studio visual editor, click the **Global Elements** tab to access a list of all global elements in an application: ![A menu for creating and managing global configuration elements in Mule](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-new-global-element.png) 2. Click **Create** to add a new global element. 3. In the **Choose Global Type** wizard, navigate the directories or use the filter to select the type of global element you want to create, and then click **OK**. 4. Define the configurable parameters of your global element in the **Global Element Properties** window. 5. Click **OK** to save. ### From the Properties Panel of a Connector or Module To create a new global element from within a local component you placed in your flow: 1. Click the component you want to create a global element for: ![A basic flow component setup with error handling](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-global-element-component.png) 2. In the properties panel, click the Add icon next to the **Connector Configuration**: ![An interface for creating a new global element in Mule](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-global-element-create.png) 3. Complete the required fields for the type of global element you want to create. ## See Also - [Global Configurations](https://docs.mulesoft.com/mule-runtime/latest/global-settings-configuration) --- product: Mule Runtime version: 4.11 --- # Graphically Construct a Mapping (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform Message component you can do the tasks below. When doing each, the necessary lines are added to the DataWeave code to describe the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this casts a line that joins them. ![A JSON input and output structure](/mulesoft/current/en-us/mule-runtime/4.11/_images/using-dataweave-in-studio-8e6e0.png) ## Map a Structure Drag a high-level structure that contains lists of elements or inner fields onto another in the output. This creates a shaded region covering all the mapped structure. Fields that have identical names in these structures are automatically mapped too. ![A list of items with fields including ItemID and DeliveryMethod](/mulesoft/current/en-us/mule-runtime/4.11/_images/using-dataweave-in-studio-6b171.png) ## Set a Fixed Value or Function 1. Double click on a field in the output tree. This adds a function icon ![Function icon](/mulesoft/current/en-us/mule-runtime/4.11/_images/using-dataweave-in-studio-66cdc.png) next to it. 2. A new line is added to the DataWeave code that assigns a default `null` value to the field. This line is highlighted. Change its value to anything you want. You can add: - A fixed string value by using " ". - A reference to an input field. - A DataWeave statement that includes functions. ## See Also - [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.11/transform-component-about) - [Workflow: Create a Mapping](https://docs.mulesoft.com/mule-runtime/4.11/transform-workflow-create-mapping-ui-studio) - [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.11/dataweave) --- product: Mule Runtime version: 4.12 --- # Graphically Construct a Mapping (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform Message component you can do the tasks below. When doing each, the necessary lines are added to the DataWeave code to describe the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this casts a line that joins them. ![A JSON input and output structure](/mulesoft/current/en-us/mule-runtime/4.12/_images/using-dataweave-in-studio-8e6e0.png) ## Map a Structure Drag a high-level structure that contains lists of elements or inner fields onto another in the output. This creates a shaded region covering all the mapped structure. Fields that have identical names in these structures are automatically mapped too. ![A list of items with fields including ItemID and DeliveryMethod](/mulesoft/current/en-us/mule-runtime/4.12/_images/using-dataweave-in-studio-6b171.png) ## Set a Fixed Value or Function 1. Double click on a field in the output tree. This adds a function icon ![Function icon](/mulesoft/current/en-us/mule-runtime/4.12/_images/using-dataweave-in-studio-66cdc.png) next to it. 2. A new line is added to the DataWeave code that assigns a default `null` value to the field. This line is highlighted. Change its value to anything you want. You can add: - A fixed string value by using " ". - A reference to an input field. - A DataWeave statement that includes functions. ## See Also - [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.12/transform-component-about) - [Workflow: Create a Mapping](https://docs.mulesoft.com/mule-runtime/4.12/transform-workflow-create-mapping-ui-studio) - [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.12/dataweave) --- product: Mule Runtime version: 4.3 --- # Graphically Construct a Mapping (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform Message component you can do the tasks below. When doing each, the necessary lines are added to the DataWeave code to describe the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this casts a line that joins them. ![using dataweave in studio 8e6e0](/mulesoft/current/en-us/mule-runtime/4.3/_images/using-dataweave-in-studio-8e6e0.png) ## Map a Structure Drag a high-level structure that contains lists of elements or inner fields onto another in the output. This creates a shaded region covering all the mapped structure. Fields that have identical names in these structures are automatically mapped too. ![using dataweave in studio 6b171](/mulesoft/current/en-us/mule-runtime/4.3/_images/using-dataweave-in-studio-6b171.png) ## Set a Fixed Value or Function 1. Double click on a field in the output tree. This adds a function icon ![using dataweave in studio 66cdc](/mulesoft/current/en-us/mule-runtime/4.3/_images/using-dataweave-in-studio-66cdc.png) next to it. 2. A new line is added to the DataWeave code that assigns a default `null` value to the field. This line is highlighted. Change its value to anything you want. You can add: - A fixed string value by using " ". - A reference to an input field. - A DataWeave statement that includes functions. ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.3/transform-component-about) [Workflow: Create a Mapping](https://docs.mulesoft.com/mule-runtime/4.3/transform-workflow-create-mapping-ui-studio) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) --- product: Mule Runtime version: 4.4 --- # Graphically Construct a Mapping (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform Message component you can do the tasks below. When doing each, the necessary lines are added to the DataWeave code to describe the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this casts a line that joins them. ![using dataweave in studio 8e6e0](/mulesoft/current/en-us/mule-runtime/4.4/_images/using-dataweave-in-studio-8e6e0.png) ## Map a Structure Drag a high-level structure that contains lists of elements or inner fields onto another in the output. This creates a shaded region covering all the mapped structure. Fields that have identical names in these structures are automatically mapped too. ![using dataweave in studio 6b171](/mulesoft/current/en-us/mule-runtime/4.4/_images/using-dataweave-in-studio-6b171.png) ## Set a Fixed Value or Function 1. Double click on a field in the output tree. This adds a function icon ![using dataweave in studio 66cdc](/mulesoft/current/en-us/mule-runtime/4.4/_images/using-dataweave-in-studio-66cdc.png) next to it. 2. A new line is added to the DataWeave code that assigns a default `null` value to the field. This line is highlighted. Change its value to anything you want. You can add: - A fixed string value by using " ". - A reference to an input field. - A DataWeave statement that includes functions. ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.4/transform-component-about) [Workflow: Create a Mapping](https://docs.mulesoft.com/mule-runtime/4.4/transform-workflow-create-mapping-ui-studio) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) --- product: Mule Runtime version: 4.6 --- # Graphically Construct a Mapping (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform Message component you can do the tasks below. When doing each, the necessary lines are added to the DataWeave code to describe the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this casts a line that joins them. ![using dataweave in studio 8e6e0](/mulesoft/current/en-us/mule-runtime/4.6/_images/using-dataweave-in-studio-8e6e0.png) ## Map a Structure Drag a high-level structure that contains lists of elements or inner fields onto another in the output. This creates a shaded region covering all the mapped structure. Fields that have identical names in these structures are automatically mapped too. ![using dataweave in studio 6b171](/mulesoft/current/en-us/mule-runtime/4.6/_images/using-dataweave-in-studio-6b171.png) ## Set a Fixed Value or Function 1. Double click on a field in the output tree. This adds a function icon ![using dataweave in studio 66cdc](/mulesoft/current/en-us/mule-runtime/4.6/_images/using-dataweave-in-studio-66cdc.png) next to it. 2. A new line is added to the DataWeave code that assigns a default `null` value to the field. This line is highlighted. Change its value to anything you want. You can add: - A fixed string value by using " ". - A reference to an input field. - A DataWeave statement that includes functions. ## See Also [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.6/transform-component-about) [Workflow: Create a Mapping](https://docs.mulesoft.com/mule-runtime/4.6/transform-workflow-create-mapping-ui-studio) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.6/dataweave) --- product: Mule Runtime version: 4.9 --- # Graphically Construct a Mapping (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform Message component you can do the tasks below. When doing each, the necessary lines are added to the DataWeave code to describe the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this casts a line that joins them. ![A JSON input and output structure](/mulesoft/current/en-us/mule-runtime/4.9/_images/using-dataweave-in-studio-8e6e0.png) ## Map a Structure Drag a high-level structure that contains lists of elements or inner fields onto another in the output. This creates a shaded region covering all the mapped structure. Fields that have identical names in these structures are automatically mapped too. ![A list of items with fields including ItemID and DeliveryMethod](/mulesoft/current/en-us/mule-runtime/4.9/_images/using-dataweave-in-studio-6b171.png) ## Set a Fixed Value or Function 1. Double click on a field in the output tree. This adds a function icon ![Function icon](/mulesoft/current/en-us/mule-runtime/4.9/_images/using-dataweave-in-studio-66cdc.png) next to it. 2. A new line is added to the DataWeave code that assigns a default `null` value to the field. This line is highlighted. Change its value to anything you want. You can add: - A fixed string value by using " ". - A reference to an input field. - A DataWeave statement that includes functions. ## See Also - [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.9/transform-component-about) - [Workflow: Create a Mapping](https://docs.mulesoft.com/mule-runtime/4.9/transform-workflow-create-mapping-ui-studio) - [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.9/dataweave) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Graphically Construct a Mapping (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform Message component you can do the tasks below. When doing each, the necessary lines are added to the DataWeave code to describe the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this casts a line that joins them. ![A JSON input and output structure](/mulesoft/current/en-us/mule-runtime/latest/_images/using-dataweave-in-studio-8e6e0.png) ## Map a Structure Drag a high-level structure that contains lists of elements or inner fields onto another in the output. This creates a shaded region covering all the mapped structure. Fields that have identical names in these structures are automatically mapped too. ![A list of items with fields including ItemID and DeliveryMethod](/mulesoft/current/en-us/mule-runtime/latest/_images/using-dataweave-in-studio-6b171.png) ## Set a Fixed Value or Function 1. Double click on a field in the output tree. This adds a function icon ![Function icon](/mulesoft/current/en-us/mule-runtime/latest/_images/using-dataweave-in-studio-66cdc.png) next to it. 2. A new line is added to the DataWeave code that assigns a default `null` value to the field. This line is highlighted. Change its value to anything you want. You can add: - A fixed string value by using " ". - A reference to an input field. - A DataWeave statement that includes functions. ## See Also - [Transform Message Component](https://docs.mulesoft.com/mule-runtime/latest/transform-component-about) - [Workflow: Create a Mapping](https://docs.mulesoft.com/mule-runtime/latest/transform-workflow-create-mapping-ui-studio) - [DataWeave Language](https://docs.mulesoft.com/mule-runtime/latest/dataweave) --- product: Mule Runtime version: 4.11 --- # Graphically Construct a Mapping (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform component you can do the tasks below. Each task will produce the DataWeave source code that describes the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this action creates a line that joins these two elements. ![A transformation flow from item type and price in a payload](/mulesoft/current/en-us/mule-runtime/4.11/_images/to-transform-data-c2fc6.png) ![A table with properties for title, author, item, and year](/mulesoft/current/en-us/mule-runtime/4.11/_images/to-transform-data-afe5b.png) ## Remove a Mapping 1. Select the corresponding input element. A trash can icon ![Delete icon](/mulesoft/current/en-us/mule-runtime/4.11/_images/graphically-construct-mapping-design-center-task-2457b.png) appears on the connection. 2. Click the trash can icon. ## Set a Fixed Value or Function 1. Double click on a field (that doesn’t have any children) in the output tree. This adds a function icon ![Function icon](/mulesoft/current/en-us/mule-runtime/4.11/_images/graphically-construct-mapping-design-center-task-8a822.png) next to it. 2. A box with the default value `null` appears. You can change `null` to anything you want, such as: - A fixed text value by using " ". - A reference to an input field. - A statement that includes DataWeave functions. This experience relates to that of using a spreadsheet, where each field can be a direct reference to another field, or can be the product of a function that involves such references. > [!NOTE] Functions can be removed by clicking on the trash-can icons that appear next to them. ## See Also [DataWeave Function Reference](https://docs.mulesoft.com/dataweave/latest/dw-functions) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.11/dataweave) --- product: Mule Runtime version: 4.12 --- # Graphically Construct a Mapping (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform component you can do the tasks below. Each task will produce the DataWeave source code that describes the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this action creates a line that joins these two elements. ![A transformation flow from item type and price in a payload](/mulesoft/current/en-us/mule-runtime/4.12/_images/to-transform-data-c2fc6.png) ![A table with properties for title, author, item, and year](/mulesoft/current/en-us/mule-runtime/4.12/_images/to-transform-data-afe5b.png) ## Remove a Mapping 1. Select the corresponding input element. A trash can icon ![Delete icon](/mulesoft/current/en-us/mule-runtime/4.12/_images/graphically-construct-mapping-design-center-task-2457b.png) appears on the connection. 2. Click the trash can icon. ## Set a Fixed Value or Function 1. Double click on a field (that doesn’t have any children) in the output tree. This adds a function icon ![Function icon](/mulesoft/current/en-us/mule-runtime/4.12/_images/graphically-construct-mapping-design-center-task-8a822.png) next to it. 2. A box with the default value `null` appears. You can change `null` to anything you want, such as: - A fixed text value by using " ". - A reference to an input field. - A statement that includes DataWeave functions. This experience relates to that of using a spreadsheet, where each field can be a direct reference to another field, or can be the product of a function that involves such references. > [!NOTE] Functions can be removed by clicking on the trash-can icons that appear next to them. ## See Also [DataWeave Function Reference](https://docs.mulesoft.com/dataweave/latest/dw-functions) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.12/dataweave) --- product: Mule Runtime version: 4.3 --- # Graphically Construct a Mapping (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform component you can do the tasks below. Each task will produce the DataWeave source code that describes the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this action creates a line that joins these two elements. ![to transform data c2fc6](/mulesoft/current/en-us/mule-runtime/4.3/_images/to-transform-data-c2fc6.png) ![to transform data afe5b](/mulesoft/current/en-us/mule-runtime/4.3/_images/to-transform-data-afe5b.png) ## Remove a Mapping 1. Select the corresponding input element. A trash can icon ![graphically construct mapping design center task 2457b](/mulesoft/current/en-us/mule-runtime/4.3/_images/graphically-construct-mapping-design-center-task-2457b.png) appears on the connection. 2. Click the trash can icon. ## Set a Fixed Value or Function 1. Double click on a field (that doesn’t have any children) in the output tree. This adds a function icon ![graphically construct mapping design center task 8a822](/mulesoft/current/en-us/mule-runtime/4.3/_images/graphically-construct-mapping-design-center-task-8a822.png) next to it. 2. A box with the default value `null` appears. You can change `null` to anything you want, such as: - A fixed text value by using " ". - A reference to an input field. - A statement that includes DataWeave functions. This experience relates to that of using a spreadsheet, where each field can be a direct reference to another field, or can be the product of a function that involves such references. > [!NOTE] Functions can be removed by clicking on the trash-can icons that appear next to them. ## See Also [DataWeave Function Reference](https://docs.mulesoft.com/dataweave/2.3/dw-functions) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) --- product: Mule Runtime version: 4.4 --- # Graphically Construct a Mapping (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform component you can do the tasks below. Each task will produce the DataWeave source code that describes the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this action creates a line that joins these two elements. ![to transform data c2fc6](/mulesoft/current/en-us/mule-runtime/4.4/_images/to-transform-data-c2fc6.png) ![to transform data afe5b](/mulesoft/current/en-us/mule-runtime/4.4/_images/to-transform-data-afe5b.png) ## Remove a Mapping 1. Select the corresponding input element. A trash can icon ![graphically construct mapping design center task 2457b](/mulesoft/current/en-us/mule-runtime/4.4/_images/graphically-construct-mapping-design-center-task-2457b.png) appears on the connection. 2. Click the trash can icon. ## Set a Fixed Value or Function 1. Double click on a field (that doesn’t have any children) in the output tree. This adds a function icon ![graphically construct mapping design center task 8a822](/mulesoft/current/en-us/mule-runtime/4.4/_images/graphically-construct-mapping-design-center-task-8a822.png) next to it. 2. A box with the default value `null` appears. You can change `null` to anything you want, such as: - A fixed text value by using " ". - A reference to an input field. - A statement that includes DataWeave functions. This experience relates to that of using a spreadsheet, where each field can be a direct reference to another field, or can be the product of a function that involves such references. > [!NOTE] Functions can be removed by clicking on the trash-can icons that appear next to them. ## See Also [DataWeave Function Reference](https://docs.mulesoft.com/dataweave/latest/dw-functions) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) --- product: Mule Runtime version: 4.6 --- # Graphically Construct a Mapping (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform component you can do the tasks below. Each task will produce the DataWeave source code that describes the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this action creates a line that joins these two elements. ![to transform data c2fc6](/mulesoft/current/en-us/mule-runtime/4.6/_images/to-transform-data-c2fc6.png) ![to transform data afe5b](/mulesoft/current/en-us/mule-runtime/4.6/_images/to-transform-data-afe5b.png) ## Remove a Mapping 1. Select the corresponding input element. A trash can icon ![graphically construct mapping design center task 2457b](/mulesoft/current/en-us/mule-runtime/4.6/_images/graphically-construct-mapping-design-center-task-2457b.png) appears on the connection. 2. Click the trash can icon. ## Set a Fixed Value or Function 1. Double click on a field (that doesn’t have any children) in the output tree. This adds a function icon ![graphically construct mapping design center task 8a822](/mulesoft/current/en-us/mule-runtime/4.6/_images/graphically-construct-mapping-design-center-task-8a822.png) next to it. 2. A box with the default value `null` appears. You can change `null` to anything you want, such as: - A fixed text value by using " ". - A reference to an input field. - A statement that includes DataWeave functions. This experience relates to that of using a spreadsheet, where each field can be a direct reference to another field, or can be the product of a function that involves such references. > [!NOTE] Functions can be removed by clicking on the trash-can icons that appear next to them. ## See Also [DataWeave Function Reference](https://docs.mulesoft.com/dataweave/latest/dw-functions) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.6/dataweave) --- product: Mule Runtime version: 4.9 --- # Graphically Construct a Mapping (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform component you can do the tasks below. Each task will produce the DataWeave source code that describes the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this action creates a line that joins these two elements. ![A transformation flow from item type and price in a payload](/mulesoft/current/en-us/mule-runtime/4.9/_images/to-transform-data-c2fc6.png) ![A table with properties for title, author, item, and year](/mulesoft/current/en-us/mule-runtime/4.9/_images/to-transform-data-afe5b.png) ## Remove a Mapping 1. Select the corresponding input element. A trash can icon ![Delete icon](/mulesoft/current/en-us/mule-runtime/4.9/_images/graphically-construct-mapping-design-center-task-2457b.png) appears on the connection. 2. Click the trash can icon. ## Set a Fixed Value or Function 1. Double click on a field (that doesn’t have any children) in the output tree. This adds a function icon ![Function icon](/mulesoft/current/en-us/mule-runtime/4.9/_images/graphically-construct-mapping-design-center-task-8a822.png) next to it. 2. A box with the default value `null` appears. You can change `null` to anything you want, such as: - A fixed text value by using " ". - A reference to an input field. - A statement that includes DataWeave functions. This experience relates to that of using a spreadsheet, where each field can be a direct reference to another field, or can be the product of a function that involves such references. > [!NOTE] Functions can be removed by clicking on the trash-can icons that appear next to them. ## See Also [DataWeave Function Reference](https://docs.mulesoft.com/dataweave/latest/dw-functions) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.9/dataweave) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Graphically Construct a Mapping (Design Center) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Through the graphical UI of the Transform component you can do the tasks below. Each task will produce the DataWeave source code that describes the action. ## Map a Field Drag an element on the input structure over to another on the output structure, this action creates a line that joins these two elements. ![A transformation flow from item type and price in a payload](/mulesoft/current/en-us/mule-runtime/latest/_images/to-transform-data-c2fc6.png) ![A table with properties for title, author, item, and year](/mulesoft/current/en-us/mule-runtime/latest/_images/to-transform-data-afe5b.png) ## Remove a Mapping 1. Select the corresponding input element. A trash can icon ![Delete icon](/mulesoft/current/en-us/mule-runtime/latest/_images/graphically-construct-mapping-design-center-task-2457b.png) appears on the connection. 2. Click the trash can icon. ## Set a Fixed Value or Function 1. Double click on a field (that doesn’t have any children) in the output tree. This adds a function icon ![Function icon](/mulesoft/current/en-us/mule-runtime/latest/_images/graphically-construct-mapping-design-center-task-8a822.png) next to it. 2. A box with the default value `null` appears. You can change `null` to anything you want, such as: - A fixed text value by using " ". - A reference to an input field. - A statement that includes DataWeave functions. This experience relates to that of using a spreadsheet, where each field can be a direct reference to another field, or can be the product of a function that involves such references. > [!NOTE] Functions can be removed by clicking on the trash-can icons that appear next to them. ## See Also [DataWeave Function Reference](https://docs.mulesoft.com/dataweave/latest/dw-functions) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/latest/dataweave) --- product: Mule Runtime version: 4.11 --- # Handling Errors During Batch Job > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Handle record-level failures in Mule batch jobs while balancing logging detail and performance. Learn how batch steps log errors, how failed records propagate through a job, and how to inspect errors by using DataWeave functions. Batch jobs capture record-level failures during batch step execution. For details about the error representation and how to access error fields, see [Batch Errors](https://docs.mulesoft.com/mule-runtime/4.11/batch-error-concept). Mule batch processing is designed to handle large data sets and to perform almost real-time data integration that recovers from crashes and continues processing a job from a point of failure. However, _verbose_ logs for issues that occur in large data sets can become enormous and severely impact performance. To limit this impact, Mule uses INFO-level logging by default, as described in [Logs of Failing Records Inside a Batch Step](#default_logging). For cases in which you require more verbose log messages, you can change the mode to DEBUG. This mode is helpful for debugging and is feasible for some cases that involve smaller data sets. Set the logging mode with this property: ```xml ``` If you’re using CloudHub or Runtime Manager, you can add this package to the Logs tab in DEBUG level: ```logs com.mulesoft.mule.runtime.module.batch ``` Avoid using the DEBUG mode in a production environment when processing large data sets. > [!NOTE] Starting with Mule 4.11, batch error handling relies on `BatchError` objects instead of > exceptions. ## Logs of Failing Records Inside a Batch Step When processing a batch job instance, a processor inside a batch step can fail or raise an error, for example, because of corrupted or incomplete record data. By default, Mule uses the INFO log level to log stack traces according to this logic when issues occur: 1. Mule gets the exception’s full stack trace. 2. Mule strips the stack trace from error messages in the log. Even if all records raise the same error, the messages being processed would probably contain specific information related to those records. For example, if you push leads to a Salesforce account and one record fails because the lead was uploaded, another repeated lead would have different record information, but the error is the same. 3. Mule verifies if the stack trace was already logged in the current step. The first time the runtime encounters this error, Mule logs the error and produces a message like this one: ```logs com.mulesoft.mule.runtime.module.batch.internal.DefaultBatchStep: Found error processing record on step 'batchStep1' for job instance 'Batch Job Example' of job 'CreateLeadsBatch'. This is the first record to show this error on this step for this job instance. Subsequent records with the same failures will not be logged for performance and log readability reasons: ``` Mule logs on a "by step" basis. If another step also raises the same error, the runtime logs it again for that step. 4. When the batch job reaches the On Complete phase, Mule displays an error summary with every error type and the number of occurrences in each batch step. The error summary for a batch job with two batch steps that raised an `APP:FAILURE` error: ```logs ******************************************************************************* * - - + Error Type + - - * - - + Step + - - * - - + Count + - - * ******************************************************************************* * APP:FAILURE * batchStep1 * 10 * * APP:FAILURE * batchStep2 * 9 * ******************************************************************************* ``` Here, the first step failed ten times and the second failed nine. Mule logs batch errors using this behavior as its default configuration, which only logs INFO level messages to get a balanced trade-off between logging efficiency for large chunks of data. However, your motivation to use batch processing might not be its ability to handle large datasets, but its capacity to recover from a crash and keep processing a batch job from where it was left off when performing "near real-time" data integration. Or you may need more verbose log levels for debugging. ## DataWeave Functions for Error Handling Mule 4.x includes a set of DataWeave functions that you can use in the context of a batch step.
DataWeave FunctionDescription

#[Batch::isSuccessfulRecord()]

A boolean function that returns true if the current record hasn’t presented errors in any prior step.

#[Batch::isFailedRecord()]

A boolean function that returns true if the current record has presented errors in any prior step.

#[Batch::failureErrorForStep(String)]

Receives the name of a step as a String argument. If the current record presented an error on that step, it returns the BatchError object. Otherwise, returns null.

#[Batch::getStepErrors()]

Returns a Map<String, BatchError> in which the keys are the name of a batch step in which the current record has failed, and the value is the error itself.
If the record hasn’t failed in any step, this map is empty but never null. The map contains no entries for steps in which the record hasn’t failed.

#[Batch::getFirstError()]

Returns the BatchError for the first step in which the current record has failed. If the record hasn’t failed in any step, returns null.

#[Batch::getLastError()]

Returns the BatchError for the last step in which the current record has failed. If the record hasn’t failed in any step, returns null.

There are also bindings to work with the old batch error handling mechanism, which relied on exceptions rather than `BatchError` objects.
DataWeave FunctionDescription

#[Batch::failureExceptionForStep(String)]

Receives the name of a step as a String argument. If the current record throws an exception on that step, it returns the Exception object. Otherwise, returns null.

#[Batch::getStepExceptions()]

Returns a Java Map<String, Exception> in which the keys are the name of a batch step in which the current record has failed, and the value is the exception itself.
If the record hasn’t failed in any step, this map is empty but never null. The map contains no entries for steps in which the record hasn’t failed.

#[Batch::getFirstException()]

Returns the Exception for the first step in which the current record has failed. If the record hasn’t failed in any step, returns null.

#[Batch::getLastException()]

Returns the Exception for the last step in which the current record has failed. If the record hasn’t failed in any step, returns null.

### Example Consider a batch job that polls files containing contact information: - In the first step, the batch job aggregates the contact information and transforms it using the Transform Message component, then pushes the data to Salesforce. - In the second step, the job transforms the same contacts again to match the data structure of another third-party contacts application (such as Google Contacts) and pushes them to this service using an HTTP request. - In the third step, you write into a JMS dead-letter queue for each record that has failed. The message content is the error itself. Each record could have failed in both steps, meaning the same record translates into two JMS messages. Such an application would look like this: ![A flow showing a batch process for lead management with detailed steps and error handling in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/batch-error-handling-faq-f34d5.png) Since the goal is to gather failures, it makes sense to configure the `Failures` step with an ONLY\_FAILURES filter (see [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.11/batch-filters-and-batch-aggregator) for more details about batch filters). The set-payload processor in this step can be configured to use the `Batch::getStepErrors()` function. ![A Set Payload component with a value expression related to batch errors in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/batch-error-handling-faq-6269e.png) This function returns a map with all errors found in all steps. To send the errors through JMS, use a For Each scope to iterate over the map’s values (the errors) and send them through a JMS outbound endpoint: ![A For Each component processing error in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/batch-error-handling-faq-b822e.png) ## Batch Processing Strategies for Error Handling Mule has three options for handling a record-level error: 1. **Finish processing** Stop the execution of the current job instance. Finish the execution of the records currently in-flight, but do not pull any more records from the queues and set the job instance into a `FAILURE` state. The On Complete phase is invoked. 2. **Continue processing** the batch regardless of any failed records, using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records. 3. **Continue processing** the batch regardless of any failed records (using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records), until the batch job accumulates a **maximum number of failed records** at which point the execution will halt just like in option 1. By default, Mule batch jobs follow the first error handling strategy, which halts the batch instance execution. This behavior is controlled through the `maxFailedRecords` attribute.
Failed Record Handling OptionBatch Job AttributeValue

Stops processing when a failed record is found

maxFailedRecords

0

Continues processing indefinitely, regardless of the number of failed records

maxFailedRecords

-1

Continues processing until reaching the maximum number of failed records

maxFailedRecords

integer

```xml ``` ### Crossing the Max Failed Threshold When a batch job accumulates enough failed records to cross the `maxFailedRecords` threshold, Mule aborts processing for any remaining batch steps, skipping directly to the On Complete phase. For example, if you set the value of `maxFailedRecords` to "10" and a batch job accumulates ten failed records in the first of three batch steps, Mule does not attempt to process the batch through the remaining two batch steps. Instead, it aborts further processing and skips directly to On Complete to report on the batch job failure. If a batch job _does not_ accumulate enough failed records to cross the `maxFailedRecords` threshold, _all_ records – successes and failures – continue to flow from batch step to batch step; use filters to control which records each batch step processes. ## See Also - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.11/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.12 --- # Handling Errors During Batch Job > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Handle record-level failures in Mule batch jobs while balancing logging detail and performance. Learn how batch steps log errors, how failed records propagate through a job, and how to inspect errors by using DataWeave functions. Batch jobs capture record-level failures during batch step execution. For details about the error representation and how to access error fields, see [Batch Errors](https://docs.mulesoft.com/mule-runtime/4.12/batch-error-concept). Mule batch processing is designed to handle large data sets and to perform almost real-time data integration that recovers from crashes and continues processing a job from a point of failure. However, _verbose_ logs for issues that occur in large data sets can become enormous and severely impact performance. To limit this impact, Mule uses INFO-level logging by default, as described in [Logs of Failing Records Inside a Batch Step](#default_logging). For cases in which you require more verbose log messages, you can change the mode to DEBUG. This mode is helpful for debugging and is feasible for some cases that involve smaller data sets. Set the logging mode with this property: ```xml ``` If you’re using CloudHub or Runtime Manager, you can add this package to the Logs tab in DEBUG level: ```logs com.mulesoft.mule.runtime.module.batch ``` Avoid using the DEBUG mode in a production environment when processing large data sets. > [!NOTE] Starting with Mule 4.11, batch error handling relies on `BatchError` objects instead of > exceptions. ## Logs of Failing Records Inside a Batch Step When processing a batch job instance, a processor inside a batch step can fail or raise an error, for example, because of corrupted or incomplete record data. By default, Mule uses the INFO log level to log stack traces according to this logic when issues occur: 1. Mule gets the exception’s full stack trace. 2. Mule strips the stack trace from error messages in the log. Even if all records raise the same error, the messages being processed would probably contain specific information related to those records. For example, if you push leads to a Salesforce account and one record fails because the lead was uploaded, another repeated lead would have different record information, but the error is the same. 3. Mule verifies if the stack trace was already logged in the current step. The first time the runtime encounters this error, Mule logs the error and produces a message like this one: ```logs com.mulesoft.mule.runtime.module.batch.internal.DefaultBatchStep: Found error processing record on step 'batchStep1' for job instance 'Batch Job Example' of job 'CreateLeadsBatch'. This is the first record to show this error on this step for this job instance. Subsequent records with the same failures will not be logged for performance and log readability reasons: ``` Mule logs on a "by step" basis. If another step also raises the same error, the runtime logs it again for that step. 4. When the batch job reaches the On Complete phase, Mule displays an error summary with every error type and the number of occurrences in each batch step. The error summary for a batch job with two batch steps that raised an `APP:FAILURE` error: ```logs ******************************************************************************* * - - + Error Type + - - * - - + Step + - - * - - + Count + - - * ******************************************************************************* * APP:FAILURE * batchStep1 * 10 * * APP:FAILURE * batchStep2 * 9 * ******************************************************************************* ``` Here, the first step failed ten times and the second failed nine. Mule logs batch errors using this behavior as its default configuration, which only logs INFO level messages to get a balanced trade-off between logging efficiency for large chunks of data. However, your motivation to use batch processing might not be its ability to handle large datasets, but its capacity to recover from a crash and keep processing a batch job from where it was left off when performing "near real-time" data integration. Or you may need more verbose log levels for debugging. ## DataWeave Functions for Error Handling Mule 4.x includes a set of DataWeave functions that you can use in the context of a batch step.
DataWeave FunctionDescription

#[Batch::isSuccessfulRecord()]

A boolean function that returns true if the current record hasn’t presented errors in any prior step.

#[Batch::isFailedRecord()]

A boolean function that returns true if the current record has presented errors in any prior step.

#[Batch::failureErrorForStep(String)]

Receives the name of a step as a String argument. If the current record presented an error on that step, it returns the BatchError object. Otherwise, returns null.

#[Batch::getStepErrors()]

Returns a Map<String, BatchError> in which the keys are the name of a batch step in which the current record has failed, and the value is the error itself.
If the record hasn’t failed in any step, this map is empty but never null. The map contains no entries for steps in which the record hasn’t failed.

#[Batch::getFirstError()]

Returns the BatchError for the first step in which the current record has failed. If the record hasn’t failed in any step, returns null.

#[Batch::getLastError()]

Returns the BatchError for the last step in which the current record has failed. If the record hasn’t failed in any step, returns null.

There are also bindings to work with the old batch error handling mechanism, which relied on exceptions rather than `BatchError` objects.
DataWeave FunctionDescription

#[Batch::failureExceptionForStep(String)]

Receives the name of a step as a String argument. If the current record throws an exception on that step, it returns the Exception object. Otherwise, returns null.

#[Batch::getStepExceptions()]

Returns a Java Map<String, Exception> in which the keys are the name of a batch step in which the current record has failed, and the value is the exception itself.
If the record hasn’t failed in any step, this map is empty but never null. The map contains no entries for steps in which the record hasn’t failed.

#[Batch::getFirstException()]

Returns the Exception for the first step in which the current record has failed. If the record hasn’t failed in any step, returns null.

#[Batch::getLastException()]

Returns the Exception for the last step in which the current record has failed. If the record hasn’t failed in any step, returns null.

### Example Consider a batch job that polls files containing contact information: - In the first step, the batch job aggregates the contact information and transforms it using the Transform Message component, then pushes the data to Salesforce. - In the second step, the job transforms the same contacts again to match the data structure of another third-party contacts application (such as Google Contacts) and pushes them to this service using an HTTP request. - In the third step, you write into a JMS dead-letter queue for each record that has failed. The message content is the error itself. Each record could have failed in both steps, meaning the same record translates into two JMS messages. Such an application would look like this: ![A flow showing a batch process for lead management with detailed steps and error handling in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/batch-error-handling-faq-f34d5.png) Since the goal is to gather failures, it makes sense to configure the `Failures` step with an ONLY\_FAILURES filter (see [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.12/batch-filters-and-batch-aggregator) for more details about batch filters). The set-payload processor in this step can be configured to use the `Batch::getStepErrors()` function. ![A Set Payload component with a value expression related to batch errors in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/batch-error-handling-faq-6269e.png) This function returns a map with all errors found in all steps. To send the errors through JMS, use a For Each scope to iterate over the map’s values (the errors) and send them through a JMS outbound endpoint: ![A For Each component processing error in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/batch-error-handling-faq-b822e.png) ## Batch Processing Strategies for Error Handling Mule has three options for handling a record-level error: 1. **Finish processing** Stop the execution of the current job instance. Finish the execution of the records currently in-flight, but do not pull any more records from the queues and set the job instance into a `FAILURE` state. The On Complete phase is invoked. 2. **Continue processing** the batch regardless of any failed records, using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records. 3. **Continue processing** the batch regardless of any failed records (using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records), until the batch job accumulates a **maximum number of failed records** at which point the execution will halt just like in option 1. By default, Mule batch jobs follow the first error handling strategy, which halts the batch instance execution. This behavior is controlled through the `maxFailedRecords` attribute.
Failed Record Handling OptionBatch Job AttributeValue

Stops processing when a failed record is found

maxFailedRecords

0

Continues processing indefinitely, regardless of the number of failed records

maxFailedRecords

-1

Continues processing until reaching the maximum number of failed records

maxFailedRecords

integer

```xml ``` ### Crossing the Max Failed Threshold When a batch job accumulates enough failed records to cross the `maxFailedRecords` threshold, Mule aborts processing for any remaining batch steps, skipping directly to the On Complete phase. For example, if you set the value of `maxFailedRecords` to "10" and a batch job accumulates ten failed records in the first of three batch steps, Mule does not attempt to process the batch through the remaining two batch steps. Instead, it aborts further processing and skips directly to On Complete to report on the batch job failure. If a batch job _does not_ accumulate enough failed records to cross the `maxFailedRecords` threshold, _all_ records – successes and failures – continue to flow from batch step to batch step; use filters to control which records each batch step processes. ## See Also - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.12/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.4 --- # Handling Errors During Batch Job > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch processing is designed to handle very large data sets and to perform almost real-time data integration that recovers from crashes and continues processing a job from a point of failure. However, _verbose_ logs for issues that occur in large data sets can become enormous and severely impact performance. To limit this impact, Mule uses INFO-level logging by default, as described in [Logs of Failing Records Inside a Batch Step](#default_logging). For cases in which you require more verbose log messages, you can change the mode to DEBUG. This mode is helpful for debugging and is feasible for some cases that involve smaller data sets. The following property is available for setting the logging mode: ```xml ``` If you are using CloudHub or Runtime Manager, you can add the following package to the Logs tab in DEBUG level: ```logs com.mulesoft.mule.runtime.module.batch ``` Avoid using the DEBUG mode in a production environment when processing very large data sets. ## Logs of Failing Records Inside a Batch Step When processing a batch job instance, a processor inside a batch step can fail or raise an error, for example, because of corrupted or incomplete record data. By default, Mule uses the INFO log level to log stack traces according to the following logic when issues occur: 1. Mule gets the exception’s full stack trace. 2. Mule strips the stack trace from error messages in the log. Even if all records raise the same error, the messages being processed would probably contain specific information related to those records. For example, if I’m pushing leads to my Salesforce account and one record fails because the lead was already uploaded, another repeated lead would have different record information, but the error is the same. 3. Mule verifies if the stack trace was already logged in the current step. The first time the runtime encounters this error, Mule logs the error and produces a message like this one: ```logs com.mulesoft.mule.runtime.module.batch.internal.DefaultBatchStep: Found exception processing record on step 'batchStep1' for job instance 'Batch Job Example' of job 'CreateLeadsBatch'. This is the first record to show this exception on this step for this job instance. Subsequent records with the same failures will not be logged for performance and log readability reasons: ``` Mule logs on a "by step" basis. If another step also raises the same error, the runtime logs it again for that step. 4. When the batch job reaches the On Complete phase, Mule displays an error summary with every error type and the number of occurrences in each batch step. The error summary for a batch job with two batch steps that raised a `batch.exception` type: ```logs ******************************************************************************* * - - + Exception Type + - - * - - + Step + - - * - - + Count + - - * ******************************************************************************* * com.mulesoft.mule.runtime.module.batch.exception.B * batchStep1 * 10 * * com.mulesoft.mule.runtime.module.batch.exception.B * batchStep2 * 9 * ******************************************************************************* ``` Here, the first step failed ten times and the second failed nine. Mule logs batch errors using this behavior as its default configuration, which only logs INFO level messages to get a balanced trade-off between logging efficiency for large chunks of data. However, your motivation to use batch processing might not be its ability to handle large datasets, but its capacity to recover from a crash and keep processing a batch job from where it was left off when performing "near real-time" data integration. Or you may need more verbose log levels for debugging. ## DataWeave Functions for Error Handling Mule 4.x includes a set of DataWeave functions that you can use in the context of a batch step.
DataWeave FunctionDescription

#[Batch::isSuccessfulRecord()]

A boolean function that returns true if the current record has not thrown exceptions in any prior step.

#[Batch::isFailedRecord()]

A boolean function that returns true if the current record has thrown exceptions in any prior step.

#[Batch::failureExceptionForStep(String)]

Receives the name of a step as a String argument. If the current record threw exception on that step, then it returns the actual Exception object. Otherwise it returns null

#[Batch::getStepExceptions()]

Returns a java Map<String, Exception> in which the keys are the name of a batch step in which the current record has failed, and the value is the exception itself.
If the record hasn’t failed in any step, this Map will be empty but will never be null. Also, the Map contains no entries for steps in which the record hasn’t failed.

#[Batch::getFirstException()]

Returns the Exception for the very first step in which the current record has failed. If the record hasn’t failed in any step, then it returns null.

#[Batch::getLastException()]

Returns the Exception for the last step in which the current record has failed. If the record hasn’t failed in any step, then it returns null.

### Example Imagine a batch job that polls files containing contact information. In the first step, the batch job aggregates the contacts information and transforms them using the Transform Message component to then being pushed to Salesforce. In the second step, the job transforms the same contacts again to match the data structure of another third-party contacts application (say, Google Contacts for example) and pushes them to this service using HTTP request. Now, assume that as a third step, you need to be able to write into a JMS dead-letter queue per each record that has failed. To keep it simple, let’s say that the message will be the exception itself. This requirement holds a trick: each record could have failed in both steps, which means that the same record would translate into two JMS messages. Such an application would look like this: ![batch error handling faq f34d5](/mulesoft/current/en-us/mule-runtime/4.4/_images/batch-error-handling-faq-f34d5.png) Since the goal is to gather failures, it makes sense to configure the `Failures` step with an ONLY\_FAILURES filter (see [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.4/batch-filters-and-batch-aggregator) for more details about batch filters). The set-payload processor in this step can be configured to use the `Batch::getStepExceptions()` function. ![batch error handling faq 6269e](/mulesoft/current/en-us/mule-runtime/4.4/_images/batch-error-handling-faq-6269e.png) As stated above, this function returns a map with all errors found in all steps. And since our goal is to send the exceptions through JMS and we don’t care about the steps, we can use a foreach scope to iterate over the map’s values (the errors) and send them through a JMS outbound endpoint: ![batch error handling faq b822e](/mulesoft/current/en-us/mule-runtime/4.4/_images/batch-error-handling-faq-b822e.png) ## Batch Processing Strategies for Error Handling Mule has three options for handling a record-level error: 1. **Finish processing** Stop the execution of the current job instance. Finish the execution of the records currently in-flight, but do not pull any more records from the queues and set the job instance into a `FAILURE` state. The On Complete phase is invoked. 2. **Continue processing** the batch regardless of any failed records, using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records. 3. **Continue processing** the batch regardless of any failed records (using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records), until the batch job accumulates a **maximum number of failed records** at which point the execution will halt just like in option 1. By default, Mule’s batch jobs follow the first error handling strategy which halts the batch instance execution. The above behavior is controlled through the `maxFailedRecords` attributes.
Failed Record Handling OptionBatch Job AttributeValue

Stops processing when a failed record is found

maxFailedRecords

0

Continues processing indefinitely, regardless of the number of failed records

maxFailedRecords

-1

Continues processing until reaching the maximum number of failed records

maxFailedRecords

integer

```xml ``` ### Crossing the Max Failed Threshold When a batch job accumulates enough failed records to cross the `maxFailedRecords` threshold, Mule aborts processing for any remaining batch steps, skipping directly to the On Complete phase. For example, if you set the value of `maxFailedRecords` to "10" and a batch job accumulates ten failed records in the first of three batch steps, Mule does not attempt to process the batch through the remaining two batch steps. Instead, it aborts further processing and skips directly to On Complete to report on the batch job failure. If a batch job _does not_ accumulate enough failed records to cross the `maxFailedRecords` threshold, _all_ records – successes and failures – continue to flow from batch step to batch step; use filters to control which records each batch step processes. ## See Also - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.4/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.6 --- # Handling Errors During Batch Job > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch processing is designed to handle very large data sets and to perform almost real-time data integration that recovers from crashes and continues processing a job from a point of failure. However, _verbose_ logs for issues that occur in large data sets can become enormous and severely impact performance. To limit this impact, Mule uses INFO-level logging by default, as described in [Logs of Failing Records Inside a Batch Step](#default_logging). For cases in which you require more verbose log messages, you can change the mode to DEBUG. This mode is helpful for debugging and is feasible for some cases that involve smaller data sets. The following property is available for setting the logging mode: ```xml ``` If you are using CloudHub or Runtime Manager, you can add the following package to the Logs tab in DEBUG level: ```logs com.mulesoft.mule.runtime.module.batch ``` Avoid using the DEBUG mode in a production environment when processing very large data sets. ## Logs of Failing Records Inside a Batch Step When processing a batch job instance, a processor inside a batch step can fail or raise an error, for example, because of corrupted or incomplete record data. By default, Mule uses the INFO log level to log stack traces according to the following logic when issues occur: 1. Mule gets the exception’s full stack trace. 2. Mule strips the stack trace from error messages in the log. Even if all records raise the same error, the messages being processed would probably contain specific information related to those records. For example, if I’m pushing leads to my Salesforce account and one record fails because the lead was already uploaded, another repeated lead would have different record information, but the error is the same. 3. Mule verifies if the stack trace was already logged in the current step. The first time the runtime encounters this error, Mule logs the error and produces a message like this one: ```logs com.mulesoft.mule.runtime.module.batch.internal.DefaultBatchStep: Found exception processing record on step 'batchStep1' for job instance 'Batch Job Example' of job 'CreateLeadsBatch'. This is the first record to show this exception on this step for this job instance. Subsequent records with the same failures will not be logged for performance and log readability reasons: ``` Mule logs on a "by step" basis. If another step also raises the same error, the runtime logs it again for that step. 4. When the batch job reaches the On Complete phase, Mule displays an error summary with every error type and the number of occurrences in each batch step. The error summary for a batch job with two batch steps that raised a `batch.exception` type: ```logs ******************************************************************************* * - - + Exception Type + - - * - - + Step + - - * - - + Count + - - * ******************************************************************************* * com.mulesoft.mule.runtime.module.batch.exception.B * batchStep1 * 10 * * com.mulesoft.mule.runtime.module.batch.exception.B * batchStep2 * 9 * ******************************************************************************* ``` Here, the first step failed ten times and the second failed nine. Mule logs batch errors using this behavior as its default configuration, which only logs INFO level messages to get a balanced trade-off between logging efficiency for large chunks of data. However, your motivation to use batch processing might not be its ability to handle large datasets, but its capacity to recover from a crash and keep processing a batch job from where it was left off when performing "near real-time" data integration. Or you may need more verbose log levels for debugging. ## DataWeave Functions for Error Handling Mule 4.x includes a set of DataWeave functions that you can use in the context of a batch step.
DataWeave FunctionDescription

#[Batch::isSuccessfulRecord()]

A boolean function that returns true if the current record has not thrown exceptions in any prior step.

#[Batch::isFailedRecord()]

A boolean function that returns true if the current record has thrown exceptions in any prior step.

#[Batch::failureExceptionForStep(String)]

Receives the name of a step as a String argument. If the current record threw exception on that step, then it returns the actual Exception object. Otherwise it returns null

#[Batch::getStepExceptions()]

Returns a java Map<String, Exception> in which the keys are the name of a batch step in which the current record has failed, and the value is the exception itself.
If the record hasn’t failed in any step, this Map will be empty but will never be null. Also, the Map contains no entries for steps in which the record hasn’t failed.

#[Batch::getFirstException()]

Returns the Exception for the very first step in which the current record has failed. If the record hasn’t failed in any step, then it returns null.

#[Batch::getLastException()]

Returns the Exception for the last step in which the current record has failed. If the record hasn’t failed in any step, then it returns null.

### Example Imagine a batch job that polls files containing contact information. In the first step, the batch job aggregates the contacts information and transforms them using the Transform Message component to then being pushed to Salesforce. In the second step, the job transforms the same contacts again to match the data structure of another third-party contacts application (say, Google Contacts for example) and pushes them to this service using HTTP request. Now, assume that as a third step, you need to be able to write into a JMS dead-letter queue per each record that has failed. To keep it simple, let’s say that the message will be the exception itself. This requirement holds a trick: each record could have failed in both steps, which means that the same record would translate into two JMS messages. Such an application would look like this: ![batch error handling faq f34d5](/mulesoft/current/en-us/mule-runtime/4.6/_images/batch-error-handling-faq-f34d5.png) Since the goal is to gather failures, it makes sense to configure the `Failures` step with an ONLY\_FAILURES filter (see [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.6/batch-filters-and-batch-aggregator) for more details about batch filters). The set-payload processor in this step can be configured to use the `Batch::getStepExceptions()` function. ![batch error handling faq 6269e](/mulesoft/current/en-us/mule-runtime/4.6/_images/batch-error-handling-faq-6269e.png) As stated above, this function returns a map with all errors found in all steps. And since our goal is to send the exceptions through JMS and we don’t care about the steps, we can use a foreach scope to iterate over the map’s values (the errors) and send them through a JMS outbound endpoint: ![batch error handling faq b822e](/mulesoft/current/en-us/mule-runtime/4.6/_images/batch-error-handling-faq-b822e.png) ## Batch Processing Strategies for Error Handling Mule has three options for handling a record-level error: 1. **Finish processing** Stop the execution of the current job instance. Finish the execution of the records currently in-flight, but do not pull any more records from the queues and set the job instance into a `FAILURE` state. The On Complete phase is invoked. 2. **Continue processing** the batch regardless of any failed records, using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records. 3. **Continue processing** the batch regardless of any failed records (using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records), until the batch job accumulates a **maximum number of failed records** at which point the execution will halt just like in option 1. By default, Mule’s batch jobs follow the first error handling strategy which halts the batch instance execution. The above behavior is controlled through the `maxFailedRecords` attributes.
Failed Record Handling OptionBatch Job AttributeValue

Stops processing when a failed record is found

maxFailedRecords

0

Continues processing indefinitely, regardless of the number of failed records

maxFailedRecords

-1

Continues processing until reaching the maximum number of failed records

maxFailedRecords

integer

```xml ``` ### Crossing the Max Failed Threshold When a batch job accumulates enough failed records to cross the `maxFailedRecords` threshold, Mule aborts processing for any remaining batch steps, skipping directly to the On Complete phase. For example, if you set the value of `maxFailedRecords` to "10" and a batch job accumulates ten failed records in the first of three batch steps, Mule does not attempt to process the batch through the remaining two batch steps. Instead, it aborts further processing and skips directly to On Complete to report on the batch job failure. If a batch job _does not_ accumulate enough failed records to cross the `maxFailedRecords` threshold, _all_ records – successes and failures – continue to flow from batch step to batch step; use filters to control which records each batch step processes. ## See Also - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.6/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.9 --- # Handling Errors During Batch Job > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch processing is designed to handle very large data sets and to perform almost real-time data integration that recovers from crashes and continues processing a job from a point of failure. However, _verbose_ logs for issues that occur in large data sets can become enormous and severely impact performance. To limit this impact, Mule uses INFO-level logging by default, as described in [Logs of Failing Records Inside a Batch Step](#default_logging). For cases in which you require more verbose log messages, you can change the mode to DEBUG. This mode is helpful for debugging and is feasible for some cases that involve smaller data sets. The following property is available for setting the logging mode: ```xml ``` If you are using CloudHub or Runtime Manager, you can add the following package to the Logs tab in DEBUG level: ```logs com.mulesoft.mule.runtime.module.batch ``` Avoid using the DEBUG mode in a production environment when processing very large data sets. ## Logs of Failing Records Inside a Batch Step When processing a batch job instance, a processor inside a batch step can fail or raise an error, for example, because of corrupted or incomplete record data. By default, Mule uses the INFO log level to log stack traces according to the following logic when issues occur: 1. Mule gets the exception’s full stack trace. 2. Mule strips the stack trace from error messages in the log. Even if all records raise the same error, the messages being processed would probably contain specific information related to those records. For example, if I’m pushing leads to my Salesforce account and one record fails because the lead was already uploaded, another repeated lead would have different record information, but the error is the same. 3. Mule verifies if the stack trace was already logged in the current step. The first time the runtime encounters this error, Mule logs the error and produces a message like this one: ```logs com.mulesoft.mule.runtime.module.batch.internal.DefaultBatchStep: Found exception processing record on step 'batchStep1' for job instance 'Batch Job Example' of job 'CreateLeadsBatch'. This is the first record to show this exception on this step for this job instance. Subsequent records with the same failures will not be logged for performance and log readability reasons: ``` Mule logs on a "by step" basis. If another step also raises the same error, the runtime logs it again for that step. 4. When the batch job reaches the On Complete phase, Mule displays an error summary with every error type and the number of occurrences in each batch step. The error summary for a batch job with two batch steps that raised a `batch.exception` type: ```logs ******************************************************************************* * - - + Exception Type + - - * - - + Step + - - * - - + Count + - - * ******************************************************************************* * com.mulesoft.mule.runtime.module.batch.exception.B * batchStep1 * 10 * * com.mulesoft.mule.runtime.module.batch.exception.B * batchStep2 * 9 * ******************************************************************************* ``` Here, the first step failed ten times and the second failed nine. Mule logs batch errors using this behavior as its default configuration, which only logs INFO level messages to get a balanced trade-off between logging efficiency for large chunks of data. However, your motivation to use batch processing might not be its ability to handle large datasets, but its capacity to recover from a crash and keep processing a batch job from where it was left off when performing "near real-time" data integration. Or you may need more verbose log levels for debugging. ## DataWeave Functions for Error Handling Mule 4.x includes a set of DataWeave functions that you can use in the context of a batch step.
DataWeave FunctionDescription

#[Batch::isSuccessfulRecord()]

A boolean function that returns true if the current record has not thrown exceptions in any prior step.

#[Batch::isFailedRecord()]

A boolean function that returns true if the current record has thrown exceptions in any prior step.

#[Batch::failureExceptionForStep(String)]

Receives the name of a step as a String argument. If the current record threw exception on that step, then it returns the actual Exception object. Otherwise it returns null

#[Batch::getStepExceptions()]

Returns a java Map<String, Exception> in which the keys are the name of a batch step in which the current record has failed, and the value is the exception itself.
If the record hasn’t failed in any step, this Map will be empty but will never be null. Also, the Map contains no entries for steps in which the record hasn’t failed.

#[Batch::getFirstException()]

Returns the Exception for the very first step in which the current record has failed. If the record hasn’t failed in any step, then it returns null.

#[Batch::getLastException()]

Returns the Exception for the last step in which the current record has failed. If the record hasn’t failed in any step, then it returns null.

### Example Imagine a batch job that polls files containing contact information. In the first step, the batch job aggregates the contacts information and transforms them using the Transform Message component to then being pushed to Salesforce. In the second step, the job transforms the same contacts again to match the data structure of another third-party contacts application (say, Google Contacts for example) and pushes them to this service using HTTP request. Now, assume that as a third step, you need to be able to write into a JMS dead-letter queue per each record that has failed. To keep it simple, let’s say that the message will be the exception itself. This requirement holds a trick: each record could have failed in both steps, which means that the same record would translate into two JMS messages. Such an application would look like this: ![A flow showing a batch process for lead management with detailed steps and error handling in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/batch-error-handling-faq-f34d5.png) Since the goal is to gather failures, it makes sense to configure the `Failures` step with an ONLY\_FAILURES filter (see [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.9/batch-filters-and-batch-aggregator) for more details about batch filters). The set-payload processor in this step can be configured to use the `Batch::getStepExceptions()` function. ![A Set Payload component with a value expression related to batch exceptions in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/batch-error-handling-faq-6269e.png) As stated above, this function returns a map with all errors found in all steps. And since our goal is to send the exceptions through JMS and we don’t care about the steps, we can use a foreach scope to iterate over the map’s values (the errors) and send them through a JMS outbound endpoint: ![A For Each component processing error in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/batch-error-handling-faq-b822e.png) ## Batch Processing Strategies for Error Handling Mule has three options for handling a record-level error: 1. **Finish processing** Stop the execution of the current job instance. Finish the execution of the records currently in-flight, but do not pull any more records from the queues and set the job instance into a `FAILURE` state. The On Complete phase is invoked. 2. **Continue processing** the batch regardless of any failed records, using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records. 3. **Continue processing** the batch regardless of any failed records (using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records), until the batch job accumulates a **maximum number of failed records** at which point the execution will halt just like in option 1. By default, Mule’s batch jobs follow the first error handling strategy which halts the batch instance execution. The above behavior is controlled through the `maxFailedRecords` attributes.
Failed Record Handling OptionBatch Job AttributeValue

Stops processing when a failed record is found

maxFailedRecords

0

Continues processing indefinitely, regardless of the number of failed records

maxFailedRecords

-1

Continues processing until reaching the maximum number of failed records

maxFailedRecords

integer

```xml ``` ### Crossing the Max Failed Threshold When a batch job accumulates enough failed records to cross the `maxFailedRecords` threshold, Mule aborts processing for any remaining batch steps, skipping directly to the On Complete phase. For example, if you set the value of `maxFailedRecords` to "10" and a batch job accumulates ten failed records in the first of three batch steps, Mule does not attempt to process the batch through the remaining two batch steps. Instead, it aborts further processing and skips directly to On Complete to report on the batch job failure. If a batch job _does not_ accumulate enough failed records to cross the `maxFailedRecords` threshold, _all_ records – successes and failures – continue to flow from batch step to batch step; use filters to control which records each batch step processes. ## See Also - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/4.9/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Handling Errors During Batch Job > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Handle record-level failures in Mule batch jobs while balancing logging detail and performance. Learn how batch steps log errors, how failed records propagate through a job, and how to inspect errors by using DataWeave functions. Batch jobs capture record-level failures during batch step execution. For details about the error representation and how to access error fields, see [Batch Errors](https://docs.mulesoft.com/mule-runtime/latest/batch-error-concept). Mule batch processing is designed to handle large data sets and to perform almost real-time data integration that recovers from crashes and continues processing a job from a point of failure. However, _verbose_ logs for issues that occur in large data sets can become enormous and severely impact performance. To limit this impact, Mule uses INFO-level logging by default, as described in [Logs of Failing Records Inside a Batch Step](#default_logging). For cases in which you require more verbose log messages, you can change the mode to DEBUG. This mode is helpful for debugging and is feasible for some cases that involve smaller data sets. Set the logging mode with this property: ```xml ``` If you’re using CloudHub or Runtime Manager, you can add this package to the Logs tab in DEBUG level: ```logs com.mulesoft.mule.runtime.module.batch ``` Avoid using the DEBUG mode in a production environment when processing large data sets. > [!NOTE] Starting with Mule 4.11, batch error handling relies on `BatchError` objects instead of > exceptions. ## Logs of Failing Records Inside a Batch Step When processing a batch job instance, a processor inside a batch step can fail or raise an error, for example, because of corrupted or incomplete record data. By default, Mule uses the INFO log level to log stack traces according to this logic when issues occur: 1. Mule gets the exception’s full stack trace. 2. Mule strips the stack trace from error messages in the log. Even if all records raise the same error, the messages being processed would probably contain specific information related to those records. For example, if you push leads to a Salesforce account and one record fails because the lead was uploaded, another repeated lead would have different record information, but the error is the same. 3. Mule verifies if the stack trace was already logged in the current step. The first time the runtime encounters this error, Mule logs the error and produces a message like this one: ```logs com.mulesoft.mule.runtime.module.batch.internal.DefaultBatchStep: Found error processing record on step 'batchStep1' for job instance 'Batch Job Example' of job 'CreateLeadsBatch'. This is the first record to show this error on this step for this job instance. Subsequent records with the same failures will not be logged for performance and log readability reasons: ``` Mule logs on a "by step" basis. If another step also raises the same error, the runtime logs it again for that step. 4. When the batch job reaches the On Complete phase, Mule displays an error summary with every error type and the number of occurrences in each batch step. The error summary for a batch job with two batch steps that raised an `APP:FAILURE` error: ```logs ******************************************************************************* * - - + Error Type + - - * - - + Step + - - * - - + Count + - - * ******************************************************************************* * APP:FAILURE * batchStep1 * 10 * * APP:FAILURE * batchStep2 * 9 * ******************************************************************************* ``` Here, the first step failed ten times and the second failed nine. Mule logs batch errors using this behavior as its default configuration, which only logs INFO level messages to get a balanced trade-off between logging efficiency for large chunks of data. However, your motivation to use batch processing might not be its ability to handle large datasets, but its capacity to recover from a crash and keep processing a batch job from where it was left off when performing "near real-time" data integration. Or you may need more verbose log levels for debugging. ## DataWeave Functions for Error Handling Mule 4.x includes a set of DataWeave functions that you can use in the context of a batch step.
DataWeave FunctionDescription

#[Batch::isSuccessfulRecord()]

A boolean function that returns true if the current record hasn’t presented errors in any prior step.

#[Batch::isFailedRecord()]

A boolean function that returns true if the current record has presented errors in any prior step.

#[Batch::failureErrorForStep(String)]

Receives the name of a step as a String argument. If the current record presented an error on that step, it returns the BatchError object. Otherwise, returns null.

#[Batch::getStepErrors()]

Returns a Map<String, BatchError> in which the keys are the name of a batch step in which the current record has failed, and the value is the error itself.
If the record hasn’t failed in any step, this map is empty but never null. The map contains no entries for steps in which the record hasn’t failed.

#[Batch::getFirstError()]

Returns the BatchError for the first step in which the current record has failed. If the record hasn’t failed in any step, returns null.

#[Batch::getLastError()]

Returns the BatchError for the last step in which the current record has failed. If the record hasn’t failed in any step, returns null.

There are also bindings to work with the old batch error handling mechanism, which relied on exceptions rather than `BatchError` objects.
DataWeave FunctionDescription

#[Batch::failureExceptionForStep(String)]

Receives the name of a step as a String argument. If the current record throws an exception on that step, it returns the Exception object. Otherwise, returns null.

#[Batch::getStepExceptions()]

Returns a Java Map<String, Exception> in which the keys are the name of a batch step in which the current record has failed, and the value is the exception itself.
If the record hasn’t failed in any step, this map is empty but never null. The map contains no entries for steps in which the record hasn’t failed.

#[Batch::getFirstException()]

Returns the Exception for the first step in which the current record has failed. If the record hasn’t failed in any step, returns null.

#[Batch::getLastException()]

Returns the Exception for the last step in which the current record has failed. If the record hasn’t failed in any step, returns null.

### Example Consider a batch job that polls files containing contact information: - In the first step, the batch job aggregates the contact information and transforms it using the Transform Message component, then pushes the data to Salesforce. - In the second step, the job transforms the same contacts again to match the data structure of another third-party contacts application (such as Google Contacts) and pushes them to this service using an HTTP request. - In the third step, you write into a JMS dead-letter queue for each record that has failed. The message content is the error itself. Each record could have failed in both steps, meaning the same record translates into two JMS messages. Such an application would look like this: ![A flow showing a batch process for lead management with detailed steps and error handling in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/batch-error-handling-faq-f34d5.png) Since the goal is to gather failures, it makes sense to configure the `Failures` step with an ONLY\_FAILURES filter (see [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/latest/batch-filters-and-batch-aggregator) for more details about batch filters). The set-payload processor in this step can be configured to use the `Batch::getStepErrors()` function. ![A Set Payload component with a value expression related to batch errors in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/batch-error-handling-faq-6269e.png) This function returns a map with all errors found in all steps. To send the errors through JMS, use a For Each scope to iterate over the map’s values (the errors) and send them through a JMS outbound endpoint: ![A For Each component processing error in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/batch-error-handling-faq-b822e.png) ## Batch Processing Strategies for Error Handling Mule has three options for handling a record-level error: 1. **Finish processing** Stop the execution of the current job instance. Finish the execution of the records currently in-flight, but do not pull any more records from the queues and set the job instance into a `FAILURE` state. The On Complete phase is invoked. 2. **Continue processing** the batch regardless of any failed records, using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records. 3. **Continue processing** the batch regardless of any failed records (using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records), until the batch job accumulates a **maximum number of failed records** at which point the execution will halt just like in option 1. By default, Mule batch jobs follow the first error handling strategy, which halts the batch instance execution. This behavior is controlled through the `maxFailedRecords` attribute.
Failed Record Handling OptionBatch Job AttributeValue

Stops processing when a failed record is found

maxFailedRecords

0

Continues processing indefinitely, regardless of the number of failed records

maxFailedRecords

-1

Continues processing until reaching the maximum number of failed records

maxFailedRecords

integer

```xml ``` ### Crossing the Max Failed Threshold When a batch job accumulates enough failed records to cross the `maxFailedRecords` threshold, Mule aborts processing for any remaining batch steps, skipping directly to the On Complete phase. For example, if you set the value of `maxFailedRecords` to "10" and a batch job accumulates ten failed records in the first of three batch steps, Mule does not attempt to process the batch through the remaining two batch steps. Instead, it aborts further processing and skips directly to On Complete to report on the batch job failure. If a batch job _does not_ accumulate enough failed records to cross the `maxFailedRecords` threshold, _all_ records – successes and failures – continue to flow from batch step to batch step; use filters to control which records each batch step processes. ## See Also - [Configuring Batch Components](https://docs.mulesoft.com/mule-runtime/latest/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.3 --- # Handling Errors During Batch Jobs > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule batch processing is designed to handle very large data sets and to perform almost real-time data integration that recovers from crashes and continues processing a job from a point of failure. However, _verbose_ logs for issues that occur in large data sets can become enormous and severely impact performance. To limit this impact, Mule uses INFO-level logging by default, as described in [Logs of Failing Records Inside a Batch Step](#default_logging). For cases in which you require more verbose log messages, you can change the mode to DEBUG. This mode is helpful for debugging and is feasible for some cases that involve smaller data sets. The following property is available for setting the logging mode: ```text log4j.logger.com.mulesoft.module.batch=DEBUG ``` Avoid using the DEBUG mode in a production environment when processing very large data sets. ## Logs of Failing Records Inside a Batch Step When processing a batch job instance, a processor inside a batch step can fail or raise an error, for example, because of corrupted or incomplete record data. By default, Mule uses the INFO log level to log stack traces according to the following logic when issues occur: 1. Mule gets the exception’s full stack trace. 2. Mule strips the stack trace from error message in the log. Even if all records raise the same error, the messages being processed would probably contain specific information related to those records. For example, if I’m pushing leads to my Salesforce account and one record fails because the lead was already uploaded, another repeated lead would have different record information, but the error is the same. 3. Mule verifies if the stack trace was already logged in the current step. The first time the runtime encounters this error, Mule logs the error and produces a message like this one: ```text com.mulesoft.mule.runtime.module.batch.internal.DefaultBatchStep: Found exception processing record on step 'batchStep1' for job instance 'Batch Job Example' of job 'CreateLeadsBatch'. This is the first record to show this exception on this step for this job instance. Subsequent records with the same failures will not be logged for performance and log readability reasons: ``` Mule logs on a "by step" basis. If another step also raises the same error, the runtime logs it again for that step. 4. When the batch job reaches the On Complete phase, Mule displays an error summary with every error type and the number of occurrences in each batch step. The error summary for a batch job with two batch steps that raised a `batch.exception` type: ```text ************************************************************************************************************************ * - - + Exception Type + - - * - - + Step + - - * - - + Count + - - * ************************************************************************************************************************ * com.mulesoft.mule.runtime.module.batch.exception.B * batchStep1 * 10 * * com.mulesoft.mule.runtime.module.batch.exception.B * batchStep2 * 9 * ************************************************************************************************************************ ``` Here, the first step failed ten times, and the second failed nine. ## DataWeave Functions for Error Handling Mule 4.x includes a set of DataWeave functions that you can use in the context of a batch step.
DataWeave FunctionDescription

#[Batch::isSuccessfulRecord()]

A boolean function that returns true if the current record has not thrown exceptions in any prior step.

#[Batch::isFailedRecord()]

A boolean function that returns true if the current record has thrown exceptions in any prior step.

#[Batch::failureExceptionForStep(String)]

Receives the name of a step as a String argument. If the current record threw exception on that step, then it returns the actual Exception object. Otherwise it returns null

#[Batch::getStepExceptions()]

Returns a java Map<String, Exception> in which the keys are the name of a batch step in which the current record has failed, and the value is the exception itself.
If the record hasn’t failed in any step, this Map will be empty but will never be null. Also, the Map contains no entries for steps in which the record hasn’t failed.

#[Batch::getFirstException()]

Returns the Exception for the very first step in which the current record has failed. If the record hasn’t failed in any step, then it returns null.

#[Batch::getLastException()]

Returns the Exception for the last step in which the current record has failed. If the record hasn’t failed in any step, then it returns null.

### Example Imagine a batch job that polls files containing contact information. In the first step, the batch job aggregates the contacts information and transforms them using the Transform Message component to then being pushed to Salesforce. In the second step, the job transforms the same contacts again to match the data structure of another third-party contacts application (say, Google Contacts for example) and pushes them to this service using HTTP request. Now, assume that as a third step, you need to be able to write into a JMS dead-letter queue per each record that has failed. To keep it simple, let’s say that the message will be the exception itself. This requirement holds a trick: each record could have failed in both steps, which means that the same record would translate into two JMS messages. Such an application would look like this: ![batch error handling faq f34d5](/mulesoft/current/en-us/mule-runtime/4.3/_images/batch-error-handling-faq-f34d5.png) Since the goal is to gather failures, it makes sense to configure the `Failures` step with an ONLY\_FAILURES filter (see [Refining Batch Steps Processing](https://docs.mulesoft.com/mule-runtime/4.3/batch-filters-and-batch-aggregator) for more details about batch filters). The set-payload processor in this step can be configured to use the `Batch::getStepExceptions()` function. ![batch error handling faq 6269e](/mulesoft/current/en-us/mule-runtime/4.3/_images/batch-error-handling-faq-6269e.png) As stated above, this function returns a map with all errors found in all steps. And since our goal is to send the exceptions through JMS and we don’t care about the steps, we can use a foreach scope to iterate over the map’s values (the errors) and send them through a JMS outbound endpoint: ![batch error handling faq b822e](/mulesoft/current/en-us/mule-runtime/4.3/_images/batch-error-handling-faq-b822e.png) ## Batch Processing Strategies for Error Handling Mule has three options for handling a record-level error: 1. **Finish processing** Stop the execution of the current job instance. Finish the execution of the records currently in-flight, but do not pull any more records from the queues and set the job instance into a `FAILURE` state. The On Complete phase is invoked. 2. **Continue processing** the batch regardless of any failed records, using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records. 3. **Continue processing** the batch regardless of any failed records (using the `acceptExpression` and `acceptPolicy` attributes to instruct subsequent batch steps how to handle failed records), until the batch job accumulates a **maximum number of failed records** at which point the execution will halt just like in option 1. By default, Mule’s batch jobs follow the first error handling strategy which halts the batch instance execution. The above behavior is controlled through the `maxFailedRecords` attributes.
Failed Record Handling OptionBatch Job AttributeValue

Stops processing when a failed record is found

maxFailedRecords

0

Continues processing indefinitely, regardless of the number of failed records

maxFailedRecords

-1

Continues processing until reaching the maximum number of failed records

maxFailedRecords

integer

```xml ``` ### Crossing the Max Failed Threshold When a batch job accumulates enough failed records to cross the `maxFailedRecords` threshold, Mule aborts processing for any remaining batch steps, skipping directly to the On Complete phase. For example, if you set the value of `maxFailedRecords` to "10" and a batch job accumulates ten failed records in the first of three batch steps, Mule does not attempt to process the batch through the remaining two batch steps. Instead, it aborts further processing and skips directly to On Complete to report on the batch job failure. If a batch job _does not_ accumulate enough failed records to cross the `maxFailedRecords` threshold, _all_ records – successes and failures – continue to flow from batch step to batch step; use filters to control which records each batch step processes. ## See Also - [Refining Batch Steps Processing](https://docs.mulesoft.com/mule-runtime/4.3/batch-filters-and-batch-aggregator) --- product: Mule Runtime version: 4.11 keywords: anypoint studio, filters, conditional, gates, idempotent --- # Idempotent Message Validator > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Idempotent Message Validator ensures that only unique messages continue through a flow’s execution by checking the unique ID of the incoming message. You can use any incoming attribute of the Mule message as an ID, or you can compute the ID by configuring a DataWeave expression. You can also use the DataWeave `Crypto` functions to compute hashes (SHA, MD5) from the data. ## Message Hashing DataWeave enables you to import the `Crypto` library to execute hashing functions. Calculating a hash can be useful when you want to compute a unique ID for the Mule message. For example, if you want to get an MD5 hash from the payload and use it as the ID, open the Idempotent Message Validator properties in Anypoint Studio and set **ID Expression** (`idExpression` in XML) to the following DataWeave expression: #\[ %dw 2.0 output text/plain import dw::Crypto --- Crypto::hashWith(payload,'MD5') \] ## Examples - The following example shows an Idempotent Message Validator configured to extract the query parameter `id` from the HTTP request and use that value as a unique identifier to filter the message: ```xml ... ... ``` - The next example shows an Idempotent Message Validator configured to hash the payload using a DataWeave expression, store the result in a persistent object store, and then use the processed message IDs as the unique identifier to filter the message: ```xml ... ... ``` ## Parameter Reference
NameTypeDescriptionDefault ValueRequired

ID Expression

Expression

The expression Mule uses to generate the ID. You can use a DataWeave function to calculate the ID, or you can extract the ID from any existing value of the Mule message.

#[correlationId]

No

Value Expression

Expression

This parameter is not used. Setting a value has no effect.

#[correlationId]

No

Object Store

Object Store

Either a name to reference a global object store or a definition of a private object store where the component stores the processed message IDs.

Object Store created by the Object Store Manager. Not persistent, with an entry TTL of 5 MINUTES and an expiration interval of 6 SECONDS.

No

Store Prefix

String

Defines the prefix of the object store names. This value is used only for the internally built object store.

configFileName.flowName.IdempotentMessageValidator

No

### Throws - `MULE:DUPLICATE_MESSAGE` ## See Also - [Crypto (dw::Crypto)](https://docs.mulesoft.com/dataweave/latest/dw-crypto) --- product: Mule Runtime version: 4.12 keywords: anypoint studio, filters, conditional, gates, idempotent --- # Idempotent Message Validator > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Idempotent Message Validator ensures that only unique messages continue through a flow’s execution by checking the unique ID of the incoming message. You can use any incoming attribute of the Mule message as an ID, or you can compute the ID by configuring a DataWeave expression. You can also use the DataWeave `Crypto` functions to compute hashes (SHA, MD5) from the data. ## Message Hashing DataWeave enables you to import the `Crypto` library to execute hashing functions. Calculating a hash can be useful when you want to compute a unique ID for the Mule message. For example, if you want to get an MD5 hash from the payload and use it as the ID, open the Idempotent Message Validator properties in Anypoint Studio and set **ID Expression** (`idExpression` in XML) to the following DataWeave expression: #\[ %dw 2.0 output text/plain import dw::Crypto --- Crypto::hashWith(payload,'MD5') \] ## Examples - The following example shows an Idempotent Message Validator configured to extract the query parameter `id` from the HTTP request and use that value as a unique identifier to filter the message: ```xml ... ... ``` - The next example shows an Idempotent Message Validator configured to hash the payload using a DataWeave expression, store the result in a persistent object store, and then use the processed message IDs as the unique identifier to filter the message: ```xml ... ... ``` ## Parameter Reference
NameTypeDescriptionDefault ValueRequired

ID Expression

Expression

The expression Mule uses to generate the ID. You can use a DataWeave function to calculate the ID, or you can extract the ID from any existing value of the Mule message.

#[correlationId]

No

Value Expression

Expression

This parameter is not used. Setting a value has no effect.

#[correlationId]

No

Object Store

Object Store

Either a name to reference a global object store or a definition of a private object store where the component stores the processed message IDs.

Object Store created by the Object Store Manager. Not persistent, with an entry TTL of 5 MINUTES and an expiration interval of 6 SECONDS.

No

Store Prefix

String

Defines the prefix of the object store names. This value is used only for the internally built object store.

configFileName.flowName.IdempotentMessageValidator

No

### Throws - `MULE:DUPLICATE_MESSAGE` ## See Also - [Crypto (dw::Crypto)](https://docs.mulesoft.com/dataweave/latest/dw-crypto) --- product: Mule Runtime version: 4.3 keywords: anypoint studio, filters, conditional, gates, idempotent --- # Idempotent Message Validator > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Idempotent Message Validator ensures that only unique messages continue through a flow’s execution by checking the unique ID of the incoming message. You can use any incoming attribute of the Mule message as an ID, or you can compute the ID by configuring a DataWeave expression. You can also use the DataWeave `Crypto` functions to compute hashes (SHA, MD5) from the data. ## Message Hashing DataWeave enables you to import the `Crypto` library to execute hashing functions. Calculating a hash can be useful when you want to compute a unique ID for the Mule message. For example, if you want to get an MD5 hash from the payload and use it as the ID, open the Idempotent Message Validator properties in Anypoint Studio and set **ID Expression** (`idExpression` in XML) to the following DataWeave expression: #\[ %dw 2.0 output text/plain import dw::Crypto --- Crypto::hashWith(payload,'MD5') \] ## Examples - The following example shows an Idempotent Message Validator configured to extract the query parameter `id` from the HTTP request and use that value as a unique identifier to filter the message: ```xml ... ... ``` - The next example shows an Idempotent Message Validator configured to hash the payload using a DataWeave expression, store the result in a persistent object store, and then use the processed message IDs as the unique identifier to filter the message: ```xml ... ... ``` ## Parameter Reference
NameTypeDescriptionDefault ValueRequired

ID Expression

Expression

The expression Mule uses to generate the ID. You can use a DataWeave function to calculate the ID, or you can extract the ID from any existing value of the Mule message.

#[correlationId]

No

Value Expression

Expression

This parameter is not used. Setting a value has no effect.

#[correlationId]

No

Object Store

Object Store

Either a name to reference a global object store or a definition of a private object store where the component stores the processed message IDs.

Object Store created by the Object Store Manager. Not persistent, with an entry TTL of 5 MINUTES and an expiration interval of 6 SECONDS.

No

Store Prefix

String

Defines the prefix of the object store names. This value is used only for the internally built object store.

configFileName.flowName.IdempotentMessageValidator

No

### Throws - `MULE:DUPLICATE_MESSAGE` ## See Also - [Crypto (dw::Crypto)](https://docs.mulesoft.com/dataweave/2.3/dw-crypto) --- product: Mule Runtime version: 4.4 keywords: anypoint studio, filters, conditional, gates, idempotent --- # Idempotent Message Validator > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Idempotent Message Validator ensures that only unique messages continue through a flow’s execution by checking the unique ID of the incoming message. You can use any incoming attribute of the Mule message as an ID, or you can compute the ID by configuring a DataWeave expression. You can also use the DataWeave `Crypto` functions to compute hashes (SHA, MD5) from the data. ## Message Hashing DataWeave enables you to import the `Crypto` library to execute hashing functions. Calculating a hash can be useful when you want to compute a unique ID for the Mule message. For example, if you want to get an MD5 hash from the payload and use it as the ID, open the Idempotent Message Validator properties in Anypoint Studio and set **ID Expression** (`idExpression` in XML) to the following DataWeave expression: #\[ %dw 2.0 output text/plain import dw::Crypto --- Crypto::hashWith(payload,'MD5') \] ## Examples - The following example shows an Idempotent Message Validator configured to extract the query parameter `id` from the HTTP request and use that value as a unique identifier to filter the message: ```xml ... ... ``` - The next example shows an Idempotent Message Validator configured to hash the payload using a DataWeave expression, store the result in a persistent object store, and then use the processed message IDs as the unique identifier to filter the message: ```xml ... ... ``` ## Parameter Reference
NameTypeDescriptionDefault ValueRequired

ID Expression

Expression

The expression Mule uses to generate the ID. You can use a DataWeave function to calculate the ID, or you can extract the ID from any existing value of the Mule message.

#[correlationId]

No

Value Expression

Expression

This parameter is not used. Setting a value has no effect.

#[correlationId]

No

Object Store

Object Store

Either a name to reference a global object store or a definition of a private object store where the component stores the processed message IDs.

Object Store created by the Object Store Manager. Not persistent, with an entry TTL of 5 MINUTES and an expiration interval of 6 SECONDS.

No

Store Prefix

String

Defines the prefix of the object store names. This value is used only for the internally built object store.

configFileName.flowName.IdempotentMessageValidator

No

### Throws - `MULE:DUPLICATE_MESSAGE` ## See Also - [Crypto (dw::Crypto)](https://docs.mulesoft.com/dataweave/latest/dw-crypto) --- product: Mule Runtime version: 4.6 keywords: anypoint studio, filters, conditional, gates, idempotent --- # Idempotent Message Validator > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Idempotent Message Validator ensures that only unique messages continue through a flow’s execution by checking the unique ID of the incoming message. You can use any incoming attribute of the Mule message as an ID, or you can compute the ID by configuring a DataWeave expression. You can also use the DataWeave `Crypto` functions to compute hashes (SHA, MD5) from the data. ## Message Hashing DataWeave enables you to import the `Crypto` library to execute hashing functions. Calculating a hash can be useful when you want to compute a unique ID for the Mule message. For example, if you want to get an MD5 hash from the payload and use it as the ID, open the Idempotent Message Validator properties in Anypoint Studio and set **ID Expression** (`idExpression` in XML) to the following DataWeave expression: #\[ %dw 2.0 output text/plain import dw::Crypto --- Crypto::hashWith(payload,'MD5') \] ## Examples - The following example shows an Idempotent Message Validator configured to extract the query parameter `id` from the HTTP request and use that value as a unique identifier to filter the message: ```xml ... ... ``` - The next example shows an Idempotent Message Validator configured to hash the payload using a DataWeave expression, store the result in a persistent object store, and then use the processed message IDs as the unique identifier to filter the message: ```xml ... ... ``` ## Parameter Reference
NameTypeDescriptionDefault ValueRequired

ID Expression

Expression

The expression Mule uses to generate the ID. You can use a DataWeave function to calculate the ID, or you can extract the ID from any existing value of the Mule message.

#[correlationId]

No

Value Expression

Expression

This parameter is not used. Setting a value has no effect.

#[correlationId]

No

Object Store

Object Store

Either a name to reference a global object store or a definition of a private object store where the component stores the processed message IDs.

Object Store created by the Object Store Manager. Not persistent, with an entry TTL of 5 MINUTES and an expiration interval of 6 SECONDS.

No

Store Prefix

String

Defines the prefix of the object store names. This value is used only for the internally built object store.

configFileName.flowName.IdempotentMessageValidator

No

### Throws - `MULE:DUPLICATE_MESSAGE` ## See Also - [Crypto (dw::Crypto)](https://docs.mulesoft.com/dataweave/latest/dw-crypto) --- product: Mule Runtime version: 4.9 keywords: anypoint studio, filters, conditional, gates, idempotent --- # Idempotent Message Validator > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Idempotent Message Validator ensures that only unique messages continue through a flow’s execution by checking the unique ID of the incoming message. You can use any incoming attribute of the Mule message as an ID, or you can compute the ID by configuring a DataWeave expression. You can also use the DataWeave `Crypto` functions to compute hashes (SHA, MD5) from the data. ## Message Hashing DataWeave enables you to import the `Crypto` library to execute hashing functions. Calculating a hash can be useful when you want to compute a unique ID for the Mule message. For example, if you want to get an MD5 hash from the payload and use it as the ID, open the Idempotent Message Validator properties in Anypoint Studio and set **ID Expression** (`idExpression` in XML) to the following DataWeave expression: #\[ %dw 2.0 output text/plain import dw::Crypto --- Crypto::hashWith(payload,'MD5') \] ## Examples - The following example shows an Idempotent Message Validator configured to extract the query parameter `id` from the HTTP request and use that value as a unique identifier to filter the message: ```xml ... ... ``` - The next example shows an Idempotent Message Validator configured to hash the payload using a DataWeave expression, store the result in a persistent object store, and then use the processed message IDs as the unique identifier to filter the message: ```xml ... ... ``` ## Parameter Reference
NameTypeDescriptionDefault ValueRequired

ID Expression

Expression

The expression Mule uses to generate the ID. You can use a DataWeave function to calculate the ID, or you can extract the ID from any existing value of the Mule message.

#[correlationId]

No

Value Expression

Expression

This parameter is not used. Setting a value has no effect.

#[correlationId]

No

Object Store

Object Store

Either a name to reference a global object store or a definition of a private object store where the component stores the processed message IDs.

Object Store created by the Object Store Manager. Not persistent, with an entry TTL of 5 MINUTES and an expiration interval of 6 SECONDS.

No

Store Prefix

String

Defines the prefix of the object store names. This value is used only for the internally built object store.

configFileName.flowName.IdempotentMessageValidator

No

### Throws - `MULE:DUPLICATE_MESSAGE` ## See Also - [Crypto (dw::Crypto)](https://docs.mulesoft.com/dataweave/latest/dw-crypto) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: anypoint studio, filters, conditional, gates, idempotent --- # Idempotent Message Validator > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Idempotent Message Validator ensures that only unique messages continue through a flow’s execution by checking the unique ID of the incoming message. You can use any incoming attribute of the Mule message as an ID, or you can compute the ID by configuring a DataWeave expression. You can also use the DataWeave `Crypto` functions to compute hashes (SHA, MD5) from the data. ## Message Hashing DataWeave enables you to import the `Crypto` library to execute hashing functions. Calculating a hash can be useful when you want to compute a unique ID for the Mule message. For example, if you want to get an MD5 hash from the payload and use it as the ID, open the Idempotent Message Validator properties in Anypoint Studio and set **ID Expression** (`idExpression` in XML) to the following DataWeave expression: #\[ %dw 2.0 output text/plain import dw::Crypto --- Crypto::hashWith(payload,'MD5') \] ## Examples - The following example shows an Idempotent Message Validator configured to extract the query parameter `id` from the HTTP request and use that value as a unique identifier to filter the message: ```xml ... ... ``` - The next example shows an Idempotent Message Validator configured to hash the payload using a DataWeave expression, store the result in a persistent object store, and then use the processed message IDs as the unique identifier to filter the message: ```xml ... ... ``` ## Parameter Reference
NameTypeDescriptionDefault ValueRequired

ID Expression

Expression

The expression Mule uses to generate the ID. You can use a DataWeave function to calculate the ID, or you can extract the ID from any existing value of the Mule message.

#[correlationId]

No

Value Expression

Expression

This parameter is not used. Setting a value has no effect.

#[correlationId]

No

Object Store

Object Store

Either a name to reference a global object store or a definition of a private object store where the component stores the processed message IDs.

Object Store created by the Object Store Manager. Not persistent, with an entry TTL of 5 MINUTES and an expiration interval of 6 SECONDS.

No

Store Prefix

String

Defines the prefix of the object store names. This value is used only for the internally built object store.

configFileName.flowName.IdempotentMessageValidator

No

### Throws - `MULE:DUPLICATE_MESSAGE` ## See Also - [Crypto (dw::Crypto)](https://docs.mulesoft.com/dataweave/latest/dw-crypto) --- product: Mule Runtime version: 4.3 --- # Introduction to Mule 4 for Mule 3 Users > For the full documentation index, see: https://docs.mulesoft.com/llms.txt If you are a user that already knows Mule 3 and recently migrated to Mule 4, review the following introduction to learn the main changes in Mule 4. If you are an experienced Mule 4 user, go directly to our [Mule Runtime](https://docs.mulesoft.com/mule-runtime/4.3/) documentation instead. Mule 4 simplifies the expression language and reduces management complexity so that you can speed up the on-ramping process and deliver applications faster than in Mule 3. Conceptually, you can think of Mule 4 as an evolution of Mule 3. Many of the core concepts are the same: applications, flows, connectors, DataWeave, and so on. However, because it is simpler, there is less to learn and less for you to manage. This overview takes you through the high-level changes in Mule 4 so that you can quickly learn the basics. It covers these topics: - [Mule Message](https://docs.mulesoft.com/mule-runtime/4.3/intro-mule-message) The Mule Message structure has evolved to make it easier to work with properties and to provide more consistency across connectors. - [Expression language](https://docs.mulesoft.com/mule-runtime/4.3/intro-expressions) The Mule Expression Language has been replaced with the DataWeave language so that you work with data and learn Mule more easily. - [Connectors](https://docs.mulesoft.com/mule-runtime/4.3/intro-connectors) The approach to connectivity was unified in Mule 4. Mule 3 transports were replaced with new operation-oriented connectors that are easier to use, have better out-of-the-box defaults, and provide new advanced capabilities. - [Error Handling](https://docs.mulesoft.com/mule-runtime/4.3/intro-error-handlers) Easier and more powerful error handling with a new Try scope. - [DataWeave](https://docs.mulesoft.com/mule-runtime/4.3/intro-dataweave2) DataWeave includes minor changes to simplify the syntax and make it easier to learn. - [Studio 7](https://docs.mulesoft.com/mule-runtime/4.3/intro-studio) Features a simplified palette, improved Maven integration, and many other usability improvements. - [Runtime engine](https://docs.mulesoft.com/mule-runtime/4.3/intro-engine) The internal execution engine has been updated with a new self-tuning and non-blocking reactive engine. This allows for better performance and scalability out-of-the-box. --- product: Mule Runtime version: 4.4 --- # Introduction to Mule 4 for Mule 3 Users > For the full documentation index, see: https://docs.mulesoft.com/llms.txt If you are a user that already knows Mule 3 and recently migrated to Mule 4, review the following introduction to learn the main changes in Mule 4. If you are an experienced Mule 4 user, go directly to our [Mule Runtime](https://docs.mulesoft.com/mule-runtime/4.4/) documentation instead. Mule 4 simplifies the expression language and reduces management complexity so that you can speed up the on-ramping process and deliver applications faster than in Mule 3. Conceptually, you can think of Mule 4 as an evolution of Mule 3. Many of the core concepts are the same: applications, flows, connectors, DataWeave, and so on. However, because it is simpler, there is less to learn and less for you to manage. This overview takes you through the high-level changes in Mule 4 so that you can quickly learn the basics. It covers these topics: - [Mule Message](https://docs.mulesoft.com/mule-runtime/4.4/intro-mule-message) The Mule Message structure has evolved to make it easier to work with properties and to provide more consistency across connectors. - [Expression language](https://docs.mulesoft.com/mule-runtime/4.4/intro-expressions) The Mule Expression Language has been replaced with the DataWeave language so that you work with data and learn Mule more easily. - [Connectors](https://docs.mulesoft.com/mule-runtime/4.4/intro-connectors) The approach to connectivity was unified in Mule 4. Mule 3 transports were replaced with new operation-oriented connectors that are easier to use, have better out-of-the-box defaults, and provide new advanced capabilities. - [Error Handling](https://docs.mulesoft.com/mule-runtime/4.4/intro-error-handlers) Easier and more powerful error handling with a new Try scope. - [DataWeave](https://docs.mulesoft.com/mule-runtime/4.4/intro-dataweave2) DataWeave includes minor changes to simplify the syntax and make it easier to learn. - [Studio 7](https://docs.mulesoft.com/mule-runtime/4.4/intro-studio) Features a simplified palette, improved Maven integration, and many other usability improvements. - [Runtime engine](https://docs.mulesoft.com/mule-runtime/4.4/intro-engine) The internal execution engine has been updated with a new self-tuning and non-blocking reactive engine. This allows for better performance and scalability out-of-the-box. --- product: Mule Runtime version: 4.3 --- # Introduction to Mule 4: Configuring Mule Apps > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 3, Spring property placeholders are often used to configure apps dynamically for the environment in which they are deployed. Mule 4 contains a built-in mechanism for this that allows you to set default values and avoid the need to learn Spring. These properties are stored in a YAML file: ```yaml http: path: service port: "10000" ``` You can add the YAML file to your Mule app through the Global Element called Configuration Properties. The XML for it looks like this: ```xml ``` MuleSoft highly recommends that you do not package the configuration files for all the environments inside your app. Instead, you should use this file to provide defaults, then use Runtime Manager to override each of these properties at deployment time. ## See Also [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.3/configuring-properties) --- product: Mule Runtime version: 4.4 --- # Introduction to Mule 4: Configuring Mule Apps > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 3, Spring property placeholders are often used to configure apps dynamically for the environment in which they are deployed. Mule 4 contains a built-in mechanism for this that allows you to set default values and avoid the need to learn Spring. These properties are stored in a YAML file: ```yaml http: path: service port: "10000" ``` You can add the YAML file to your Mule app through the Global Element called Configuration Properties. The XML for it looks like this: ```xml ``` MuleSoft highly recommends that you do not package the configuration files for all the environments inside your app. Instead, you should use this file to provide defaults, then use Runtime Manager to override each of these properties at deployment time. ## See Also [Configure Properties](https://docs.mulesoft.com/mule-runtime/4.4/configuring-properties) --- product: Mule Runtime version: 4.3 --- # Introduction to Mule 4: Connectors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 3 offered two ways of connecting to systems: transports and connectors. Transports used the concept of inbound and outbound endpoints to send data. Connectors used the concept of operations to invoke systems, for example, `` or ``. In Mule 3, MuleSoft started to replace some of these transports through the new HTTP and Database connectors. Mule 4 completes this change by completely standardizing the approach so that all connectivity is built as connectors. This change improves the consistency and usability of connectors, and it enables more powerful connectors. ## Independent Release Cycles for Core Connectors and Modules Another big difference is how the connectors are shipped and released. In Mule 3, a number of connectors/transports were part of the Mule Runtime distribution (for example, File, Ftp, Sftp, HTTP, Database, JMS, XML, Validations, and so on). To get fixes and enhancements to any of these connectors, it was necessary to wait for the next Mule Runtime release. Meanwhile, other connectors (typically the SaaS connectors) were shipped and released independently (for example, Salesforce, Workday, ServiceNow, SAP, and so on). Mule 4 standardizes the latest model. The Mule 4 distribution ships with no connectors or modules. Instead, each application includes the modules it needs. This approach has the following advantages: - Faster innovation in core modules/connectors because all connectors have their own release cycle. New features and bug fixes can become available without the need to wait for the next Mule Runtime release. - Ability for different apps to use different versions of the same module. This allows for easier adoption of new releases without the need to run a full regression on applications that don’t require the upgrade. - Consistent approach. --- product: Mule Runtime version: 4.4 --- # Introduction to Mule 4: Connectors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 3 offered two ways of connecting to systems: transports and connectors. Transports used the concept of inbound and outbound endpoints to send data. Connectors used the concept of operations to invoke systems, for example, `` or ``. In Mule 3, MuleSoft started to replace some of these transports through the new HTTP and Database connectors. Mule 4 completes this change by completely standardizing the approach so that all connectivity is built as connectors. This change improves the consistency and usability of connectors, and it enables more powerful connectors. ## Independent Release Cycles for Core Connectors and Modules Another big difference is how the connectors are shipped and released. In Mule 3, a number of connectors/transports were part of the Mule Runtime distribution (for example, File, Ftp, Sftp, HTTP, Database, JMS, XML, Validations, and so on). To get fixes and enhancements to any of these connectors, it was necessary to wait for the next Mule Runtime release. Meanwhile, other connectors (typically the SaaS connectors) were shipped and released independently (for example, Salesforce, Workday, ServiceNow, SAP, and so on). Mule 4 standardizes the latest model. The Mule 4 distribution ships with no connectors or modules. Instead, each application includes the modules it needs. This approach has the following advantages: - Faster innovation in core modules/connectors because all connectors have their own release cycle. New features and bug fixes can become available without the need to wait for the next Mule Runtime release. - Ability for different apps to use different versions of the same module. This allows for easier adoption of new releases without the need to run a full regression on applications that don’t require the upgrade. - Consistent approach. --- product: Mule Runtime version: 4.3 --- # Introduction to Mule 4: DataWeave 2.0 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt DataWeave 2 is largely unchanged from DataWeave 1. However, MuleSoft made many improvements to make it easier to learn and added new capabilities. ## Operators Are Functions In DataWeave 2, all operators are now functions. While this can involve more parentheses, it is less ambiguous and more friendly to learn through auto-completion features. The previous syntax continues to work for functions with two parameters, providing a shorter syntax for power users.

DataWeave 1

sizeOf payload filter $.age > 30

DataWeave 2 - Function Syntax

sizeOf(filter(payload, (value) → value.age > 30)))

DataWeave 2 - Shortcut Syntax

sizeOf(payload filter $.age > 30)

## Traits Are Functions

DataWeave 1

payload is :empty

DataWeave 2

isEmpty(payload)

## Type Names DataWeave 2 uses a type name syntax, which removes the `:` from the name.

DataWeave 1

payload.foo as :string

DataWeave 2

payload.foo as String

## XML Format The default for the reader property `nullValueOn` is `empty` for DataWeave 2.0. For DataWeave 1.0 (which is compatible with Mule 3.x), the value is `none`, for example: DataWeave Script ```dataweave %dw 1.0 %output application/xml nullValueOn="none" --- payload ``` Input ```xml ``` Output ```xml ``` ## New Capabilities There are also many new capabilities, including: - Typing for reusable functions - Multi-line comments - Ability to call out to Java code - Multipart, URL-encoded, and text readers and writers - Modules and imports - and more ## See Also [Migrating from DataWeave 1.0 to 2.x](https://docs.mulesoft.com/mule-runtime/4.3/migration-dataweave) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) --- product: Mule Runtime version: 4.4 --- # Introduction to Mule 4: DataWeave 2.0 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt DataWeave 2 is largely unchanged from DataWeave 1. However, MuleSoft made many improvements to make it easier to learn and added new capabilities. ## Operators Are Functions In DataWeave 2, all operators are now functions. While this can involve more parentheses, it is less ambiguous and more friendly to learn through auto-completion features. The previous syntax continues to work for functions with two parameters, providing a shorter syntax for power users.

DataWeave 1

sizeOf payload filter $.age > 30

DataWeave 2 - Function Syntax

sizeOf(filter(payload, (value) → value.age > 30)))

DataWeave 2 - Shortcut Syntax

sizeOf(payload filter $.age > 30)

## Traits Are Functions

DataWeave 1

payload is :empty

DataWeave 2

isEmpty(payload)

## Type Names DataWeave 2 uses a type name syntax, which removes the `:` from the name.

DataWeave 1

payload.foo as :string

DataWeave 2

payload.foo as String

## XML Format The default for the reader property `nullValueOn` is `empty` for DataWeave 2.0. For DataWeave 1.0 (which is compatible with Mule 3.x), the value is `none`, for example: DataWeave Script ```dataweave %dw 1.0 %output application/xml nullValueOn="none" --- payload ``` Input ```xml ``` Output ```xml ``` ## New Capabilities There are also many new capabilities, including: - Typing for reusable functions - Multi-line comments - Ability to call out to Java code - Multipart, URL-encoded, and text readers and writers - Modules and imports - and more ## See Also [Migrating from DataWeave 1.0 to 2.x](https://docs.mulesoft.com/mule-runtime/4.4/migration-dataweave) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) --- product: Mule Runtime version: 4.3 --- # Introduction to Mule 4: DataWeave Expression Language > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 3, you must learn both the Mule Expression Language (MEL) and DataWeave. MEL forces you to convert your payloads from binary data (such as XML or JSON documents) into Java objects so that you can write expressions that access that data, for example, when routing to a specific location. In Mule 4, DataWeave is the default expression language. Combined with the built-in streaming capabilities, this change simplifies many common tasks: - Events can be routed based on payload data, without requiring conversion to Java objects. - Binary data can easily be queried from an expression anywhere in your flow, for example, when logging. - Streaming now happens transparently. You no longer need to worry about larger-than-memory data streams or about consuming a stream twice. DataWeave 2.0 also features many improvements, which are covered in the [DataWeave 2.0](https://docs.mulesoft.com/mule-runtime/4.3/intro-dataweave2) section. At the core, expressions continue to work as before. You can use them to extract data, log data, or make decisions about where to route data. And like MEL, the syntax to access properties in your data is very simple. ```xml ``` Unlike MEL, you can use DataWeave to easily access data anywhere in your flow without concern for transforming it into intermediate objects. Consider this example in Mule 3: ```xml ``` In Mule 4, you no longer need to convert JSON to an intermediate format. You can simply access the data directly through expressions without losing the original underlying data, and Mule 4 handles all data streaming and random access transparently for you. ```xml ``` ## See Also [Transformations and Streaming](https://docs.mulesoft.com/mule-runtime/4.3/intro-transformations) [Migrating from DataWeave 1.0 to 2.x](https://docs.mulesoft.com/mule-runtime/4.3/migration-dataweave) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) --- product: Mule Runtime version: 4.4 --- # Introduction to Mule 4: DataWeave Expression Language > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 3, you must learn both the Mule Expression Language (MEL) and DataWeave. MEL forces you to convert your payloads from binary data (such as XML or JSON documents) into Java objects so that you can write expressions that access that data, for example, when routing to a specific location. In Mule 4, DataWeave is the default expression language. Combined with the built-in streaming capabilities, this change simplifies many common tasks: - Events can be routed based on payload data, without requiring conversion to Java objects. - Binary data can easily be queried from an expression anywhere in your flow, for example, when logging. - Streaming now happens transparently. You no longer need to worry about larger-than-memory data streams or about consuming a stream twice. DataWeave 2.0 also features many improvements, which are covered in the [DataWeave 2.0](https://docs.mulesoft.com/mule-runtime/4.4/intro-dataweave2) section. At the core, expressions continue to work as before. You can use them to extract data, log data, or make decisions about where to route data. And like MEL, the syntax to access properties in your data is very simple. ```xml ``` Unlike MEL, you can use DataWeave to easily access data anywhere in your flow without concern for transforming it into intermediate objects. Consider this example in Mule 3: ```xml ``` In Mule 4, you no longer need to convert JSON to an intermediate format. You can simply access the data directly through expressions without losing the original underlying data, and Mule 4 handles all data streaming and random access transparently for you. ```xml ``` ## See Also [Transformations and Streaming](https://docs.mulesoft.com/mule-runtime/4.4/intro-transformations) [Migrating from DataWeave 1.0 to 2.x](https://docs.mulesoft.com/mule-runtime/4.4/migration-dataweave) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) --- product: Mule Runtime version: 4.3 --- # Introduction to Mule 4: Error Handlers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, error handling is no longer limited to a Java exception handling process that requires you to check the source code or force an error in order to understand what happened. Though Java `Throwable` errors and exceptions are still available, Mule 4 introduces a formal Error concept that’s easier to use. Now, each component declares the type of errors it can throw, so you can identify potential errors at design time. ## Mule Errors Execution failures are represented with Mule errors that have the following components: - A description of the problem. - A type that is used to characterize the problem. - A cause, the underlying Java `Throwable` that resulted in the failure. - An optional error message, which is used to include a proper Mule Message regarding the problem. For example, when an HTTP request fails with a 401 status code, a Mule error provides the following information: Description: HTTP GET on resource ‘http://localhost:36682/testPath’ failed: unauthorized (401) Type: HTTP:UNAUTHORIZED Cause: a ResponseValidatorTypedException instance Error Message: { "message" : "Could not authorize the user." } ## Error Types In the example above, the error type is `HTTP:UNAUTHORIZED`, not simply `UNAUTHORIZED`. Error types consist of both a namespace and an identifier, allowing you to distinguish the types according to their domain (for example, `HTTP:NOT_FOUND` and `FILE:NOT_FOUND`). While connectors define their own namespace, core runtime errors have an implicit one: `MULE:EXPRESSION` and `EXPRESSION` are interpreted as one. Another important characteristic of error types is that they might have a parent type. For example, `HTTP:UNAUTHORIZED` has `MULE:CLIENT_SECURITY` as the parent, which, in turn, has `MULE:SECURITY` as the parent. This establishes error types as specifications of more global ones: an HTTP unauthorized error is a kind of client security error, which is a type of a more broad security issue. These hierarchies mean routing can be more general, since, for example, a handler for `MULE:SECURITY` catches HTTP unauthorized errors as well as OAuth errors. Below you can see what the core runtime hierarchy looks like: ![Error Hierarchy](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-hierarchy.png) All errors are either general or `CRITICAL`, the latter being so severe that they cannot be handled. At the top of the general hierarchy is `ANY`, which allows matching all types under it. It’s important to note the `UNKNOWN` type, which is used when no clear reason for the failure is found. This error can only be handled through the `ANY` type to allow specifying the unclear errors in the future, without changing the existing app’s behavior. When it comes to connectors, each connector defines its error type hierarchy considering the core runtime one, though `CONNECTIVITY` and `RETRY_EXHAUSTED` types are always present because they are common to all connectors. ## Error Handlers Mule 4 has redesigned error handling by introducing the `error-handler` component, which can contain any number of internal handlers and can route an error to the first one matching it. Such handlers are `on-error-continue` and `on-error-propagate`, which both support matching through an error type (or group of error types) or through an expression (for advanced use cases). These are quite similar to the Mule 3 choice (`choice-exception-strategy`), catch (`catch-exception-strategy`), and rollback (`rollback-exception-strategy`) exceptions strategies However, they are much simpler and more consistent. If an error is raised in Mule 4, an error handler is executed and the error is routed to the first matching handler. At this point, the error is available for inspection, so the handlers can execute and act accordingly, relative to the component where they are used (a Flow or Try scope): - An `on-error-continue` executes and uses the result of the execution as the result of its owner (as though the owner completed the execution successfully). Any transactions at this point are committed, as well. - An `on-error-propagate` rolls back any transactions, executes, and uses that result to re-throw the existing error, meaning its owner is considered to be “failing.” Consider the following application where an HTTP listener triggers a Flow Reference component to another flow that performs an HTTP request. If everything goes right when a message is received (1 below), the reference is triggered (2), and the request performed (3), which results in a successful response (HTTP status code 200) (4). ![Error Handling Example 1](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-handling-example-1.png) If the HTTP request fails with an `HTTP:NOT_FOUND` error (see 3 below) because of the error handler configuration in `inner-flow`, the error is propagated (4), and the Flow Reference component fails (2). However, because `primary-flow` handles the error with `on-error-continue`, the Logger it contains (5) executes, and a successful response (HTTP status code 200) is returned (6). ![Error Handling Example 1](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-handling-example-2.png) If the request fails with an unauthorized error instead (3), then `inner-flow` handles it with an `on-error-continue` by retrieving static content from a file (4). Then the Flow Reference component is successful as well (2), and a successful response (HTTP status code 200) is returned (5). ![Error Handling Example 3](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-handling-example-3.png) But what if another error occurred in the HTTP request? Although there are only handlers for `NOT_FOUND` and `UNAUTHORIZED` errors in the flow, errors are still propagated by default. This means that if no handler matches the error that is raised, then it is re-thrown. For example, if the request fails with a method not allowed error (3), then it is propagated, causing the Flow Reference component to fail (2), and that propagation results in a failure response (4). ![Error Handling Example 4](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-handling-example-4.png) The scenario above can be avoided by making the last handler match `ANY`, instead of just `HTTP:UNAUTHORIZED`. Notice how, below, all the possible errors of an `HTTP` request are suggested: ![Error Handling Any](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-handling-any.png) You can also match errors using an expression. For example, since the Mule Error is available during error handling, we can use it to match all errors with the HTTP namespace: ![Error Handling Expression](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-handling-expression.png) ## Try Scope For the most part, Mule 3 only allows error handling at the flow level, forcing you to extract logic to a flow in order to address errors. In Mule 4, we’ve introduced a Try scope that you can use within a flow to do error handling of just inner components. The scope also supports transactions, which replaces the old Transactional scope. ![Try Scope](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-handling-try.png) In the previous example, On Error Propagate component is configured to propagate database connection errors, causing the `try` to fail and the flow’s error handler to execute. On Error Continue component is configured to handle any other error. The Try scope’s execution is successful for that case, which means that the flow’s execution continues with the next processor, an HTTP Request operation. ## Error Mapping Mule 4 now also allows for mapping default errors to custom ones. The Try scope is useful, but if you have several equal components and want to distinguish the errors of each one, using a Try on them can clutter your app. Instead, you can add error mappings to each component, meaning that all or certain kind of errors streaming from the component are mapped to another error of your choosing. If, for example, you are aggregating results from 2 APIs using an HTTP request component for each, you might want to distinguish between the errors of API 1 and API 2, since by default, their errors are the same. By mapping errors from the first request to a custom `API_1` error and errors in the second request to `API_2`, you can route those errors to different handlers. The next example maps `HTTP:INTERNAL_SERVER_ERROR` so that different handling policies can be applied if the APIs go down (propagating the error in the first API and handling it in the second API). ![Error Handling Mappings](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-handling-mappings.png) ## See Also - [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.3/error-handling) - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.3/mule-error-concept) - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.3/on-error-scope-concept) - [Try Scope](https://docs.mulesoft.com/mule-runtime/4.3/try-scope-concept) --- product: Mule Runtime version: 4.4 --- # Introduction to Mule 4: Error Handlers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, error handling is no longer limited to a Java exception handling process that requires you to check the source code or force an error in order to understand what happened. Though Java `Throwable` errors and exceptions are still available, Mule 4 introduces a formal Error concept that’s easier to use. Now, each component declares the type of errors it can throw, so you can identify potential errors at design time. ## Mule Errors Execution failures are represented with Mule errors that have the following components: - A description of the problem. - A type that is used to characterize the problem. - A cause, the underlying Java `Throwable` that resulted in the failure. - An optional error message, which is used to include a proper Mule Message regarding the problem. For example, when an HTTP request fails with a 401 status code, a Mule error provides the following information: Description: HTTP GET on resource ‘http://localhost:36682/testPath’ failed: unauthorized (401) Type: HTTP:UNAUTHORIZED Cause: a ResponseValidatorTypedException instance Error Message: { "message" : "Could not authorize the user." } ## Error Types In the example above, the error type is `HTTP:UNAUTHORIZED`, not simply `UNAUTHORIZED`. Error types consist of both a namespace and an identifier, allowing you to distinguish the types according to their domain (for example, `HTTP:NOT_FOUND` and `FILE:NOT_FOUND`). While connectors define their own namespace, core runtime errors have an implicit one: `MULE:EXPRESSION` and `EXPRESSION` are interpreted as one. Another important characteristic of error types is that they might have a parent type. For example, `HTTP:UNAUTHORIZED` has `MULE:CLIENT_SECURITY` as the parent, which, in turn, has `MULE:SECURITY` as the parent. This establishes error types as specifications of more global ones: an HTTP unauthorized error is a kind of client security error, which is a type of a more broad security issue. These hierarchies mean routing can be more general, since, for example, a handler for `MULE:SECURITY` catches HTTP unauthorized errors as well as OAuth errors. Below you can see what the core runtime hierarchy looks like: ![Error Hierarchy](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-hierarchy.png) All errors are either general or `CRITICAL`, the latter being so severe that they cannot be handled. At the top of the general hierarchy is `ANY`, which allows matching all types under it. It’s important to note the `UNKNOWN` type, which is used when no clear reason for the failure is found. This error can only be handled through the `ANY` type to allow specifying the unclear errors in the future, without changing the existing app’s behavior. When it comes to connectors, each connector defines its error type hierarchy considering the core runtime one, though `CONNECTIVITY` and `RETRY_EXHAUSTED` types are always present because they are common to all connectors. ## Error Handlers Mule 4 has redesigned error handling by introducing the `error-handler` component, which can contain any number of internal handlers and can route an error to the first one matching it. Such handlers are `on-error-continue` and `on-error-propagate`, which both support matching through an error type (or group of error types) or through an expression (for advanced use cases). These are quite similar to the Mule 3 choice (`choice-exception-strategy`), catch (`catch-exception-strategy`), and rollback (`rollback-exception-strategy`) exceptions strategies However, they are much simpler and more consistent. If an error is raised in Mule 4, an error handler is executed and the error is routed to the first matching handler. At this point, the error is available for inspection, so the handlers can execute and act accordingly, relative to the component where they are used (a Flow or Try scope): - An `on-error-continue` executes and uses the result of the execution as the result of its owner (as though the owner completed the execution successfully). Any transactions at this point are committed, as well. - An `on-error-propagate` rolls back any transactions, executes, and uses that result to re-throw the existing error, meaning its owner is considered to be “failing.” Consider the following application where an HTTP listener triggers a Flow Reference component to another flow that performs an HTTP request. If everything goes right when a message is received (1 below), the reference is triggered (2), and the request performed (3), which results in a successful response (HTTP status code 200) (4). ![Error Handling Example 1](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-handling-example-1.png) If the HTTP request fails with an `HTTP:NOT_FOUND` error (see 3 below) because of the error handler configuration in `inner-flow`, the error is propagated (4), and the Flow Reference component fails (2). However, because `primary-flow` handles the error with `on-error-continue`, the Logger it contains (5) executes, and a successful response (HTTP status code 200) is returned (6). ![Error Handling Example 1](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-handling-example-2.png) If the request fails with an unauthorized error instead (3), then `inner-flow` handles it with an `on-error-continue` by retrieving static content from a file (4). Then the Flow Reference component is successful as well (2), and a successful response (HTTP status code 200) is returned (5). ![Error Handling Example 3](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-handling-example-3.png) But what if another error occurred in the HTTP request? Although there are only handlers for `NOT_FOUND` and `UNAUTHORIZED` errors in the flow, errors are still propagated by default. This means that if no handler matches the error that is raised, then it is re-thrown. For example, if the request fails with a method not allowed error (3), then it is propagated, causing the Flow Reference component to fail (2), and that propagation results in a failure response (4). ![Error Handling Example 4](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-handling-example-4.png) The scenario above can be avoided by making the last handler match `ANY`, instead of just `HTTP:UNAUTHORIZED`. Notice how, below, all the possible errors of an `HTTP` request are suggested: ![Error Handling Any](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-handling-any.png) You can also match errors using an expression. For example, since the Mule Error is available during error handling, we can use it to match all errors with the HTTP namespace: ![Error Handling Expression](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-handling-expression.png) ## Try Scope For the most part, Mule 3 only allows error handling at the flow level, forcing you to extract logic to a flow in order to address errors. In Mule 4, we’ve introduced a Try scope that you can use within a flow to do error handling of just inner components. The scope also supports transactions, which replaces the old Transactional scope. ![Try Scope](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-handling-try.png) In the previous example, On Error Propagate component is configured to propagate database connection errors, causing the `try` to fail and the flow’s error handler to execute. On Error Continue component is configured to handle any other error. The Try scope’s execution is successful for that case, which means that the flow’s execution continues with the next processor, an HTTP Request operation. ## Error Mapping Mule 4 now also allows for mapping default errors to custom ones. The Try scope is useful, but if you have several equal components and want to distinguish the errors of each one, using a Try on them can clutter your app. Instead, you can add error mappings to each component, meaning that all or certain kind of errors streaming from the component are mapped to another error of your choosing. If, for example, you are aggregating results from 2 APIs using an HTTP request component for each, you might want to distinguish between the errors of API 1 and API 2, since by default, their errors are the same. Mapping enables you to customize error handling by routing errors to the appropriate error handler. The following example routes errors from the first Request operation to the error handler `APP:API_1` and routes errors from the second Request operation to `APP:API_2`. To apply different handling policies if the APIs go down, the example maps `HTTP:INTERNAL_SERVER_ERROR` to each error handler. One mapping propagates the error if it comes from the first API. The other handles the error if it comes from the second API. ![Error Handling Mappings](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-handling-mappings.png) ## See Also - [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.4/error-handling) - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.4/mule-error-concept) - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.4/on-error-scope-concept) - [Try Scope](https://docs.mulesoft.com/mule-runtime/4.4/try-scope-concept) --- product: Mule Runtime version: 4.3 --- # Introduction to Mule 4: Execution Engine Threads and Concurrency > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 4 has an improved execution engine that simplifies the development and scaling of Mule apps. The underlying engine is based on a reactive, non-blocking architecture. This task-oriented execution model allows you to take advantage of non-blocking IO calls and avoid performance problems due to incorrect processing strategy configurations. From a development point of view, there are a few major changes: - Exchange patterns no longer exist. All connectors receive responses. If you want to process a message asynchronously, use the Async component. - Every flow always uses a non-blocking processing strategy, and there is no need to configure processing strategies anymore. - There is a single, global thread pool for all flows. For details, see [Execution Engine](https://docs.mulesoft.com/mule-runtime/4.3/execution-engine). ## Controlling Concurrency Mule 4 decouples thread configuration from concurrency management. To control concurrency on a flow or any component that supports it, use the `maxConcurrency` attribute to set the number of simultaneous invocations that component can receive an any given time. ```xml ``` ## Thread Pools and Tuning apps Mule 4.3 contains one unique thread pool, called the UBER pool. This thread pool is managed by Mule and shared across all apps in the same Mule instance. At startup, Mule introspects the available resources (such as memory and CPU cores) in the system and tunes automatically for the environment where Mule is running. This algorithm was established through performance testing and found optimal values for most scenarios. The single thread pool allows Mule to be efficient, requiring significantly fewer threads (and their inherent memory footprint) to handle a given workload when compared to Mule 3. Mule Event processors indicate to Mule whether they are CPU intensive, CPU light, or IO intensive operations. These workload types help Mule tune for different workloads, so you don’t need to manage thread pools manually to achieve optimum performance. Instead, Mule introspects the available resources (such as memory and CPU cores) in the system to tune thread pools automatically. See [Execution Engine](https://docs.mulesoft.com/mule-runtime/4.3/execution-engine) for complete details about the new threading model and upgrade instructions. ## Upgrading from Mule 4.2/4.1 If you are upgrading from Mule 4.2.x or 4.1.x to Mule 4.3.x, take the following actions: - If there are no custom threading settings applied (either through the `scheduler-pools.conf` file or directly in the Mule app), then no action is required. - If there are custom threading configurations applied, test your Mule applications with the default configuration. Because of the UBER pool strategy and other performance updates implemented in Mule 4.3, you might not need custom threading configurations. - If tests confirm that a custom configuration is still necessary, a problem might exist with resource management in the application, one of the application dependencies, or the Mule instance. Using a custom configuration can lead to inefficient use of resources and might hide underlying issues. --- product: Mule Runtime version: 4.4 --- # Introduction to Mule 4: Execution Engine Threads and Concurrency > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 4 has an improved execution engine that simplifies the development and scaling of Mule apps. The underlying engine is based on a reactive, non-blocking architecture. This task-oriented execution model allows you to take advantage of non-blocking IO calls and avoid performance problems due to incorrect processing strategy configurations. From a development point of view, there are a few major changes: - Exchange patterns no longer exist. All connectors receive responses. If you want to process a message asynchronously, use the Async component. - Every flow always uses a non-blocking processing strategy, and there is no need to configure processing strategies anymore. - There is a single, global thread pool for all flows. For details, see [Execution Engine](https://docs.mulesoft.com/mule-runtime/4.4/execution-engine). ## Controlling Concurrency Mule 4 decouples thread configuration from concurrency management. To control concurrency on a flow or any component that supports it, use the `maxConcurrency` attribute to set the number of simultaneous invocations that component can receive an any given time. ```xml ``` ## Thread Pools and Tuning apps Starting in Mule 4.3, Mule contains one unique thread pool, called the UBER pool. This thread pool is managed by Mule and shared across all apps in the same Mule instance. At startup, Mule introspects the available resources (such as memory and CPU cores) in the system and tunes automatically for the environment where Mule is running. This algorithm was established through performance testing and found optimal values for most scenarios. The single thread pool allows Mule to be efficient, requiring significantly fewer threads (and their inherent memory footprint) to handle a given workload when compared to Mule 3. Mule Event processors indicate to Mule whether they are CPU intensive, CPU light, or IO intensive operations. These workload types help Mule tune for different workloads, so you don’t need to manage thread pools manually to achieve optimum performance. Instead, Mule introspects the available resources (such as memory and CPU cores) in the system to tune thread pools automatically. See [Execution Engine](https://docs.mulesoft.com/mule-runtime/4.4/execution-engine) for complete details about the new threading model and upgrade instructions. ## Upgrading from Mule 4.2/4.1 When upgrading from Mule 4.2.x or 4.1.x to Mule 4.3.x or later, take the following actions: - If there are no custom threading settings applied (either through the `scheduler-pools.conf` file or directly in the Mule app), then no action is required. - If there are custom threading configurations applied, test your Mule applications with the default configuration. Because of the UBER pool strategy and other performance updates implemented in Mule 4.3, you might not need custom threading configurations. - If tests confirm that a custom configuration is still necessary, a problem might exist with resource management in the application, one of the application dependencies, or the Mule instance. Using a custom configuration can lead to inefficient use of resources and might hide underlying issues. --- product: Mule Runtime version: 4.3 --- # Introduction to Mule 4: Java Integration > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## Expressions versus Code Experienced Mule users will notice that Mule 4 takes a more opinionated approach about how to structure apps, which limits what can be done through the expression language. The intention is to provide a clear separation between the flow logic and the business logic that should be extracted through code. If you want to extract, query, transform, or otherwise work with data in your flows, DataWeave expressions and transforms are the recommended tool. If you want to write custom logic, instantiate Java objects, or call arbitrary methods, MuleSoft recommends that you encapsulate this code into scripts or classes that can be injected and tested easily. This is why MuleSoft removed the Expression component and Expression transformer in favor of encouraging you to cleanly separate your logic into scripts or Java classes, instead. ## Calling Static Java Methods from DataWeave When you want to call out to Java logic to help format or parse data, DataWeave now allows you to call out to static methods. Consider this Java method: ```java package org.acme; public class MyCompanyUtils { public static String reformat(String input) { return …; } } ``` You can call it through the following DataWeave code: ```dataweave import java!org::acme::MyCompanyUtils --- { date: MyCompanyUtils::reformat(payload.input) } ``` ## Scripting Module The Scripting module replaces the Mule 3 Scripting component. The Mule 4 module enables you to embed your Groovy, Ruby, Python, or JavaScript scripts inside Mule flows. You can inject data from the Mule message into your code using the new `parameters` configuration attribute. ```xml return "$payload $prop1 $prop2" #[{prop1: "Received", prop2: payload.body}] ``` To use the scripting module, simply add it to your app using the Studio palette, or add the following dependency in your `pom.xml` file: ```xml org.mule.modules mule-scripting-module 1.1.0 mule-plugin ``` For more detail on this module, see [Scripting Module Documentation](https://docs.mulesoft.com/scripting-module/latest/). ## Java Module While the Scripting module is a very powerful tool that allows for interoperation with Java by executing any random set of instructions, often you simply need to just instantiate a class or execute a single method. While Mule 3 usually relies on MEL for this, the Java module was introduced in Mule 4 to allow for these use cases. Other advantages of the Java module over the Scripting module are: - Support for [DataSense](https://docs.mulesoft.com/studio/datasense-explorer): Each time you execute a method, you will get DataSense for the output type and the method’s input arguments. - UI Support: You get visual aids in terms of methods available for each class, autocompletion, and so on. ### Create a New Java Instance In Mule 3: ```xml ``` In Mule 4: ```xml #[{name: 'some string arg', apple: vars.apple}] ``` ### Invoke an Instance Method In Mule 3: ```xml flowVars.appleEater.chew(500) ``` In Mule 4: ```xml #[{chewingTime: 500}] ``` The `invoke` functionality can also be used through DataWeave functions: ```xml ``` To use the Java module, simply add it to your application using the Studio palette, or add the following dependency to your `pom.xml` file: ```xml org.mule.module mule-java-module 1.0.0 mule-plugin ``` ## See Also - [Scripting Module](https://docs.mulesoft.com/scripting-module/latest/) - [Java Module](https://docs.mulesoft.com/java-module/latest/) --- product: Mule Runtime version: 4.4 --- # Introduction to Mule 4: Java Integration > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## Expressions versus Code Experienced Mule users will notice that Mule 4 takes a more opinionated approach about how to structure apps, which limits what can be done through the expression language. The intention is to provide a clear separation between the flow logic and the business logic that should be extracted through code. If you want to extract, query, transform, or otherwise work with data in your flows, DataWeave expressions and transforms are the recommended tool. If you want to write custom logic, instantiate Java objects, or call arbitrary methods, MuleSoft recommends that you encapsulate this code into scripts or classes that can be injected and tested easily. This is why MuleSoft removed the Expression component and Expression transformer in favor of encouraging you to cleanly separate your logic into scripts or Java classes, instead. ## Calling Static Java Methods from DataWeave When you want to call out to Java logic to help format or parse data, DataWeave now allows you to call out to static methods. Consider this Java method: ```java package org.acme; public class MyCompanyUtils { public static String reformat(String input) { return …; } } ``` You can call it through the following DataWeave code: ```dataweave import java!org::acme::MyCompanyUtils --- { date: MyCompanyUtils::reformat(payload.input) } ``` ## Scripting Module The Scripting module replaces the Mule 3 Scripting component. The Mule 4 module enables you to embed your Groovy, Ruby, Python, or JavaScript scripts inside Mule flows. You can inject data from the Mule message into your code using the new `parameters` configuration attribute. ```xml return "$payload $prop1 $prop2" #[{prop1: "Received", prop2: payload.body}] ``` To use the scripting module, simply add it to your app using the Studio palette, or add the following dependency in your `pom.xml` file: ```xml org.mule.modules mule-scripting-module 1.1.0 mule-plugin ``` For more detail on this module, see [Scripting Module Documentation](https://docs.mulesoft.com/scripting-module/latest/). ## Java Module While the Scripting module is a very powerful tool that allows for interoperation with Java by executing any random set of instructions, often you simply need to just instantiate a class or execute a single method. While Mule 3 usually relies on MEL for this, the Java module was introduced in Mule 4 to allow for these use cases. Other advantages of the Java module over the Scripting module are: - Support for [DataSense](https://docs.mulesoft.com/studio/datasense-explorer): Each time you execute a method, you will get DataSense for the output type and the method’s input arguments. - UI Support: You get visual aids in terms of methods available for each class, autocompletion, and so on. ### Create a New Java Instance In Mule 3: ```xml ``` In Mule 4: ```xml #[{name: 'some string arg', apple: vars.apple}] ``` ### Invoke an Instance Method In Mule 3: ```xml flowVars.appleEater.chew(500) ``` In Mule 4: ```xml #[{chewingTime: 500}] ``` The `invoke` functionality can also be used through DataWeave functions: ```xml ``` To use the Java module, simply add it to your application using the Studio palette, or add the following dependency to your `pom.xml` file: ```xml org.mule.module mule-java-module 1.0.0 mule-plugin ``` ## See Also - [Scripting Module](https://docs.mulesoft.com/scripting-module/latest/) - [Java Module](https://docs.mulesoft.com/java-module/latest/) --- product: Mule Runtime version: 4.3 --- # Introduction to Mule 4: Mule Message > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 4 includes a simplified Mule message model in which each Mule event has a message and associated variables. - A Mule message is composed of a payload and its attributes (metadata, such as file size). - Variables (`vars`) which hold arbitrary user information such as operation results, auxiliary values, and so on. In general, operations do not automatically propagate variables to other components, like a listener. Though, if you use the Flow Reference component it does propagate variables within flows. This simplified message model makes it easier to work with data in a consistent way across connectors without overwriting information. ![Mule Event and Message](/mulesoft/current/en-us/mule-runtime/4.3/_images/mruntime-message-diagram.png) Figure 1. Mule Event and Message. ## Inbound Properties Are Now Attributes In Mule 3, inbound properties stored additional information about a payload obtained through a Message Source, such as the query parameters coming through an HTTP listener. **Attributes** in Mule 4 replace inbound properties and have these advantages: - They are strongly typed, so you can easily see what data is available. - They can easily be stored in variables that you can access throughout your flow. Here’s an HTTP listener example of a typical Mule Message in Mule 4: ![Mule Message structure in Mule 4](/mulesoft/current/en-us/mule-runtime/4.3/_images/mule-message.png) Attributes can be easily accessed through expressions, just as inbound properties were in Mule 3, for example: ```text #[attributes.requestPath] #[attributes.queryParams.searchCriteria] ``` When any Source or Operation produces a new Message as a result of its execution, **both parts of the Message (the payload and attributes) are replaced with the new values**, and the previous attributes are lost. If you need to preserve any information from the attributes across operation invocations, you can either store the previous attributes in a variable or [set the `target` parameter in the invoked operation](https://docs.mulesoft.com/mule-runtime/4.3/target-variables). Here is an example of how the Message is updated during the execution of a flow: ```xml (1) (2) (3) #[output application/xml --- { data: payload, customer: attributes.queryParams.customer_id (4) }] (5) #[output application/json --- { customer: requestAttributes.queryParams.customer_id, (6) invoiceTrackingNumber: attributes.properties.userProperties.invoiceTrackingNumber }] (7) (8) ```
1A request is received, and the http:listener produces a Message with the request payload and the HTTP Attributes.
2Because the logger is a void operation and does not produce any output, the Message remains the same after its execution.
3The example stores the current HTTP Attributes in a variable to make use of them later in the flow because the next operation will replace the current Message.
4HTTP Attributes are still available to configure the jms:publish-consume operation input.
5Once the jms:publish-consume is invoked, the output of the operation is a Message with a different payload and the JMS Attributes.
6Since the HTTP Attributes are stored in a variable, it is possible to use both the current JMS Attributes (as attributes) and the previously stored HTTP information.
7The jms:publish operation is also void. Because no output is produced, the Message remains unmodified.
8At this point, JMS Attributes from the jms:publish-consume invocation still exist.
## Outbound Properties In Mule 3, Mule connectors and transports that need to send additional data, such as headers, must explicitly specify Outbound properties. For example, with the HTTP listener, you might want to specify the outgoing status code response or headers. In Mule 4, you can set each of those separately using an individual DataWeave expression for each one of them, without introducing any side effects in the main flow: ```xml #[{'path':'input/issues-list.json'}] #[{'provider':'memory-provider'}] ``` The previous example performs an HTTP request in which individual DataWeave scripts generate headers and query parameters without the need to set message properties and without generating any side effects on the message. The same concept can be applied for message sources that emits responses, such an HTTP listener: ```xml #[vars.outboundHeaders default {}] #[payload] #[vars.outboundHeaders default {}] ``` In the previous example, `http:headers` settings like `vars.httpStatus default 200` set a default value for a variable if the actual value resolves to `null`. ## Session Properties Session properties are no longer needed and have been removed in Mule 4. Instead, store data in target variables using the Target (`target`) parameter. These properties are not needed because Mule 3 transports and their associated transport barriers do not exist in Mule 4. Mule 3 transport barriers determine how to handle Mule message data that moves through Mule 3 flows. Transports are replaced by corresponding Mule connectors (such as the FTP connector) in Mule 4, which handle networking transport protocols differently. For examples, see [Migrating the Enricher to a Target Variable](https://docs.mulesoft.com/mule-runtime/4.3/migration-core-enricher) and [Enrich Data with Target Variables](https://docs.mulesoft.com/mule-runtime/4.3/target-variables). ## Attachments Inbound and outbound attachments have been removed. The affected connectors now handle the attachment concept on their own: - HTTP now relies on DataWeave’s multipart format support. - Email and Web Service Consumer allow attachments to be explicitly added using DataWeave. ## Message Collections One of the benefits of the new Mule Message structure is when dealing with collections. In Mule 3, components that returned multiple payloads, used a special structure called the `MuleMessageCollection`. In Mule 4, any component that needs to deal with multiple messages can simply set the payload of the message to a List of Mule Messages. You can then iterate over these messages using DataWeave, For Each, or other components. For example, the `` operation retrieves a List of Messages. Each message has attributes for each file, which makes it easy to make decisions based on file size, whether it’s a directory, and so on. ## See Also - [Migrating HTTP Connector Uses](https://docs.mulesoft.com/mule-runtime/4.3/migration-connectors-http) - [Supported Data Formats](https://docs.mulesoft.com/dataweave/2.3/dataweave-formats) - [DataWeave Variables](https://docs.mulesoft.com/dataweave/2.3/dataweave-variables) - [Migrating the Enricher to a Target Variable](https://docs.mulesoft.com/mule-runtime/4.3/migration-core-enricher) --- product: Mule Runtime version: 4.4 --- # Introduction to Mule 4: Mule Message > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 4 includes a simplified Mule message model in which each Mule event has a message and associated variables. - A Mule message is composed of a payload and its attributes (metadata, such as file size). - Variables (`vars`) which hold arbitrary user information such as operation results, auxiliary values, and so on. In general, operations do not automatically propagate variables to other components, like a listener. Though, if you use the Flow Reference component it does propagate variables within flows. This simplified message model makes it easier to work with data in a consistent way across connectors without overwriting information. ![Mule Event and Message](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-message-diagram.png) Figure 1. Mule Event and Message. ## Inbound Properties Are Now Attributes In Mule 3, inbound properties stored additional information about a payload obtained through a Mule event source, such as the query parameters coming through an HTTP listener. **Attributes** in Mule 4 replace inbound properties and have these advantages: - They are strongly typed, so you can easily see what data is available. - They can easily be stored in variables that you can access throughout your flow. Here’s an HTTP listener example of a typical Mule Message in Mule 4: ![Mule Message structure in Mule 4](/mulesoft/current/en-us/mule-runtime/4.4/_images/mule-message.png) Attributes can be easily accessed through expressions, just as inbound properties were in Mule 3, for example: ```text #[attributes.requestPath] #[attributes.queryParams.searchCriteria] ``` When any Source or Operation produces a new Message as a result of its execution, **both parts of the Message (the payload and attributes) are replaced with the new values**, and the previous attributes are lost. If you need to preserve any information from the attributes across operation invocations, you can either store the previous attributes in a variable or [set the `target` parameter in the invoked operation](https://docs.mulesoft.com/mule-runtime/4.4/target-variables). Here is an example of how the Message is updated during the execution of a flow: ```xml (1) (2) (3) #[output application/xml --- { data: payload, customer: attributes.queryParams.customer_id (4) }] (5) #[output application/json --- { customer: requestAttributes.queryParams.customer_id, (6) invoiceTrackingNumber: attributes.properties.userProperties.invoiceTrackingNumber }] (7) (8) ```
1A request is received, and the http:listener produces a Message with the request payload and the HTTP Attributes.
2Because the logger is a void operation and does not produce any output, the Message remains the same after its execution.
3The example stores the current HTTP Attributes in a variable to make use of them later in the flow because the next operation will replace the current Message.
4HTTP Attributes are still available to configure the jms:publish-consume operation input.
5Once the jms:publish-consume is invoked, the output of the operation is a Message with a different payload and the JMS Attributes.
6Since the HTTP Attributes are stored in a variable, it is possible to use both the current JMS Attributes (as attributes) and the previously stored HTTP information.
7The jms:publish operation is also void. Because no output is produced, the Message remains unmodified.
8At this point, JMS Attributes from the jms:publish-consume invocation still exist.
## Outbound Properties In Mule 3, Mule connectors and transports that need to send additional data, such as headers, must explicitly specify Outbound properties. For example, with the HTTP listener, you might want to specify the outgoing status code response or headers. In Mule 4, you can set each of those separately using an individual DataWeave expression for each one of them, without introducing any side effects in the main flow: ```xml #[{'path':'input/issues-list.json'}] #[{'provider':'memory-provider'}] ``` The previous example performs an HTTP request in which individual DataWeave scripts generate headers and query parameters without the need to set message properties and without generating any side effects on the message. The same concept can be applied for Mule event sources that emit responses, such an HTTP listener: ```xml #[vars.outboundHeaders default {}] #[payload] #[vars.outboundHeaders default {}] ``` In the previous example, `http:headers` settings like `vars.httpStatus default 200` set a default value for a variable if the actual value resolves to `null`. ## Session Properties Session properties are no longer needed and have been removed in Mule 4. Instead, store data in target variables using the Target (`target`) parameter. These properties are not needed because Mule 3 transports and their associated transport barriers do not exist in Mule 4. Mule 3 transport barriers determine how to handle Mule message data that moves through Mule 3 flows. Transports are replaced by corresponding Mule connectors (such as the FTP connector) in Mule 4, which handle networking transport protocols differently. For examples, see [Migrating the Enricher to a Target Variable](https://docs.mulesoft.com/mule-runtime/4.4/migration-core-enricher) and [Enrich Data with Target Variables](https://docs.mulesoft.com/mule-runtime/4.4/target-variables). ## Attachments Inbound and outbound attachments have been removed. The affected connectors now handle the attachment concept on their own: - HTTP now relies on DataWeave’s multipart format support. - Email and Web Service Consumer allow attachments to be explicitly added using DataWeave. ## Message Collections One of the benefits of the new Mule Message structure is when dealing with collections. In Mule 3, components that returned multiple payloads, used a special structure called the `MuleMessageCollection`. In Mule 4, any component that needs to deal with multiple messages can simply set the payload of the message to a List of Mule Messages. You can then iterate over these messages using DataWeave, For Each, or other components. For example, the `` operation retrieves a List of Messages. Each message has attributes for each file, which makes it easy to make decisions based on file size, whether it’s a directory, and so on. ## See Also - [Migrating HTTP Connector Uses](https://docs.mulesoft.com/mule-runtime/4.4/migration-connectors-http) - [Supported Data Formats](https://docs.mulesoft.com/dataweave/latest/dataweave-formats) - [DataWeave Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables) - [Migrating the Enricher to a Target Variable](https://docs.mulesoft.com/mule-runtime/4.4/migration-core-enricher) --- product: Mule Runtime version: 4.3 --- # Introduction to Mule 4: Packaging Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## Application Structure There are few important changes to how Mule applications are packaged in Mule 4. Mule applications are now packaged as a JAR and have a different structure. You can use the Mule Maven Plugin to easily package your source code into this structure.
LocationDescription

META-INF/mule-artifact/mule-artifact.json

Descriptor for your Mule application (see Application Descriptor).

META-INF/mule-src/yourapp/

An optional location for your source code.

repository

A repository for all your application’s dependencies in Maven layout. This includes all your connectors for your app. For example, repository/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar

yourapp.xml

Your Mule XML code.

## Application Descriptor Mule 4 applications include a `mule-artifact.json` file in `META-INF/mule-artifact/`. This describes your app, configuration settings, the required Mule version, and the class loader configuration. ```json { "configs": ["ch-usage-sync.xml"], "redeploymentEnabled": true, "name": "ch-usage-sync", "minMuleVersion": "4.0.0", "requiredProduct": "MULE_EE", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [] } }, "bundleDescriptorLoader": { "id": "mule", "attributes": {} } } ``` ### Application Descriptor Reference
AttributeValue typeDescription

configs

Array of Strings

Set of Mule configuration files.

redeploymentEnabled

Boolean

Whether modifying the app configuration files will trigger a redeployment.

name

String

Meaningful name for the app.

minMuleVersion

String

Minimum Mule Runtime version required to deploy the app.

requiredProduct

String

Required product type to deploy the app. MULE means that the app can be deployed on the Community Edition (CE) version or the Enterprise Edition (EE) version. MULE_EE means that the app can only be deployed on the EE version.

classLoaderModelLoaderDescriptor

Object

Descriptor of the classloading model for the app. The id field identifies the mechanism to be used by the runtime to understand how the dependencies and the packages/resources of the app are meant to be used. By default, Mule uses the ID mule, which means that the exported packages and resources from the apps are described in the attributes field, and the dependencies are described in the file /META-INF/mule-artifact/classloader-model.json.

bundleDescriptorLoader

Object

Descriptor of the app bundle coordinates. The id field identifies the mechanism to be used by the runtime to understand the app bundle coordinates. The default is mule and will load the Artifact Group ID, Artifact ID, and Version from the POM file.

secureProperties

Array of Strings

Declares the set of configuration properties of the artifact that must be managed as secure in the platform.

## Application Versioning Mule Runtime follows [semantic versioning](https://semver.org/) in all its artifacts. By following semantic versioning, clients of our APIs can clearly understand what to expect whenever MuleSoft releases a new version of an asset. For instance, consider the case of Mule connectors. You can expect bug fixes (and only bug fixes) when a patch version is updated. You can expect new features in new minor versions. Both of those changes are expected to be backward compatible so that you can upgrade without any problem. But if MuleSoft updates the major version of the connector, it means that it was necessary to break backward compatibility to include new functionality or provide a much better UX. It is also expected that Mule artifacts (app, domains, policies) follow semantic versioning, so you might encounter some validations when working with Mule apps. By following semantic versioning, Anypoint Platform can better understand new assets and provide a better experience. For instance, if there’s a new major version of a Mule domain, you can expect that there is not going to be, for instance, the same set of global components defined in it as in the previous major version. So mule apps that belong to that domain might required to be updated if the new domain is used. ## Mule Maven Plugin The Mule Maven Plugin in Mule 4 packages your app into the required format and enables you to deploy it into your target environment. Studio 7 will automatically add the plugin to your `pom.xml`. See the Mule Maven Plugin documentation for information on how to use it to deploy apps. > [!IMPORTANT] Domains, policies, Mule artifact plugins (connectors, modules, and so on) all have > the same structure as Mule apps. Depending on the type of artifact, there might be more or less > properties in the artifact descriptors (`mule-artifact.json`), but they are all similar and all > must follow semantic versioning. ## See Also - [Package Mule Apps using the Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.3/mmp-concept#mule-application-packaging) - [Deploy Mule Apps using the Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.3/mmp-concept#mule-application-deployment) --- product: Mule Runtime version: 4.4 --- # Introduction to Mule 4: Packaging Applications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## Application Structure There are few important changes to how Mule applications are packaged in Mule 4. Mule applications are now packaged as a JAR and have a different structure. You can use the Mule Maven Plugin to easily package your source code into this structure.
LocationDescription

META-INF/mule-artifact/mule-artifact.json

Descriptor for your Mule application (see Application Descriptor).

META-INF/mule-src/yourapp/

An optional location for your source code.

repository

A repository for all your application’s dependencies in Maven layout. This includes all your connectors for your app. For example, repository/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar

yourapp.xml

Your Mule XML code.

## Application Descriptor Mule 4 applications include a `mule-artifact.json` file in `META-INF/mule-artifact/`. This describes your app, configuration settings, the required Mule version, and the class loader configuration. ```json { "configs": ["ch-usage-sync.xml"], "redeploymentEnabled": true, "name": "ch-usage-sync", "minMuleVersion": "4.0.0", "requiredProduct": "MULE_EE", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [] } }, "bundleDescriptorLoader": { "id": "mule", "attributes": {} } } ``` ### Application Descriptor Reference
AttributeValue typeDescription

configs

Array of Strings

Set of Mule configuration files.

redeploymentEnabled

Boolean

Whether modifying the app configuration files will trigger a redeployment.

name

String

Meaningful name for the app.

minMuleVersion

String

Minimum Mule Runtime version required to deploy the app.

requiredProduct

String

Required product type to deploy the app. MULE means that the app can be deployed on the Community Edition (CE) version or the Enterprise Edition (EE) version. MULE_EE means that the app can only be deployed on the EE version.

classLoaderModelLoaderDescriptor

Object

Descriptor of the classloading model for the app. The id field identifies the mechanism to be used by the runtime to understand how the dependencies and the packages/resources of the app are meant to be used. By default, Mule uses the ID mule, which means that the exported packages and resources from the apps are described in the attributes field, and the dependencies are described in the file /META-INF/mule-artifact/classloader-model.json.

bundleDescriptorLoader

Object

Descriptor of the app bundle coordinates. The id field identifies the mechanism to be used by the runtime to understand the app bundle coordinates. The default is mule and will load the Artifact Group ID, Artifact ID, and Version from the POM file.

secureProperties

Array of Strings

Declares the set of configuration properties of the artifact that must be managed as secure in the platform.

## Application Versioning Mule Runtime follows [semantic versioning](https://semver.org/) in all its artifacts. By following semantic versioning, clients of our APIs can clearly understand what to expect whenever MuleSoft releases a new version of an asset. For instance, consider the case of Mule connectors. You can expect bug fixes (and only bug fixes) when a patch version is updated. You can expect new features in new minor versions. Both of those changes are expected to be backward compatible so that you can upgrade without any problem. But if MuleSoft updates the major version of the connector, it means that it was necessary to break backward compatibility to include new functionality or provide a much better UX. It is also expected that Mule artifacts (app, domains, policies) follow semantic versioning, so you might encounter some validations when working with Mule apps. By following semantic versioning, Anypoint Platform can better understand new assets and provide a better experience. For instance, if there’s a new major version of a Mule domain, you can expect that there is not going to be, for instance, the same set of global components defined in it as in the previous major version. So mule apps that belong to that domain might required to be updated if the new domain is used. ## Mule Maven Plugin The Mule Maven Plugin in Mule 4 packages your app into the required format and enables you to deploy it into your target environment. Studio 7 will automatically add the plugin to your `pom.xml`. See the Mule Maven Plugin documentation for information on how to use it to deploy apps. > [!IMPORTANT] Domains, policies, Mule artifact plugins (connectors, modules, and so on) all have > the same structure as Mule apps. Depending on the type of artifact, there might be more or less > properties in the artifact descriptors (`mule-artifact.json`), but they are all similar and all > must follow semantic versioning. ## See Also - [Package Mule Apps using the Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.4/mmp-concept#mule-application-packaging) - [Deploy Mule Apps using the Mule Maven Plugin](https://docs.mulesoft.com/mule-runtime/4.4/mmp-concept#mule-application-deployment) --- product: Mule Runtime version: 4.3 --- # Introduction to Mule 4: Studio 7 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Before learning about what’s new in Mule 4, you should install and familiarize yourself with Studio 7. It is the development environment for Mule 4 applications. Beyond support for Mule 4, it includes many new productivity improvements. Note that Studio 7 does not support opening Mule 3 applications. ## New Mule Palette When using the Studio 6 palette, finding the right operation was a multi-step process: you had to find the connector, drag it onto the canvas, then search for an operation. To speed this process, Studio 7 provides a two-level palette that improves access time, discoverability, and categorization. You can search directly for a connector operation and easily add commonly used operations to your Favorites. Managing your connectors and modules has also improved. In Studio 7, you can explicitly add versions of connectors to your project, which makes the palette specific to your project. As a result, you no longer have to see connectors or modules you are not using. ![Studio Palette](/mulesoft/current/en-us/mule-runtime/4.3/_images/studio-palette.png) ## Managing Dependencies, Automatic Maven Integration In previous versions of Studio, every Mule module was an Eclipse plugin that required installation through an "update site" mechanism. Now, every module is simply a project dependency, managed by Maven. This means that you no longer have to deal with huge “update sites,” plugin installations, or plugin versions. Studio will automatically add Maven dependencies to the ‘pom.xml’ file and keep track of them for you. If you don’t know Maven, don’t worry, Studio will manage Maven for you automatically by creating a default `pom.xml` file for every project. ## Navigating to XML View You can now navigate quickly to the XML from the visual view: - Simply right-click on any component, and select Go to XML. ## Anypoint Platform Account Management In every operation related to the Platform, you’ll see a quick-change toolbar that allows you to change accounts and if applicable, the business group. You can also add accounts from the toolbar. For example, when creating a new Mule project (File > New > Mule Project), if you select an API implementation from Design Center, the toolbar displays at the top of the selection dialog: ![Studio credentials when creating a new Mule Project](/mulesoft/current/en-us/mule-runtime/4.3/_images/studio-credentials.png) Similarly, if you select Search in Exchange from the Mule Palette, the toolbar displays in a slightly different form: ![Studio Credentials in Mule Palette](/mulesoft/current/en-us/mule-runtime/4.3/_images/studio-credentials-exchange.png) ## Metadata Storage Mule 4 applications contain an `application-types.xml` file, which is where metadata around your data types is stored. For example, if you create a new CSV type, that metadata will be added to this file. This new file is easy to share, commit, and merge when conflicts arise, which enables you to do more metadata-driven development. ## Other Improvements - A new set of graphic icons for better usability. - A watermark text that will always display the operation name (such as, Select or Delete) when you change the default Display Name of the operation. This change provides you with better visibility. - Collapsible flows with interactive preview. --- product: Mule Runtime version: 4.4 --- # Introduction to Mule 4: Studio 7 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Before learning about what’s new in Mule 4, you should install and familiarize yourself with Studio 7. It is the development environment for Mule 4 applications. Beyond support for Mule 4, it includes many new productivity improvements. Note that Studio 7 does not support opening Mule 3 applications. ## New Mule Palette When using the Studio 6 palette, finding the right operation was a multi-step process: you had to find the connector, drag it onto the canvas, then search for an operation. To speed this process, Studio 7 provides a two-level palette that improves access time, discoverability, and categorization. You can search directly for a connector operation and easily add commonly used operations to your Favorites. Managing your connectors and modules has also improved. In Studio 7, you can explicitly add versions of connectors to your project, which makes the palette specific to your project. As a result, you no longer have to see connectors or modules you are not using. ![Studio Palette](/mulesoft/current/en-us/mule-runtime/4.4/_images/studio-palette.png) ## Managing Dependencies, Automatic Maven Integration In previous versions of Studio, every Mule module was an Eclipse plugin that required installation through an "update site" mechanism. Now, every module is simply a project dependency, managed by Maven. This means that you no longer have to deal with huge “update sites,” plugin installations, or plugin versions. Studio will automatically add Maven dependencies to the ‘pom.xml’ file and keep track of them for you. If you don’t know Maven, don’t worry, Studio will manage Maven for you automatically by creating a default `pom.xml` file for every project. ## Navigating to XML View You can now navigate quickly to the XML from the visual view: - Simply right-click on any component, and select Go to XML. ## Anypoint Platform Account Management In every operation related to the Platform, you’ll see a quick-change toolbar that allows you to change accounts and if applicable, the business group. You can also add accounts from the toolbar. For example, when creating a new Mule project (File > New > Mule Project), if you select an API implementation from Design Center, the toolbar displays at the top of the selection dialog: ![Studio credentials when creating a new Mule Project](/mulesoft/current/en-us/mule-runtime/4.4/_images/studio-credentials.png) Similarly, if you select Search in Exchange from the Mule Palette, the toolbar displays in a slightly different form: ![Studio Credentials in Mule Palette](/mulesoft/current/en-us/mule-runtime/4.4/_images/studio-credentials-exchange.png) ## Metadata Storage Mule 4 applications contain an `application-types.xml` file, which is where metadata around your data types is stored. For example, if you create a new CSV type, that metadata will be added to this file. This new file is easy to share, commit, and merge when conflicts arise, which enables you to do more metadata-driven development. ## Other Improvements - A new set of graphic icons for better usability. - A watermark text that will always display the operation name (such as, Select or Delete) when you change the default Display Name of the operation. This change provides you with better visibility. - Collapsible flows with interactive preview. --- product: Mule Runtime version: 4.3 --- # Introduction to Mule 4: Transformations and Streaming > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The way to think about data in Mule 4 is fundamentally different in Mule 3. In Mule 3, you often need to know about the underlying Java types, how to manage InputStreams, whether a payload is larger-than-memory, and how to convert data into Java objects so they can be accessed by MEL. For Mule 4, these best practices are recommended: - Avoid unnecessary conversions to Java data types, and work with data directly. - Let the runtime handle streaming for you. - Do not convert binary data types to `String`, `byte[]`, or `InputStream` unless you are performing a direct integration with custom Java code. ## Transparent Streaming [Introduction to Mule 4: DataWeave Expression Language](https://docs.mulesoft.com/mule-runtime/4.3/intro-expressions) showed how to work with data directly using DataWeave. This ability to access different data formats, combined with Mule 4 streaming capabilities, means that you no longer need to convert your data to Java objects first. This improvement greatly simplifies working with data in the runtime because: - Data can be read multiple times or accessed randomly using the DataWeave expression language, without side effects. - Data can be sent to multiple places without the need to cache that data in memory first. - You can transparently access larger-than-memory data. For more information on how streaming works in Mule 4, please see [About Streaming in Mule 4.0](https://docs.mulesoft.com/mule-runtime/4.3/streaming-about). ## Data Types and Object to String/Byte/InputStream Transformers Because Mule now manages the data streams for you, data access becomes simpler. You do not need to be concerned with the underlying Java representation of that type whether it is a `byte[]`, `InputStream`, `String`, or some other format. A common pattern observed in Mule 3 applications is that users would convert things to strings in order to log them or send them through some transport. This was necessary because streams cannot be consumed twice, so a Transformer was needed: ```xml ``` In Mule 4, you can simply log or send the data without worrying about the underlying type or how many times the stream is consumed. Instead of thinking about the `InputStream`, you should just think about the payload as binary data. Or, if you know the content type, you can think about it directly as JSON, XML, or whatever data type corresponds to the content type. ```xml ``` ## See Also - [Streaming in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.3/streaming-about) --- product: Mule Runtime version: 4.4 --- # Introduction to Mule 4: Transformations and Streaming > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The way to think about data in Mule 4 is fundamentally different in Mule 3. In Mule 3, you often need to know about the underlying Java types, how to manage InputStreams, whether a payload is larger-than-memory, and how to convert data into Java objects so they can be accessed by MEL. For Mule 4, these best practices are recommended: - Avoid unnecessary conversions to Java data types, and work with data directly. - Let the runtime handle streaming for you. - Do not convert binary data types to `String`, `byte[]`, or `InputStream` unless you are performing a direct integration with custom Java code. ## Transparent Streaming [Introduction to Mule 4: DataWeave Expression Language](https://docs.mulesoft.com/mule-runtime/4.4/intro-expressions) showed how to work with data directly using DataWeave. This ability to access different data formats, combined with Mule 4 streaming capabilities, means that you no longer need to convert your data to Java objects first. This improvement greatly simplifies working with data in the runtime because: - Data can be read multiple times or accessed randomly using the DataWeave expression language, without side effects. - Data can be sent to multiple places without the need to cache that data in memory first. - You can transparently access larger-than-memory data. For more information on how streaming works in Mule 4, please see [About Streaming in Mule 4.0](https://docs.mulesoft.com/mule-runtime/4.4/streaming-about). ## Data Types and Object to String/Byte/InputStream Transformers Because Mule now manages the data streams for you, data access becomes simpler. You do not need to be concerned with the underlying Java representation of that type whether it is a `byte[]`, `InputStream`, `String`, or some other format. A common pattern observed in Mule 3 applications is that users would convert things to strings in order to log them or send them through some transport. This was necessary because streams cannot be consumed twice, so a Transformer was needed: ```xml ``` In Mule 4, you can simply log or send the data without worrying about the underlying type or how many times the stream is consumed. Instead of thinking about the `InputStream`, you should just think about the payload as binary data. Or, if you know the content type, you can think about it directly as JSON, XML, or whatever data type corresponds to the content type. ```xml ``` ## See Also - [Streaming in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.4/streaming-about) --- product: Mule Runtime version: 4.11 --- # Invalidate Cache Entries > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Invalidate cache entries when you want the Cache Scope to recalculate the value for those cache entries. You can invalidate a cache key or a complete cache by using the Invalidate Key and Invalidate Cache components, respectively. Alternatively, you can configure the caching strategy to invalidate entries automatically based on time. ## Invalidate a Cache Key Configure the Invalidate Key component in your application flow to invalidate a cache key in the referenced caching strategy. > [!WARNING] Do not specify an Invalidate Key or Invalidate Cache component inside a Cache scope if > they reference the same caching strategy unless the caching strategy disables synchronized access. > Otherwise, the application will stop responding when it tries to invalidate the locked cache. ### Configure the Invalidate Key Component Follow these steps to configure the Invalidate Key component: 1. In **Anypoint Studio**, drag the **Invalidate Key** component to your flow. 2. Click the **Invalidate Key** component in your flow to open its properties. 3. Specify the **Caching Strategy** where the cache key to invalidate is stored. 4. Optionally, select the method for calculating the cache key. ### Example Invalidate Cache Key Configuration ```xml ``` ## Invalidate a Complete Cache Configure the Invalidate Cache component in your application flow to invalidate the complete cache in the referenced caching strategy. ### Configure the Invalidate Cache Component Follow these steps to configure the Invalidate Cache component: 1. In **Anypoint Studio**, drag the **Invalidate Cache** component to your flow. 2. Click the **Invalidate Cache** component in your flow to open its properties. 3. Specify the **Caching Strategy** to invalidate. ### Example Invalidate a Complete Cache Configuration ```xml ``` ## Automatic Invalidation When you configure the caching strategy, you can configure a custom object store and set the time to live (`entryTtl`) value to make stored cache keys expire over time. ### Configure the Object Store in Your Caching Strategy The following steps show how to configure the object store in your caching strategy to invalidate cache keys automatically after a set time: 1. Follow the steps in [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.11/cache-scope-strategy). 2. When configuring the object store for the strategy, set a value for **Entry ttl**. This value represents the time after which the cache entry expires. 3. Complete the object store configuration. ### Example Automatic Invalidation Configuration ```xml ``` ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/4.11/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.11/cache-scope-strategy) - [Object Store Configuration](https://docs.mulesoft.com/mule-runtime/4.11/mule-object-stores#object-store-config) - [Object Store Reference](https://docs.mulesoft.com/object-store-connector/latest/object-store-connector-reference#objectStore) --- product: Mule Runtime version: 4.12 --- # Invalidate Cache Entries > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Invalidate cache entries when you want the Cache Scope to recalculate the value for those cache entries. You can invalidate a cache key or a complete cache by using the Invalidate Key and Invalidate Cache components, respectively. Alternatively, you can configure the caching strategy to invalidate entries automatically based on time. ## Invalidate a Cache Key Configure the Invalidate Key component in your application flow to invalidate a cache key in the referenced caching strategy. > [!WARNING] Do not specify an Invalidate Key or Invalidate Cache component inside a Cache scope if > they reference the same caching strategy unless the caching strategy disables synchronized access. > Otherwise, the application will stop responding when it tries to invalidate the locked cache. ### Configure the Invalidate Key Component Follow these steps to configure the Invalidate Key component: 1. In **Anypoint Studio**, drag the **Invalidate Key** component to your flow. 2. Click the **Invalidate Key** component in your flow to open its properties. 3. Specify the **Caching Strategy** where the cache key to invalidate is stored. 4. Optionally, select the method for calculating the cache key. ### Example Invalidate Cache Key Configuration ```xml ``` ## Invalidate a Complete Cache Configure the Invalidate Cache component in your application flow to invalidate the complete cache in the referenced caching strategy. ### Configure the Invalidate Cache Component Follow these steps to configure the Invalidate Cache component: 1. In **Anypoint Studio**, drag the **Invalidate Cache** component to your flow. 2. Click the **Invalidate Cache** component in your flow to open its properties. 3. Specify the **Caching Strategy** to invalidate. ### Example Invalidate a Complete Cache Configuration ```xml ``` ## Automatic Invalidation When you configure the caching strategy, you can configure a custom object store and set the time to live (`entryTtl`) value to make stored cache keys expire over time. ### Configure the Object Store in Your Caching Strategy The following steps show how to configure the object store in your caching strategy to invalidate cache keys automatically after a set time: 1. Follow the steps in [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.12/cache-scope-strategy). 2. When configuring the object store for the strategy, set a value for **Entry ttl**. This value represents the time after which the cache entry expires. 3. Complete the object store configuration. ### Example Automatic Invalidation Configuration ```xml ``` ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/4.12/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.12/cache-scope-strategy) - [Object Store Configuration](https://docs.mulesoft.com/mule-runtime/4.12/mule-object-stores#object-store-config) - [Object Store Reference](https://docs.mulesoft.com/object-store-connector/latest/object-store-connector-reference#objectStore) --- product: Mule Runtime version: 4.3 --- # Invalidate Cache Entries > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Invalidate cache entries when you want the Cache Scope to recalculate the value for those cache entries. You can invalidate a cache key or a complete cache by using the Invalidate Key and Invalidate Cache components, respectively. Alternatively, you can configure the caching strategy to invalidate entries automatically based on time. ## Invalidate a Cache Key Configure the Invalidate Key component in your application flow to invalidate a cache key in the referenced caching strategy. > [!WARNING] Do not specify an Invalidate Key or Invalidate Cache component inside a Cache scope if > they reference the same caching strategy unless the caching strategy disables synchronized access. > Otherwise, the application will stop responding when it tries to invalidate the locked cache. ### Configure the Invalidate Key Component Follow these steps to configure the Invalidate Key component: 1. In **Anypoint Studio**, drag the **Invalidate Key** component to your flow. 2. Click the **Invalidate Key** component in your flow to open its properties. 3. Specify the **Caching Strategy** where the cache key to invalidate is stored. 4. Optionally, select the method for calculating the cache key. ### Example Invalidate Cache Key Configuration ```xml ``` ## Invalidate a Complete Cache Configure the Invalidate Cache component in your application flow to invalidate the complete cache in the referenced caching strategy. ### Configure the Invalidate Cache Component Follow these steps to configure the Invalidate Cache component: 1. In **Anypoint Studio**, drag the **Invalidate Cache** component to your flow. 2. Click the **Invalidate Cache** component in your flow to open its properties. 3. Specify the **Caching Strategy** to invalidate. ### Example Invalidate a Complete Cache Configuration ```xml ``` ## Automatic Invalidation When you configure the caching strategy, you can configure a custom object store and set the time to live (`entryTtl`) value to make stored cache keys expire over time. ### Configure the Object Store in Your Caching Strategy The following steps show how to configure the object store in your caching strategy to invalidate cache keys automatically after a set time: 1. Follow the steps in [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.3/cache-scope-strategy). 2. When configuring the object store for the strategy, set a value for **Entry ttl**. This value represents the time after which the cache entry expires. 3. Complete the object store configuration. ### Example Automatic Invalidation Configuration ```xml ``` ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/4.3/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.3/cache-scope-strategy) - [Object Store Configuration](https://docs.mulesoft.com/mule-runtime/4.3/mule-object-stores#object-store-config) - [Object Store Reference](https://docs.mulesoft.com/object-store-connector/latest/object-store-connector-reference#objectStore) --- product: Mule Runtime version: 4.4 --- # Invalidate Cache Entries > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Invalidate cache entries when you want the Cache Scope to recalculate the value for those cache entries. You can invalidate a cache key or a complete cache by using the Invalidate Key and Invalidate Cache components, respectively. Alternatively, you can configure the caching strategy to invalidate entries automatically based on time. ## Invalidate a Cache Key Configure the Invalidate Key component in your application flow to invalidate a cache key in the referenced caching strategy. > [!WARNING] Do not specify an Invalidate Key or Invalidate Cache component inside a Cache scope if > they reference the same caching strategy unless the caching strategy disables synchronized access. > Otherwise, the application will stop responding when it tries to invalidate the locked cache. ### Configure the Invalidate Key Component Follow these steps to configure the Invalidate Key component: 1. In **Anypoint Studio**, drag the **Invalidate Key** component to your flow. 2. Click the **Invalidate Key** component in your flow to open its properties. 3. Specify the **Caching Strategy** where the cache key to invalidate is stored. 4. Optionally, select the method for calculating the cache key. ### Example Invalidate Cache Key Configuration ```xml ``` ## Invalidate a Complete Cache Configure the Invalidate Cache component in your application flow to invalidate the complete cache in the referenced caching strategy. ### Configure the Invalidate Cache Component Follow these steps to configure the Invalidate Cache component: 1. In **Anypoint Studio**, drag the **Invalidate Cache** component to your flow. 2. Click the **Invalidate Cache** component in your flow to open its properties. 3. Specify the **Caching Strategy** to invalidate. ### Example Invalidate a Complete Cache Configuration ```xml ``` ## Automatic Invalidation When you configure the caching strategy, you can configure a custom object store and set the time to live (`entryTtl`) value to make stored cache keys expire over time. ### Configure the Object Store in Your Caching Strategy The following steps show how to configure the object store in your caching strategy to invalidate cache keys automatically after a set time: 1. Follow the steps in [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.4/cache-scope-strategy). 2. When configuring the object store for the strategy, set a value for **Entry ttl**. This value represents the time after which the cache entry expires. 3. Complete the object store configuration. ### Example Automatic Invalidation Configuration ```xml ``` ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/4.4/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.4/cache-scope-strategy) - [Object Store Configuration](https://docs.mulesoft.com/mule-runtime/4.4/mule-object-stores#object-store-config) - [Object Store Reference](https://docs.mulesoft.com/object-store-connector/latest/object-store-connector-reference#objectStore) --- product: Mule Runtime version: 4.6 --- # Invalidate Cache Entries > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Invalidate cache entries when you want the Cache Scope to recalculate the value for those cache entries. You can invalidate a cache key or a complete cache by using the Invalidate Key and Invalidate Cache components, respectively. Alternatively, you can configure the caching strategy to invalidate entries automatically based on time. ## Invalidate a Cache Key Configure the Invalidate Key component in your application flow to invalidate a cache key in the referenced caching strategy. > [!WARNING] Do not specify an Invalidate Key or Invalidate Cache component inside a Cache scope if > they reference the same caching strategy unless the caching strategy disables synchronized access. > Otherwise, the application will stop responding when it tries to invalidate the locked cache. ### Configure the Invalidate Key Component Follow these steps to configure the Invalidate Key component: 1. In **Anypoint Studio**, drag the **Invalidate Key** component to your flow. 2. Click the **Invalidate Key** component in your flow to open its properties. 3. Specify the **Caching Strategy** where the cache key to invalidate is stored. 4. Optionally, select the method for calculating the cache key. ### Example Invalidate Cache Key Configuration ```xml ``` ## Invalidate a Complete Cache Configure the Invalidate Cache component in your application flow to invalidate the complete cache in the referenced caching strategy. ### Configure the Invalidate Cache Component Follow these steps to configure the Invalidate Cache component: 1. In **Anypoint Studio**, drag the **Invalidate Cache** component to your flow. 2. Click the **Invalidate Cache** component in your flow to open its properties. 3. Specify the **Caching Strategy** to invalidate. ### Example Invalidate a Complete Cache Configuration ```xml ``` ## Automatic Invalidation When you configure the caching strategy, you can configure a custom object store and set the time to live (`entryTtl`) value to make stored cache keys expire over time. ### Configure the Object Store in Your Caching Strategy The following steps show how to configure the object store in your caching strategy to invalidate cache keys automatically after a set time: 1. Follow the steps in [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.6/cache-scope-strategy). 2. When configuring the object store for the strategy, set a value for **Entry ttl**. This value represents the time after which the cache entry expires. 3. Complete the object store configuration. ### Example Automatic Invalidation Configuration ```xml ``` ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/4.6/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.6/cache-scope-strategy) - [Object Store Configuration](https://docs.mulesoft.com/mule-runtime/4.6/mule-object-stores#object-store-config) - [Object Store Reference](https://docs.mulesoft.com/object-store-connector/latest/object-store-connector-reference#objectStore) --- product: Mule Runtime version: 4.9 --- # Invalidate Cache Entries > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Invalidate cache entries when you want the Cache Scope to recalculate the value for those cache entries. You can invalidate a cache key or a complete cache by using the Invalidate Key and Invalidate Cache components, respectively. Alternatively, you can configure the caching strategy to invalidate entries automatically based on time. ## Invalidate a Cache Key Configure the Invalidate Key component in your application flow to invalidate a cache key in the referenced caching strategy. > [!WARNING] Do not specify an Invalidate Key or Invalidate Cache component inside a Cache scope if > they reference the same caching strategy unless the caching strategy disables synchronized access. > Otherwise, the application will stop responding when it tries to invalidate the locked cache. ### Configure the Invalidate Key Component Follow these steps to configure the Invalidate Key component: 1. In **Anypoint Studio**, drag the **Invalidate Key** component to your flow. 2. Click the **Invalidate Key** component in your flow to open its properties. 3. Specify the **Caching Strategy** where the cache key to invalidate is stored. 4. Optionally, select the method for calculating the cache key. ### Example Invalidate Cache Key Configuration ```xml ``` ## Invalidate a Complete Cache Configure the Invalidate Cache component in your application flow to invalidate the complete cache in the referenced caching strategy. ### Configure the Invalidate Cache Component Follow these steps to configure the Invalidate Cache component: 1. In **Anypoint Studio**, drag the **Invalidate Cache** component to your flow. 2. Click the **Invalidate Cache** component in your flow to open its properties. 3. Specify the **Caching Strategy** to invalidate. ### Example Invalidate a Complete Cache Configuration ```xml ``` ## Automatic Invalidation When you configure the caching strategy, you can configure a custom object store and set the time to live (`entryTtl`) value to make stored cache keys expire over time. ### Configure the Object Store in Your Caching Strategy The following steps show how to configure the object store in your caching strategy to invalidate cache keys automatically after a set time: 1. Follow the steps in [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.9/cache-scope-strategy). 2. When configuring the object store for the strategy, set a value for **Entry ttl**. This value represents the time after which the cache entry expires. 3. Complete the object store configuration. ### Example Automatic Invalidation Configuration ```xml ``` ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/4.9/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/4.9/cache-scope-strategy) - [Object Store Configuration](https://docs.mulesoft.com/mule-runtime/4.9/mule-object-stores#object-store-config) - [Object Store Reference](https://docs.mulesoft.com/object-store-connector/latest/object-store-connector-reference#objectStore) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Invalidate Cache Entries > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Invalidate cache entries when you want the Cache Scope to recalculate the value for those cache entries. You can invalidate a cache key or a complete cache by using the Invalidate Key and Invalidate Cache components, respectively. Alternatively, you can configure the caching strategy to invalidate entries automatically based on time. ## Invalidate a Cache Key Configure the Invalidate Key component in your application flow to invalidate a cache key in the referenced caching strategy. > [!WARNING] Do not specify an Invalidate Key or Invalidate Cache component inside a Cache scope if > they reference the same caching strategy unless the caching strategy disables synchronized access. > Otherwise, the application will stop responding when it tries to invalidate the locked cache. ### Configure the Invalidate Key Component Follow these steps to configure the Invalidate Key component: 1. In **Anypoint Studio**, drag the **Invalidate Key** component to your flow. 2. Click the **Invalidate Key** component in your flow to open its properties. 3. Specify the **Caching Strategy** where the cache key to invalidate is stored. 4. Optionally, select the method for calculating the cache key. ### Example Invalidate Cache Key Configuration ```xml ``` ## Invalidate a Complete Cache Configure the Invalidate Cache component in your application flow to invalidate the complete cache in the referenced caching strategy. ### Configure the Invalidate Cache Component Follow these steps to configure the Invalidate Cache component: 1. In **Anypoint Studio**, drag the **Invalidate Cache** component to your flow. 2. Click the **Invalidate Cache** component in your flow to open its properties. 3. Specify the **Caching Strategy** to invalidate. ### Example Invalidate a Complete Cache Configuration ```xml ``` ## Automatic Invalidation When you configure the caching strategy, you can configure a custom object store and set the time to live (`entryTtl`) value to make stored cache keys expire over time. ### Configure the Object Store in Your Caching Strategy The following steps show how to configure the object store in your caching strategy to invalidate cache keys automatically after a set time: 1. Follow the steps in [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/latest/cache-scope-strategy). 2. When configuring the object store for the strategy, set a value for **Entry ttl**. This value represents the time after which the cache entry expires. 3. Complete the object store configuration. ### Example Automatic Invalidation Configuration ```xml ``` ## See Also - [Configure the Cache Scope](https://docs.mulesoft.com/mule-runtime/latest/cache-scope-to-configure) - [Set Up a Caching Strategy](https://docs.mulesoft.com/mule-runtime/latest/cache-scope-strategy) - [Object Store Configuration](https://docs.mulesoft.com/mule-runtime/latest/mule-object-stores#object-store-config) - [Object Store Reference](https://docs.mulesoft.com/object-store-connector/latest/object-store-connector-reference#objectStore) --- product: Mule Runtime version: 4.11 keywords: mule, esb, studio, logger, logs, log, notifications, errors, debug --- # Logger Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This Core component helps you monitor and debug your Mule application by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. > [!WARNING] Keep in mind that the Logger is one of the only components that supports mixing Strings > and expressions within a value. DataWeave String interpolation or concatenation within a single > expression should be used elsewhere. The configured messages are logged to the app’s log file, which is located in `MULE_HOME/logs/.log` if no custom log file path is specified in the `log4j2.xml` file. In Studio, the logs show in the Console. The following example displays the message in Set Payload in a browser and also logs the message. ![A flow of a logger component process in a Mule application including error handling in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/logger-flow.png) Example: XML Configuration of the Flow ```xml ``` ## Logger Configuration ![A Logger general fields showing name and generic data](/mulesoft/current/en-us/mule-runtime/4.11/_images/logger.png)
FieldValueDescriptionExample

Message

String or DataWeave expression

Specifies the Mule log message. By default, messages are logged to the application’s log file.

message="Current payload is #[payload]"

Level

Available options:

  • DEBUG

  • ERROR

  • INFO(Default)

  • TRACE

  • WARN

Specifies the log level.

level="ERROR"

Category

String

Optional setting that specifies a category name that it adds to log4j2.xml file. For example, you might use a category to route your log messages based on your category, or you might set log levels based on category.

category="MyCustomCategory"

## Examples This Logger is set to monitor message processing status, mixing Strings and expressions: ```xml ``` This Logger set to record the processing time of a flow, using a single expression and DataWeave’s String concatenation: ```xml ``` ## See also [DataWeave String Type](https://docs.mulesoft.com/dataweave/latest/dataweave-types#dw_type_string) --- product: Mule Runtime version: 4.12 keywords: mule, esb, studio, logger, logs, log, notifications, errors, debug --- # Logger Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This Core component helps you monitor and debug your Mule application by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. > [!WARNING] Keep in mind that the Logger is one of the only components that supports mixing Strings > and expressions within a value. DataWeave String interpolation or concatenation within a single > expression should be used elsewhere. The configured messages are logged to the app’s log file, which is located in `MULE_HOME/logs/.log` if no custom log file path is specified in the `log4j2.xml` file. In Studio, the logs show in the Console. The following example displays the message in Set Payload in a browser and also logs the message. ![A flow of a logger component process in a Mule application including error handling in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/logger-flow.png) Example: XML Configuration of the Flow ```xml ``` ## Logger Configuration ![A Logger general fields showing name and generic data](/mulesoft/current/en-us/mule-runtime/4.12/_images/logger.png)
FieldValueDescriptionExample

Message

String or DataWeave expression

Specifies the Mule log message. By default, messages are logged to the application’s log file.

message="Current payload is #[payload]"

Level

Available options:

  • DEBUG

  • ERROR

  • INFO(Default)

  • TRACE

  • WARN

Specifies the log level.

level="ERROR"

Category

String

Optional setting that specifies a category name that it adds to log4j2.xml file. For example, you might use a category to route your log messages based on your category, or you might set log levels based on category.

category="MyCustomCategory"

## Examples This Logger is set to monitor message processing status, mixing Strings and expressions: ```xml ``` This Logger set to record the processing time of a flow, using a single expression and DataWeave’s String concatenation: ```xml ``` ## See also [DataWeave String Type](https://docs.mulesoft.com/dataweave/latest/dataweave-types#dw_type_string) --- product: Mule Runtime version: 4.3 keywords: mule, esb, studio, logger, logs, log, notifications, errors, debug --- # Logger Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This Core component helps you monitor and debug your Mule application by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. > [!WARNING] Keep in mind that the Logger is one of the only components that supports mixing Strings > and expressions within a value. DataWeave String interpolation or concatenation within a single > expression should be used elsewhere. The configured messages are logged to the app’s log file, which is located in `MULE_HOME/logs/.log` if no custom log file path is specified in the `log4j2.xml` file. In Studio, the logs show in the Console. The following example displays the message in Set Payload in a browser and also logs the message. ![logger flow](/mulesoft/current/en-us/mule-runtime/4.3/_images/logger-flow.png) Example: XML Configuration of the Flow ```xml ``` ## Logger Configuration ![logger](/mulesoft/current/en-us/mule-runtime/4.3/_images/logger.png)
FieldValueDescriptionExample

Message

String or DataWeave expression

Specifies the Mule log message. By default, messages are logged to the application’s log file.

message="Current payload is #[payload]"

Level

Available options:

  • DEBUG

  • ERROR

  • INFO(Default)

  • TRACE

  • WARN

Specifies the log level.

level="ERROR"

Category

String

Optional setting that specifies a category name that it adds to log4j2.xml file. For example, you might use a category to route your log messages based on your category, or you might set log levels based on category.

category="MyCustomCategory"

## Examples This Logger is set to monitor message processing status, mixing Strings and expressions: ```xml ``` This Logger set to record the processing time of a flow, using a single expression and DataWeave’s String concatenation: ```xml ``` ## See also [DataWeave String Type](https://docs.mulesoft.com/dataweave/2.3/dataweave-types#dw_type_string) --- product: Mule Runtime version: 4.4 keywords: mule, esb, studio, logger, logs, log, notifications, errors, debug --- # Logger Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This Core component helps you monitor and debug your Mule application by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. > [!WARNING] Keep in mind that the Logger is one of the only components that supports mixing Strings > and expressions within a value. DataWeave String interpolation or concatenation within a single > expression should be used elsewhere. The configured messages are logged to the app’s log file, which is located in `MULE_HOME/logs/.log` if no custom log file path is specified in the `log4j2.xml` file. In Studio, the logs show in the Console. The following example displays the message in Set Payload in a browser and also logs the message. ![logger flow](/mulesoft/current/en-us/mule-runtime/4.4/_images/logger-flow.png) Example: XML Configuration of the Flow ```xml ``` ## Logger Configuration ![logger](/mulesoft/current/en-us/mule-runtime/4.4/_images/logger.png)
FieldValueDescriptionExample

Message

String or DataWeave expression

Specifies the Mule log message. By default, messages are logged to the application’s log file.

message="Current payload is #[payload]"

Level

Available options:

  • DEBUG

  • ERROR

  • INFO(Default)

  • TRACE

  • WARN

Specifies the log level.

level="ERROR"

Category

String

Optional setting that specifies a category name that it adds to log4j2.xml file. For example, you might use a category to route your log messages based on your category, or you might set log levels based on category.

category="MyCustomCategory"

## Examples This Logger is set to monitor message processing status, mixing Strings and expressions: ```xml ``` This Logger set to record the processing time of a flow, using a single expression and DataWeave’s String concatenation: ```xml ``` ## See also [DataWeave String Type](https://docs.mulesoft.com/dataweave/latest/dataweave-types#dw_type_string) --- product: Mule Runtime version: 4.6 keywords: mule, esb, studio, logger, logs, log, notifications, errors, debug --- # Logger Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This Core component helps you monitor and debug your Mule application by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. > [!WARNING] Keep in mind that the Logger is one of the only components that supports mixing Strings > and expressions within a value. DataWeave String interpolation or concatenation within a single > expression should be used elsewhere. The configured messages are logged to the app’s log file, which is located in `MULE_HOME/logs/.log` if no custom log file path is specified in the `log4j2.xml` file. In Studio, the logs show in the Console. The following example displays the message in Set Payload in a browser and also logs the message. ![logger flow](/mulesoft/current/en-us/mule-runtime/4.6/_images/logger-flow.png) Example: XML Configuration of the Flow ```xml ``` ## Logger Configuration ![logger](/mulesoft/current/en-us/mule-runtime/4.6/_images/logger.png)
FieldValueDescriptionExample

Message

String or DataWeave expression

Specifies the Mule log message. By default, messages are logged to the application’s log file.

message="Current payload is #[payload]"

Level

Available options:

  • DEBUG

  • ERROR

  • INFO(Default)

  • TRACE

  • WARN

Specifies the log level.

level="ERROR"

Category

String

Optional setting that specifies a category name that it adds to log4j2.xml file. For example, you might use a category to route your log messages based on your category, or you might set log levels based on category.

category="MyCustomCategory"

## Examples This Logger is set to monitor message processing status, mixing Strings and expressions: ```xml ``` This Logger set to record the processing time of a flow, using a single expression and DataWeave’s String concatenation: ```xml ``` ## See also [DataWeave String Type](https://docs.mulesoft.com/dataweave/latest/dataweave-types#dw_type_string) --- product: Mule Runtime version: 4.9 keywords: mule, esb, studio, logger, logs, log, notifications, errors, debug --- # Logger Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This Core component helps you monitor and debug your Mule application by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. > [!WARNING] Keep in mind that the Logger is one of the only components that supports mixing Strings > and expressions within a value. DataWeave String interpolation or concatenation within a single > expression should be used elsewhere. The configured messages are logged to the app’s log file, which is located in `MULE_HOME/logs/.log` if no custom log file path is specified in the `log4j2.xml` file. In Studio, the logs show in the Console. The following example displays the message in Set Payload in a browser and also logs the message. ![A flow of a logger component process in a Mule application including error handling in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/logger-flow.png) Example: XML Configuration of the Flow ```xml ``` ## Logger Configuration ![A Logger general fields showing name and generic data](/mulesoft/current/en-us/mule-runtime/4.9/_images/logger.png)
FieldValueDescriptionExample

Message

String or DataWeave expression

Specifies the Mule log message. By default, messages are logged to the application’s log file.

message="Current payload is #[payload]"

Level

Available options:

  • DEBUG

  • ERROR

  • INFO(Default)

  • TRACE

  • WARN

Specifies the log level.

level="ERROR"

Category

String

Optional setting that specifies a category name that it adds to log4j2.xml file. For example, you might use a category to route your log messages based on your category, or you might set log levels based on category.

category="MyCustomCategory"

## Examples This Logger is set to monitor message processing status, mixing Strings and expressions: ```xml ``` This Logger set to record the processing time of a flow, using a single expression and DataWeave’s String concatenation: ```xml ``` ## See also [DataWeave String Type](https://docs.mulesoft.com/dataweave/latest/dataweave-types#dw_type_string) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: mule, esb, studio, logger, logs, log, notifications, errors, debug --- # Logger Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This Core component helps you monitor and debug your Mule application by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. > [!WARNING] Keep in mind that the Logger is one of the only components that supports mixing Strings > and expressions within a value. DataWeave String interpolation or concatenation within a single > expression should be used elsewhere. The configured messages are logged to the app’s log file, which is located in `MULE_HOME/logs/.log` if no custom log file path is specified in the `log4j2.xml` file. In Studio, the logs show in the Console. The following example displays the message in Set Payload in a browser and also logs the message. ![A flow of a logger component process in a Mule application including error handling in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/logger-flow.png) Example: XML Configuration of the Flow ```xml ``` ## Logger Configuration ![A Logger general fields showing name and generic data](/mulesoft/current/en-us/mule-runtime/latest/_images/logger.png)
FieldValueDescriptionExample

Message

String or DataWeave expression

Specifies the Mule log message. By default, messages are logged to the application’s log file.

message="Current payload is #[payload]"

Level

Available options:

  • DEBUG

  • ERROR

  • INFO(Default)

  • TRACE

  • WARN

Specifies the log level.

level="ERROR"

Category

String

Optional setting that specifies a category name that it adds to log4j2.xml file. For example, you might use a category to route your log messages based on your category, or you might set log levels based on category.

category="MyCustomCategory"

## Examples This Logger is set to monitor message processing status, mixing Strings and expressions: ```xml ``` This Logger set to record the processing time of a flow, using a single expression and DataWeave’s String concatenation: ```xml ``` ## See also [DataWeave String Type](https://docs.mulesoft.com/dataweave/latest/dataweave-types#dw_type_string) --- product: Mule Runtime version: 4.11 --- # Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) 4 uses Log4j 2 asynchronous logging by default, so the logging operation happens in a separate thread from the message processing, and the latter can continue without having to wait for the log operation to complete. Asynchronous logging poses a performance-reliability trade-off as explained in [Asynchronous Logging Mule](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/mule-3-6-asynchronous-logging/), and you may lose some messages if Mule crashes before the logging buffers flush to the disk. In this case, consider that you can have a mixed configuration of asynchronous or synchronous loggers in your app. Best practice is to use asynchronous logging over synchronous with a minimum logging level of `WARN` for a production application. In some cases, enable `INFO` logging level when you need to confirm events such as successful policy installation or to perform troubleshooting. Configure your logging strategy by editing your application’s `src/main/resources/log4j2.xml` file, as shown in the following example: ```xml ``` - Apply caution when logging parts of messages, especially the payload, because this bypasses streaming and causes significant disk I/O for large payloads - Avoid using the `` scope to log messages Because the logging mechanism is already implemented asynchronously by the Log4j2 library in the backend, enclosing a logger into the `` scope does not improve parallelism, it increases the resource usage and duplicates the numbers of threads required. Repeatedly using this pattern in an application can cause thread exhaustion, low performance, and back-pressure. ```xml ``` ## See Also - [Logging in Mule](https://docs.mulesoft.com/mule-runtime/4.11/logging-in-mule) --- product: Mule Runtime version: 4.12 --- # Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) 4 uses Log4j 2 asynchronous logging by default, so the logging operation happens in a separate thread from the message processing, and the latter can continue without having to wait for the log operation to complete. Asynchronous logging poses a performance-reliability trade-off as explained in [Asynchronous Logging Mule](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/mule-3-6-asynchronous-logging/), and you may lose some messages if Mule crashes before the logging buffers flush to the disk. In this case, consider that you can have a mixed configuration of asynchronous or synchronous loggers in your app. Best practice is to use asynchronous logging over synchronous with a minimum logging level of `WARN` for a production application. In some cases, enable `INFO` logging level when you need to confirm events such as successful policy installation or to perform troubleshooting. Configure your logging strategy by editing your application’s `src/main/resources/log4j2.xml` file, as shown in the following example: ```xml ``` - Apply caution when logging parts of messages, especially the payload, because this bypasses streaming and causes significant disk I/O for large payloads - Avoid using the `` scope to log messages Because the logging mechanism is already implemented asynchronously by the Log4j2 library in the backend, enclosing a logger into the `` scope does not improve parallelism, it increases the resource usage and duplicates the numbers of threads required. Repeatedly using this pattern in an application can cause thread exhaustion, low performance, and back-pressure. ```xml ``` ## See Also - [Logging in Mule](https://docs.mulesoft.com/mule-runtime/4.12/logging-in-mule) --- product: Mule Runtime version: 4.3 --- # Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) 4 uses Log4j 2 asynchronous logging by default, so the logging operation happens in a separate thread from the message processing, and the latter can continue without having to wait for the log operation to complete. Asynchronous logging poses a performance-reliability trade-off as explained in [Asynchronous Logging Mule](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/mule-3-6-asynchronous-logging/), and you may lose some messages if Mule crashes before the logging buffers flush to the disk. In this case, consider that you can have a mixed configuration of asynchronous or synchronous loggers in your app. Best practice is to use asynchronous logging over synchronous with a minimum logging level of `WARN` for a production application. In some cases, enable `INFO` logging level when you need to confirm events such as successful policy installation or to perform troubleshooting. Configure your logging strategy by editing your application’s `src/main/resources/log4j2.xml` file, as shown in the following example: ```xml ``` - Apply caution when logging parts of messages, especially the payload, because this bypasses streaming and causes significant disk I/O for large payloads - Avoid using the `` scope to log messages Because the logging mechanism is already implemented asynchronously by the Log4j2 library in the backend, enclosing a logger into the `` scope does not improve parallelism, it increases the resource usage and duplicates the numbers of threads required. Repeatedly using this pattern in an application can cause thread exhaustion, low performance, and back-pressure. ```xml ``` ## See Also - [Logging in Mule](https://docs.mulesoft.com/mule-runtime/4.3/logging-in-mule) --- product: Mule Runtime version: 4.4 --- # Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) 4 uses Log4j 2 asynchronous logging by default, so the logging operation happens in a separate thread from the message processing, and the latter can continue without having to wait for the log operation to complete. Asynchronous logging poses a performance-reliability trade-off as explained in [Asynchronous Logging Mule](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/mule-3-6-asynchronous-logging/), and you may lose some messages if Mule crashes before the logging buffers flush to the disk. In this case, consider that you can have a mixed configuration of asynchronous or synchronous loggers in your app. Best practice is to use asynchronous logging over synchronous with a minimum logging level of `WARN` for a production application. In some cases, enable `INFO` logging level when you need to confirm events such as successful policy installation or to perform troubleshooting. Configure your logging strategy by editing your application’s `src/main/resources/log4j2.xml` file, as shown in the following example: ```xml ``` - Apply caution when logging parts of messages, especially the payload, because this bypasses streaming and causes significant disk I/O for large payloads - Avoid using the `` scope to log messages Because the logging mechanism is already implemented asynchronously by the Log4j2 library in the backend, enclosing a logger into the `` scope does not improve parallelism, it increases the resource usage and duplicates the numbers of threads required. Repeatedly using this pattern in an application can cause thread exhaustion, low performance, and back-pressure. ```xml ``` ## See Also - [Logging in Mule](https://docs.mulesoft.com/mule-runtime/4.4/logging-in-mule) --- product: Mule Runtime version: 4.6 --- # Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) 4 uses Log4j 2 asynchronous logging by default, so the logging operation happens in a separate thread from the message processing, and the latter can continue without having to wait for the log operation to complete. Asynchronous logging poses a performance-reliability trade-off as explained in [Asynchronous Logging Mule](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/mule-3-6-asynchronous-logging/), and you may lose some messages if Mule crashes before the logging buffers flush to the disk. In this case, consider that you can have a mixed configuration of asynchronous or synchronous loggers in your app. Best practice is to use asynchronous logging over synchronous with a minimum logging level of `WARN` for a production application. In some cases, enable `INFO` logging level when you need to confirm events such as successful policy installation or to perform troubleshooting. Configure your logging strategy by editing your application’s `src/main/resources/log4j2.xml` file, as shown in the following example: ```xml ``` - Apply caution when logging parts of messages, especially the payload, because this bypasses streaming and causes significant disk I/O for large payloads - Avoid using the `` scope to log messages Because the logging mechanism is already implemented asynchronously by the Log4j2 library in the backend, enclosing a logger into the `` scope does not improve parallelism, it increases the resource usage and duplicates the numbers of threads required. Repeatedly using this pattern in an application can cause thread exhaustion, low performance, and back-pressure. ```xml ``` ## See Also - [Logging in Mule](https://docs.mulesoft.com/mule-runtime/4.6/logging-in-mule) --- product: Mule Runtime version: 4.9 --- # Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) 4 uses Log4j 2 asynchronous logging by default, so the logging operation happens in a separate thread from the message processing, and the latter can continue without having to wait for the log operation to complete. Asynchronous logging poses a performance-reliability trade-off as explained in [Asynchronous Logging Mule](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/mule-3-6-asynchronous-logging/), and you may lose some messages if Mule crashes before the logging buffers flush to the disk. In this case, consider that you can have a mixed configuration of asynchronous or synchronous loggers in your app. Best practice is to use asynchronous logging over synchronous with a minimum logging level of `WARN` for a production application. In some cases, enable `INFO` logging level when you need to confirm events such as successful policy installation or to perform troubleshooting. Configure your logging strategy by editing your application’s `src/main/resources/log4j2.xml` file, as shown in the following example: ```xml ``` - Apply caution when logging parts of messages, especially the payload, because this bypasses streaming and causes significant disk I/O for large payloads - Avoid using the `` scope to log messages Because the logging mechanism is already implemented asynchronously by the Log4j2 library in the backend, enclosing a logger into the `` scope does not improve parallelism, it increases the resource usage and duplicates the numbers of threads required. Repeatedly using this pattern in an application can cause thread exhaustion, low performance, and back-pressure. ```xml ``` ## See Also - [Logging in Mule](https://docs.mulesoft.com/mule-runtime/4.9/logging-in-mule) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) 4 uses Log4j 2 asynchronous logging by default, so the logging operation happens in a separate thread from the message processing, and the latter can continue without having to wait for the log operation to complete. Asynchronous logging poses a performance-reliability trade-off as explained in [Asynchronous Logging Mule](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/mule-3-6-asynchronous-logging/), and you may lose some messages if Mule crashes before the logging buffers flush to the disk. In this case, consider that you can have a mixed configuration of asynchronous or synchronous loggers in your app. Best practice is to use asynchronous logging over synchronous with a minimum logging level of `WARN` for a production application. In some cases, enable `INFO` logging level when you need to confirm events such as successful policy installation or to perform troubleshooting. Configure your logging strategy by editing your application’s `src/main/resources/log4j2.xml` file, as shown in the following example: ```xml ``` - Apply caution when logging parts of messages, especially the payload, because this bypasses streaming and causes significant disk I/O for large payloads - Avoid using the `` scope to log messages Because the logging mechanism is already implemented asynchronously by the Log4j2 library in the backend, enclosing a logger into the `` scope does not improve parallelism, it increases the resource usage and duplicates the numbers of threads required. Repeatedly using this pattern in an application can cause thread exhaustion, low performance, and back-pressure. ```xml ``` ## See Also - [Logging in Mule](https://docs.mulesoft.com/mule-runtime/latest/logging-in-mule) --- product: Mule Runtime version: 4.11 --- # Logging and Debugging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides a variety of logging and debugging options for Mule apps. Application logs and a runtime log help you monitor and troubleshoot your apps and the Mule server. For details, see [Configuring Logging](https://docs.mulesoft.com/mule-runtime/4.11/logging-in-mule). You can [enable verbose logging](https://docs.mulesoft.com/mule-runtime/4.11/enable-verbose-logging) for connectors and modules to record debug level information in the logs. The Logger component can help you monitor or even debug your Mule app by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. For details, see [Logger Component](https://docs.mulesoft.com/mule-runtime/4.11/logger-component-reference) in the Core component documentation. To control the display of Mule stack traces, you can use command-line arguments or set properties in Anypoint Studio. For details, see [Configuring Mule Stack Traces](https://docs.mulesoft.com/mule-runtime/4.11/configuring-mule-stacktraces). To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept), which lets you set breakpoints to stop execution and check events. If you are creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. For details, see [Debugging Outside Studio](https://docs.mulesoft.com/mule-runtime/4.11/debugging-outside-studio). If you are running your Mule application in CloudHub, see [View Log Data](https://docs.mulesoft.com/cloudhub/viewing-log-data) for additional information about log data and persistence. --- product: Mule Runtime version: 4.12 --- # Logging and Debugging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides a variety of logging and debugging options for Mule apps. Application logs and a runtime log help you monitor and troubleshoot your apps and the Mule server. For details, see [Configuring Logging](https://docs.mulesoft.com/mule-runtime/4.12/logging-in-mule). You can [enable verbose logging](https://docs.mulesoft.com/mule-runtime/4.12/enable-verbose-logging) for connectors and modules to record debug level information in the logs. The Logger component can help you monitor or even debug your Mule app by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. For details, see [Logger Component](https://docs.mulesoft.com/mule-runtime/4.12/logger-component-reference) in the Core component documentation. To control the display of Mule stack traces, you can use command-line arguments or set properties in Anypoint Studio. For details, see [Configuring Mule Stack Traces](https://docs.mulesoft.com/mule-runtime/4.12/configuring-mule-stacktraces). To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept), which lets you set breakpoints to stop execution and check events. If you are creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. For details, see [Debugging Outside Studio](https://docs.mulesoft.com/mule-runtime/4.12/debugging-outside-studio). If you are running your Mule application in CloudHub, see [View Log Data](https://docs.mulesoft.com/cloudhub/viewing-log-data) for additional information about log data and persistence. --- product: Mule Runtime version: 4.3 --- # Logging and Debugging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides a variety of logging and debugging options for Mule apps. Application logs and a runtime log help you monitor and troubleshoot your apps and the Mule server. For details, see [Configuring Logging](https://docs.mulesoft.com/mule-runtime/4.3/logging-in-mule). You can [enable verbose logging](https://docs.mulesoft.com/mule-runtime/4.3/enable-verbose-logging) for connectors and modules to record debug level information in the logs. The Logger component can help you monitor or even debug your Mule app by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. For details, see [Logger Component](https://docs.mulesoft.com/mule-runtime/4.3/logger-component-reference) in the Core component documentation. To control the display of Mule stack traces, you can use command-line arguments or set properties in Anypoint Studio. For details, see [Configuring Mule Stack Traces](https://docs.mulesoft.com/mule-runtime/4.3/configuring-mule-stacktraces). To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept), which lets you set breakpoints to stop execution and check events. If you are creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. For details, see [Debugging Outside Studio](https://docs.mulesoft.com/mule-runtime/4.3/debugging-outside-studio). If you are running your Mule application in CloudHub, see [View Log Data](https://docs.mulesoft.com/cloudhub/viewing-log-data) for additional information about log data and persistence. --- product: Mule Runtime version: 4.4 --- # Logging and Debugging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides a variety of logging and debugging options for Mule apps. Application logs and a runtime log help you monitor and troubleshoot your apps and the Mule server. For details, see [Configuring Logging](https://docs.mulesoft.com/mule-runtime/4.4/logging-in-mule). You can [enable verbose logging](https://docs.mulesoft.com/mule-runtime/4.4/enable-verbose-logging) for connectors and modules to record debug level information in the logs. The Logger component can help you monitor or even debug your Mule app by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. For details, see [Logger Component](https://docs.mulesoft.com/mule-runtime/4.4/logger-component-reference) in the Core component documentation. To control the display of Mule stack traces, you can use command-line arguments or set properties in Anypoint Studio. For details, see [Configuring Mule Stack Traces](https://docs.mulesoft.com/mule-runtime/4.4/configuring-mule-stacktraces). To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept), which lets you set breakpoints to stop execution and check events. If you are creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. For details, see [Debugging Outside Studio](https://docs.mulesoft.com/mule-runtime/4.4/debugging-outside-studio). If you are running your Mule application in CloudHub, see [View Log Data](https://docs.mulesoft.com/cloudhub/viewing-log-data) for additional information about log data and persistence. --- product: Mule Runtime version: 4.6 --- # Logging and Debugging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides a variety of logging and debugging options for Mule apps. Application logs and a runtime log help you monitor and troubleshoot your apps and the Mule server. For details, see [Configuring Logging](https://docs.mulesoft.com/mule-runtime/4.6/logging-in-mule). You can [enable verbose logging](https://docs.mulesoft.com/mule-runtime/4.6/enable-verbose-logging) for connectors and modules to record debug level information in the logs. The Logger component can help you monitor or even debug your Mule app by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. For details, see [Logger Component](https://docs.mulesoft.com/mule-runtime/4.6/logger-component-reference) in the Core component documentation. To control the display of Mule stack traces, you can use command-line arguments or set properties in Anypoint Studio. For details, see [Configuring Mule Stack Traces](https://docs.mulesoft.com/mule-runtime/4.6/configuring-mule-stacktraces). To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept), which lets you set breakpoints to stop execution and check events. If you are creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. For details, see [Debugging Outside Studio](https://docs.mulesoft.com/mule-runtime/4.6/debugging-outside-studio). If you are running your Mule application in CloudHub, see [View Log Data](https://docs.mulesoft.com/cloudhub/viewing-log-data) for additional information about log data and persistence. --- product: Mule Runtime version: 4.9 --- # Logging and Debugging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides a variety of logging and debugging options for Mule apps. Application logs and a runtime log help you monitor and troubleshoot your apps and the Mule server. For details, see [Configuring Logging](https://docs.mulesoft.com/mule-runtime/4.9/logging-in-mule). You can [enable verbose logging](https://docs.mulesoft.com/mule-runtime/4.9/enable-verbose-logging) for connectors and modules to record debug level information in the logs. The Logger component can help you monitor or even debug your Mule app by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. For details, see [Logger Component](https://docs.mulesoft.com/mule-runtime/4.9/logger-component-reference) in the Core component documentation. To control the display of Mule stack traces, you can use command-line arguments or set properties in Anypoint Studio. For details, see [Configuring Mule Stack Traces](https://docs.mulesoft.com/mule-runtime/4.9/configuring-mule-stacktraces). To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept), which lets you set breakpoints to stop execution and check events. If you are creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. For details, see [Debugging Outside Studio](https://docs.mulesoft.com/mule-runtime/4.9/debugging-outside-studio). If you are running your Mule application in CloudHub, see [View Log Data](https://docs.mulesoft.com/cloudhub/viewing-log-data) for additional information about log data and persistence. --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Logging and Debugging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt MuleSoft provides a variety of logging and debugging options for Mule apps. Application logs and a runtime log help you monitor and troubleshoot your apps and the Mule server. For details, see [Configuring Logging](https://docs.mulesoft.com/mule-runtime/latest/logging-in-mule). You can [enable verbose logging](https://docs.mulesoft.com/mule-runtime/latest/enable-verbose-logging) for connectors and modules to record debug level information in the logs. The Logger component can help you monitor or even debug your Mule app by logging important information such as error messages, status notifications, payloads, and so on. You can add a Logger anywhere in a flow, and you can configure it to log a string that you specify, the output of a DataWeave expression you write, or any combination of strings and expressions. For details, see [Logger Component](https://docs.mulesoft.com/mule-runtime/latest/logger-component-reference) in the Core component documentation. To control the display of Mule stack traces, you can use command-line arguments or set properties in Anypoint Studio. For details, see [Configuring Mule Stack Traces](https://docs.mulesoft.com/mule-runtime/latest/configuring-mule-stacktraces). To troubleshoot a Mule app in Anypoint Studio, you can use the [Studio Visual Debugger](https://docs.mulesoft.com/studio/visual-debugger-concept), which lets you set breakpoints to stop execution and check events. If you are creating your Mule app outside of Studio, you can either use MUnit to test your app, or you can activate remote debugging. For details, see [Debugging Outside Studio](https://docs.mulesoft.com/mule-runtime/latest/debugging-outside-studio). If you are running your Mule application in CloudHub, see [View Log Data](https://docs.mulesoft.com/cloudhub/viewing-log-data) for additional information about log data and persistence. --- product: Mule Runtime version: 4.3 --- # Manual Migration Process > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After learning how to [prepare for a migration](https://docs.mulesoft.com/mule-runtime/4.3/migration-prep), it is important to understand the high-level migration steps. Note For an assisted migration with the Mule Migration Assistant, start instead from the [user documentation (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/migration-intro.adoc), which links to the MMA user documentation. For a completely manual migration: 1. Add all required modules, such as the Database connector, to the Anypoint Studio 7 palette. Notes: - You can add modules through the Studio 7 palette. Other modules are available in Anypoint Exchange. - All Mule projects are Mavenized by default when you add the modules to your project. 2. Migrate all the global configurations. 3. Migrate configuration properties. 4. Learn how the components work in Mule 4 to see what has changed from Mule 3. 5. Understand how changes to the Mule message structure (attributes, payload, and variables) affect your configurations. See [Introduction to Mule 4: The Mule Message](https://docs.mulesoft.com/mule-runtime/4.3/intro-mule-message). 6. Update your expressions and scripts to DataWeave version 2: - Be aware of changes between DataWeave 1 and DataWeave 2, for example, importing specific function modules and understanding syntax changes. See [Migrating from DataWeave 1.0 to 2.x](https://docs.mulesoft.com/mule-runtime/4.3/migration-dataweave). - Change MEL expressions to DataWeave 2, for example, in an connector or Choice component. See [Migrating MEL to DataWeave](https://docs.mulesoft.com/mule-runtime/4.3/migration-mel). 7. Update all exception handling to Mule 4 with the new exception types that are available. 8. If you are working with APIs, understand how to set HTTP status codes. ## See Also [Preparing for the Migration](https://docs.mulesoft.com/mule-runtime/4.3/migration-prep) [Introduction to Mule 4](https://docs.mulesoft.com/mule-runtime/4.3/intro-overview) --- product: Mule Runtime version: 4.4 --- # Manual Migration Process > For the full documentation index, see: https://docs.mulesoft.com/llms.txt After learning how to [prepare for a migration](https://docs.mulesoft.com/mule-runtime/4.4/migration-prep), it is important to understand the high-level migration steps. Note For an assisted migration with the Mule Migration Assistant, start instead from the [user documentation (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/migration-intro.adoc), which links to the MMA user documentation. For a completely manual migration: 1. Add all required modules, such as the Database connector, to the Anypoint Studio 7 palette. Notes: - You can add modules through the Studio 7 palette. Other modules are available in Anypoint Exchange. - All Mule projects are Mavenized by default when you add the modules to your project. 2. Migrate all the global configurations. 3. Migrate configuration properties. 4. Learn how the components work in Mule 4 to see what has changed from Mule 3. 5. Understand how changes to the Mule message structure (attributes, payload, and variables) affect your configurations. See [Introduction to Mule 4: The Mule Message](https://docs.mulesoft.com/mule-runtime/4.4/intro-mule-message). 6. Update your expressions and scripts to DataWeave version 2: - Be aware of changes between DataWeave 1 and DataWeave 2, for example, importing specific function modules and understanding syntax changes. See [Migrating from DataWeave 1.0 to 2.x](https://docs.mulesoft.com/mule-runtime/4.4/migration-dataweave). - Change MEL expressions to DataWeave 2, for example, in an connector or Choice component. See [Migrating MEL to DataWeave](https://docs.mulesoft.com/mule-runtime/4.4/migration-mel). 7. Update all exception handling to Mule 4 with the new exception types that are available. 8. If you are working with APIs, understand how to set HTTP status codes. ## See Also [Preparing for the Migration](https://docs.mulesoft.com/mule-runtime/4.4/migration-prep) [Introduction to Mule 4](https://docs.mulesoft.com/mule-runtime/4.4/intro-overview) --- product: Mule Runtime version: 4.11 keywords: studio, maven, version control, dependencies, libraries --- # Maven Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. This page summarizes reference information that helps you work when using Maven with Mule. Refer to [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.11/using-maven-with-mule) for an introduction and overview. ## pom.xml File ```xml /pom.xml ``` Project Object Model file that defines settings for a Maven project describing an application. It includes all settings necessary to build the application such as build plugin configurations. Note that the `pom.xml` exists on a per-project basis and is distributed along with a project. ## settings.xml File ```xml /settings.xml /.m2/settings.xml ``` Contains global settings for your Maven installation. Unlike a project’s `pom.xml`, it defines system-wide settings and is not distributed with a project, since it can contain confidential information such as authentication credentials. The `settings.xml` file can reside in two locations: - In a system-wide settings folder: In this case, it is a _global_ `settings.xml` file that defines the settings for all Maven installations on the system, regardless of user. For example: /etc/maven2/settings.xml - In a user-specific settings folder: In this case, it is a _user_ `settings.xml` file that is relevant only for a specific user’s Maven installation. The default location is the `.m2` directory in the user’s home directory: /home/joe/.m2/settings.xml On a system with both global and user `settings.xml` files, the settings from both files become merged. In case there are duplicate settings, the user’s settings take precedence over the global settings. ## MuleSoft Repositories When you create a new Mule project in Anypoint Studio, the required MuleSoft repositories are automatically added to the project. If you create the Mule project outside Studio, you have to manually add the repositories to the `pom.xml` file and also configure your credentials for Maven to access the enterprise repository. ### Configure MuleSoft Public Repositories To configure the public MuleSoft repositories, add the following to your project’s `pom.xml` file: ```xml anypoint-exchange Anypoint Exchange https://maven.anypoint.mulesoft.com/api/v3/maven default mulesoft-releases MuleSoft Releases Repository https://repository.mulesoft.org/releases/ default mulesoft-public MuleSoft Public Repository https://repository.mulesoft.org/nexus/content/repositories/public/ default mulesoft-releases MuleSoft Releases Repository default https://repository.mulesoft.org/releases/ false ``` ### Configure MuleSoft Enterprise Repository To add access to the enterprise repository to your project, you must obtain and install an Enterprise license, acquire access to the repository, and configure the repository in your project. #### Obtain and Install an Enterprise License See [Install an Enterprise License](https://docs.mulesoft.com/on-premises/latest/installing-an-enterprise-license), for instructions to acquire or install an Enterprise license #### Acquire Access to Enterprise Repositories If you are a MuleSoft customer and do not have credentials to access the [MuleSoft Enterprise repository](https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/), contact Support and request Nexus enterprise credentials. #### Configure Maven to Access MuleSoft Enterprise Repository To configure Maven to access the enterprise repository: 1. Navigate to `/.m2/settings.xml`. 2. Open `settings.xml` on all workstations that require access. If the `settings.xml` file does not exist, create it. Read more about the `settings.xml` file in the [Maven documentation](https://maven.apache.org/settings.html). 3. Add the following syntax to the `servers` section in each `settings.xml` file: ```xml ... MuleRepository YOUR_ID YOUR_PASSWORD ... ``` 4. Add the following syntax to the `profile` section in each `settings.xml` file: ```xml ... Mule true MuleRepository MuleRepository https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/ default true true ... ``` ## Useful Commands The following set of commands enables you to retrieve information about your Maven installation and to perform project-related tasks. ### Locate the Maven binary and other files (Unix) whereis mvn ### Locate Maven files such as global configuration files (Unix) locate maven ### Obtain Maven version mvn --version This also provides other information such as the Java home directory, locale and processor architecture. ### Obtain a List of Maven Commands and Options mvn -h ### Check the Manual Page for Maven (Unix) man mvn ### Create a Project mvn archetype:generate -DgroupId=com.company.app -DartifactId=myapp -DarchetypeArtifactId=myarchetypeid -DinteractiveMode=false ### Build a Project mvn package ### Clean a Project mvn clean ### Generate a Site mvn site ### Obtain a List of JAR Files Included in Your Artifact mvn dependency:build-classpath ### Obtain the Dependency Tree for Your Artifact mvn dependency:tree ## Deploying Mule Artifacts to a Central Maven Repository Using a central repository can save users' time when building applications. To deploy to a central repository, you need to deploy the Mule `POM` files and `JAR` artifacts to the desired repository. The deploy plugin is primarily used during the deploy phase, to add your artifacts to a remote repository for sharing with other developers and projects. ### Deploying pom.xml To deploy the `pom.xml` to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${project.groupId} -DartifactId=${project.artifactId} -Dversion=${version} -Dpackaging=pom -Dfile=${localPom.canonicalPath} -Durl=http:///nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. ### Deploying the JAR files To deploy a `JAR` file to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${pomProps.groupId} -DartifactId=${pomProps.artifactId} -Dversion=${pomProps.version} -Dpackaging=jar -Dfile=${f.canonicalPath} -DpomFile=${localPom.canonicalPath} -Durl=http://${your_repository_ip}/nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `your_repository_ip` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. If you wish to both install the `JAR` files locally and deploy them remotely, you can keep both locations in the argument definition. ## External Resources - [Apache Maven Home Page](https://maven.apache.org/index.html) - [Maven Getting Started Guide](https://maven.apache.org/guides/getting-started/index.html) - [Maven Deploy Plugin Reference](https://maven.apache.org/plugins/maven-deploy-plugin) - [POM Reference](https://maven.apache.org/pom.html) - [Settings Reference](https://maven.apache.org/settings.html) --- product: Mule Runtime version: 4.12 keywords: studio, maven, version control, dependencies, libraries --- # Maven Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. This page summarizes reference information that helps you work when using Maven with Mule. Refer to [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.12/using-maven-with-mule) for an introduction and overview. ## pom.xml File ```xml /pom.xml ``` Project Object Model file that defines settings for a Maven project describing an application. It includes all settings necessary to build the application such as build plugin configurations. Note that the `pom.xml` exists on a per-project basis and is distributed along with a project. ## settings.xml File ```xml /settings.xml /.m2/settings.xml ``` Contains global settings for your Maven installation. Unlike a project’s `pom.xml`, it defines system-wide settings and is not distributed with a project, since it can contain confidential information such as authentication credentials. The `settings.xml` file can reside in two locations: - In a system-wide settings folder: In this case, it is a _global_ `settings.xml` file that defines the settings for all Maven installations on the system, regardless of user. For example: /etc/maven2/settings.xml - In a user-specific settings folder: In this case, it is a _user_ `settings.xml` file that is relevant only for a specific user’s Maven installation. The default location is the `.m2` directory in the user’s home directory: /home/joe/.m2/settings.xml On a system with both global and user `settings.xml` files, the settings from both files become merged. In case there are duplicate settings, the user’s settings take precedence over the global settings. ## MuleSoft Repositories When you create a new Mule project in Anypoint Studio, the required MuleSoft repositories are automatically added to the project. If you create the Mule project outside Studio, you have to manually add the repositories to the `pom.xml` file and also configure your credentials for Maven to access the enterprise repository. ### Configure MuleSoft Public Repositories To configure the public MuleSoft repositories, add the following to your project’s `pom.xml` file: ```xml anypoint-exchange Anypoint Exchange https://maven.anypoint.mulesoft.com/api/v3/maven default mulesoft-releases MuleSoft Releases Repository https://repository.mulesoft.org/releases/ default mulesoft-public MuleSoft Public Repository https://repository.mulesoft.org/nexus/content/repositories/public/ default mulesoft-releases MuleSoft Releases Repository default https://repository.mulesoft.org/releases/ false ``` ### Configure MuleSoft Enterprise Repository To add access to the enterprise repository to your project, you must obtain and install an Enterprise license, acquire access to the repository, and configure the repository in your project. #### Obtain and Install an Enterprise License See [Install an Enterprise License](https://docs.mulesoft.com/on-premises/latest/installing-an-enterprise-license), for instructions to acquire or install an Enterprise license #### Acquire Access to Enterprise Repositories If you are a MuleSoft customer and do not have credentials to access the [MuleSoft Enterprise repository](https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/), contact Support and request Nexus enterprise credentials. #### Configure Maven to Access MuleSoft Enterprise Repository To configure Maven to access the enterprise repository: 1. Navigate to `/.m2/settings.xml`. 2. Open `settings.xml` on all workstations that require access. If the `settings.xml` file does not exist, create it. Read more about the `settings.xml` file in the [Maven documentation](https://maven.apache.org/settings.html). 3. Add the following syntax to the `servers` section in each `settings.xml` file: ```xml ... MuleRepository YOUR_ID YOUR_PASSWORD ... ``` 4. Add the following syntax to the `profile` section in each `settings.xml` file: ```xml ... Mule true MuleRepository MuleRepository https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/ default true true ... ``` ## Useful Commands The following set of commands enables you to retrieve information about your Maven installation and to perform project-related tasks. ### Locate the Maven binary and other files (Unix) whereis mvn ### Locate Maven files such as global configuration files (Unix) locate maven ### Obtain Maven version mvn --version This also provides other information such as the Java home directory, locale and processor architecture. ### Obtain a List of Maven Commands and Options mvn -h ### Check the Manual Page for Maven (Unix) man mvn ### Create a Project mvn archetype:generate -DgroupId=com.company.app -DartifactId=myapp -DarchetypeArtifactId=myarchetypeid -DinteractiveMode=false ### Build a Project mvn package ### Clean a Project mvn clean ### Generate a Site mvn site ### Obtain a List of JAR Files Included in Your Artifact mvn dependency:build-classpath ### Obtain the Dependency Tree for Your Artifact mvn dependency:tree ## Deploying Mule Artifacts to a Central Maven Repository Using a central repository can save users' time when building applications. To deploy to a central repository, you need to deploy the Mule `POM` files and `JAR` artifacts to the desired repository. The deploy plugin is primarily used during the deploy phase, to add your artifacts to a remote repository for sharing with other developers and projects. ### Deploying pom.xml To deploy the `pom.xml` to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${project.groupId} -DartifactId=${project.artifactId} -Dversion=${version} -Dpackaging=pom -Dfile=${localPom.canonicalPath} -Durl=http:///nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. ### Deploying the JAR files To deploy a `JAR` file to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${pomProps.groupId} -DartifactId=${pomProps.artifactId} -Dversion=${pomProps.version} -Dpackaging=jar -Dfile=${f.canonicalPath} -DpomFile=${localPom.canonicalPath} -Durl=http://${your_repository_ip}/nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `your_repository_ip` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. If you wish to both install the `JAR` files locally and deploy them remotely, you can keep both locations in the argument definition. ## External Resources - [Apache Maven Home Page](https://maven.apache.org/index.html) - [Maven Getting Started Guide](https://maven.apache.org/guides/getting-started/index.html) - [Maven Deploy Plugin Reference](https://maven.apache.org/plugins/maven-deploy-plugin) - [POM Reference](https://maven.apache.org/pom.html) - [Settings Reference](https://maven.apache.org/settings.html) --- product: Mule Runtime version: 4.3 keywords: studio, maven, version control, dependencies, libraries --- # Maven Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. This page summarizes reference information that helps you work when using Maven with Mule. Refer to [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.3/using-maven-with-mule) for an introduction and overview. ## pom.xml File ```xml /pom.xml ``` Project Object Model file that defines settings for a Maven project describing an application. It includes all settings necessary to build the application such as build plugin configurations. Note that the `pom.xml` exists on a per-project basis and is distributed along with a project. ## settings.xml File ```xml /settings.xml /.m2/settings.xml ``` Contains global settings for your Maven installation. Unlike a project’s `pom.xml`, it defines system-wide settings and is not distributed with a project, since it can contain confidential information such as authentication credentials. The `settings.xml` file can reside in two locations: - In a system-wide settings folder: In this case, it is a _global_ `settings.xml` file that defines the settings for all Maven installations on the system, regardless of user. For example: /etc/maven2/settings.xml - In a user-specific settings folder: In this case, it is a _user_ `settings.xml` file that is relevant only for a specific user’s Maven installation. The default location is the `.m2` directory in the user’s home directory: /home/joe/.m2/settings.xml On a system with both global and user `settings.xml` files, the settings from both files become merged. In case there are duplicate settings, the user’s settings take precedence over the global settings. ## MuleSoft Repositories When you create a new Mule project in Anypoint Studio, the required MuleSoft repositories are automatically added to the project. If you create the Mule project outside Studio, you have to manually add the repositories to the `pom.xml` file and also configure your credentials for Maven to access the enterprise repository. ### Configure MuleSoft Public Repositories To configure the public MuleSoft repositories, add the following to your project’s `pom.xml` file: ```xml anypoint-exchange Anypoint Exchange https://maven.anypoint.mulesoft.com/api/v3/maven default mulesoft-releases MuleSoft Releases Repository https://repository.mulesoft.org/releases/ default mulesoft-public MuleSoft Public Repository https://repository.mulesoft.org/nexus/content/repositories/public/ default mulesoft-releases MuleSoft Releases Repository default https://repository.mulesoft.org/releases/ false ``` ### Configure MuleSoft Enterprise Repository To add access to the enterprise repository to your project, you must obtain and install an Enterprise license, acquire access to the repository, and configure the repository in your project. #### Obtain and Install an Enterprise License See [Install an Enterprise License](https://docs.mulesoft.com/on-premises/latest/installing-an-enterprise-license), for instructions to acquire or install an Enterprise license #### Acquire Access to Enterprise Repositories If you are a MuleSoft customer and do not have credentials to access the [MuleSoft Enterprise repository](https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/), contact Support and request Nexus enterprise credentials. #### Configure Maven to Access MuleSoft Enterprise Repository To configure Maven to access the enterprise repository: 1. Navigate to `/.m2/settings.xml`. 2. Open `settings.xml` on all workstations that require access. If the `settings.xml` file does not exist, create it. Read more about the `settings.xml` file in the [Maven documentation](https://maven.apache.org/settings.html). 3. Add the following syntax to the `servers` section in each `settings.xml` file: ```xml ... MuleRepository YOUR_ID YOUR_PASSWORD ... ``` 4. Add the following syntax to the `profile` section in each `settings.xml` file: ```xml ... Mule true MuleRepository MuleRepository https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/ default true true ... ``` ## Useful Commands The following set of commands enables you to retrieve information about your Maven installation and to perform project-related tasks. ### Locate the Maven binary and other files (Unix) whereis mvn ### Locate Maven files such as global configuration files (Unix) locate maven ### Obtain Maven version mvn --version This also provides other information such as the Java home directory, locale and processor architecture. ### Obtain a List of Maven Commands and Options mvn -h ### Check the Manual Page for Maven (Unix) man mvn ### Create a Project mvn archetype:generate -DgroupId=com.company.app -DartifactId=myapp -DarchetypeArtifactId=myarchetypeid -DinteractiveMode=false ### Build a Project mvn package ### Clean a Project mvn clean ### Generate a Site mvn site ### Obtain a List of JAR Files Included in Your Artifact mvn dependency:build-classpath ### Obtain the Dependency Tree for Your Artifact mvn dependency:tree ## Deploying Mule Artifacts to a Central Maven Repository Using a central repository can save users' time when building applications. To deploy to a central repository, you need to deploy the Mule `POM` files and `JAR` artifacts to the desired repository. The deploy plugin is primarily used during the deploy phase, to add your artifacts to a remote repository for sharing with other developers and projects. ### Deploying pom.xml To deploy the `pom.xml` to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${project.groupId} -DartifactId=${project.artifactId} -Dversion=${version} -Dpackaging=pom -Dfile=${localPom.canonicalPath} -Durl=http:///nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. ### Deploying the JAR files To deploy a `JAR` file to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${pomProps.groupId} -DartifactId=${pomProps.artifactId} -Dversion=${pomProps.version} -Dpackaging=jar -Dfile=${f.canonicalPath} -DpomFile=${localPom.canonicalPath} -Durl=http://${your_repository_ip}/nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `your_repository_ip` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. If you wish to both install the `JAR` files locally and deploy them remotely, you can keep both locations in the argument definition. ## External Resources - [Apache Maven Home Page](https://maven.apache.org/index.html) - [Maven Getting Started Guide](https://maven.apache.org/guides/getting-started/index.html) - [Maven Deploy Plugin Reference](https://maven.apache.org/plugins/maven-deploy-plugin) - [POM Reference](https://maven.apache.org/pom.html) - [Settings Reference](https://maven.apache.org/settings.html) --- product: Mule Runtime version: 4.4 keywords: studio, maven, version control, dependencies, libraries --- # Maven Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. This page summarizes reference information that helps you work when using Maven with Mule. Refer to [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.4/using-maven-with-mule) for an introduction and overview. ## pom.xml File ```xml /pom.xml ``` Project Object Model file that defines settings for a Maven project describing an application. It includes all settings necessary to build the application such as build plugin configurations. Note that the `pom.xml` exists on a per-project basis and is distributed along with a project. ## settings.xml File ```xml /settings.xml /.m2/settings.xml ``` Contains global settings for your Maven installation. Unlike a project’s `pom.xml`, it defines system-wide settings and is not distributed with a project, since it can contain confidential information such as authentication credentials. The `settings.xml` file can reside in two locations: - In a system-wide settings folder: In this case, it is a _global_ `settings.xml` file that defines the settings for all Maven installations on the system, regardless of user. For example: /etc/maven2/settings.xml - In a user-specific settings folder: In this case, it is a _user_ `settings.xml` file that is relevant only for a specific user’s Maven installation. The default location is the `.m2` directory in the user’s home directory: /home/joe/.m2/settings.xml On a system with both global and user `settings.xml` files, the settings from both files become merged. In case there are duplicate settings, the user’s settings take precedence over the global settings. ## MuleSoft Repositories When you create a new Mule project in Anypoint Studio, the required MuleSoft repositories are automatically added to the project. If you create the Mule project outside Studio, you have to manually add the repositories to the `pom.xml` file and also configure your credentials for Maven to access the enterprise repository. ### Configure MuleSoft Public Repositories To configure the public MuleSoft repositories, add the following to your project’s `pom.xml` file: ```xml anypoint-exchange Anypoint Exchange https://maven.anypoint.mulesoft.com/api/v3/maven default mulesoft-releases MuleSoft Releases Repository https://repository.mulesoft.org/releases/ default mulesoft-public MuleSoft Public Repository https://repository.mulesoft.org/nexus/content/repositories/public/ default mulesoft-releases MuleSoft Releases Repository default https://repository.mulesoft.org/releases/ false ``` ### Configure MuleSoft Enterprise Repository To add access to the enterprise repository to your project, you must obtain and install an Enterprise license, acquire access to the repository, and configure the repository in your project. #### Obtain and Install an Enterprise License See [Install an Enterprise License](https://docs.mulesoft.com/on-premises/latest/installing-an-enterprise-license), for instructions to acquire or install an Enterprise license #### Acquire Access to Enterprise Repositories If you are a MuleSoft customer and do not have credentials to access the [MuleSoft Enterprise repository](https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/), contact Support and request Nexus enterprise credentials. #### Configure Maven to Access MuleSoft Enterprise Repository To configure Maven to access the enterprise repository: 1. Navigate to `/.m2/settings.xml`. 2. Open `settings.xml` on all workstations that require access. If the `settings.xml` file does not exist, create it. Read more about the `settings.xml` file in the [Maven documentation](https://maven.apache.org/settings.html). 3. Add the following syntax to the `servers` section in each `settings.xml` file: ```xml ... MuleRepository YOUR_ID YOUR_PASSWORD ... ``` 4. Add the following syntax to the `profile` section in each `settings.xml` file: ```xml ... Mule true MuleRepository MuleRepository https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/ default true true ... ``` ## Useful Commands The following set of commands enables you to retrieve information about your Maven installation and to perform project-related tasks. ### Locate the Maven binary and other files (Unix) whereis mvn ### Locate Maven files such as global configuration files (Unix) locate maven ### Obtain Maven version mvn --version This also provides other information such as the Java home directory, locale and processor architecture. ### Obtain a List of Maven Commands and Options mvn -h ### Check the Manual Page for Maven (Unix) man mvn ### Create a Project mvn archetype:generate -DgroupId=com.company.app -DartifactId=myapp -DarchetypeArtifactId=myarchetypeid -DinteractiveMode=false ### Build a Project mvn package ### Clean a Project mvn clean ### Generate a Site mvn site ### Obtain a List of JAR Files Included in Your Artifact mvn dependency:build-classpath ### Obtain the Dependency Tree for Your Artifact mvn dependency:tree ## Deploying Mule Artifacts to a Central Maven Repository Using a central repository can save users' time when building applications. To deploy to a central repository, you need to deploy the Mule `POM` files and `JAR` artifacts to the desired repository. The deploy plugin is primarily used during the deploy phase, to add your artifacts to a remote repository for sharing with other developers and projects. ### Deploying pom.xml To deploy the `pom.xml` to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${project.groupId} -DartifactId=${project.artifactId} -Dversion=${version} -Dpackaging=pom -Dfile=${localPom.canonicalPath} -Durl=http:///nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. ### Deploying the JAR files To deploy a `JAR` file to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${pomProps.groupId} -DartifactId=${pomProps.artifactId} -Dversion=${pomProps.version} -Dpackaging=jar -Dfile=${f.canonicalPath} -DpomFile=${localPom.canonicalPath} -Durl=http://${your_repository_ip}/nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `your_repository_ip` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. If you wish to both install the `JAR` files locally and deploy them remotely, you can keep both locations in the argument definition. ## External Resources - [Apache Maven Home Page](https://maven.apache.org/index.html) - [Maven Getting Started Guide](https://maven.apache.org/guides/getting-started/index.html) - [Maven Deploy Plugin Reference](https://maven.apache.org/plugins/maven-deploy-plugin) - [POM Reference](https://maven.apache.org/pom.html) - [Settings Reference](https://maven.apache.org/settings.html) --- product: Mule Runtime version: 4.6 keywords: studio, maven, version control, dependencies, libraries --- # Maven Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. This page summarizes reference information that helps you work when using Maven with Mule. Refer to [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.6/using-maven-with-mule) for an introduction and overview. ## pom.xml File ```xml /pom.xml ``` Project Object Model file that defines settings for a Maven project describing an application. It includes all settings necessary to build the application such as build plugin configurations. Note that the `pom.xml` exists on a per-project basis and is distributed along with a project. ## settings.xml File ```xml /settings.xml /.m2/settings.xml ``` Contains global settings for your Maven installation. Unlike a project’s `pom.xml`, it defines system-wide settings and is not distributed with a project, since it can contain confidential information such as authentication credentials. The `settings.xml` file can reside in two locations: - In a system-wide settings folder: In this case, it is a _global_ `settings.xml` file that defines the settings for all Maven installations on the system, regardless of user. For example: /etc/maven2/settings.xml - In a user-specific settings folder: In this case, it is a _user_ `settings.xml` file that is relevant only for a specific user’s Maven installation. The default location is the `.m2` directory in the user’s home directory: /home/joe/.m2/settings.xml On a system with both global and user `settings.xml` files, the settings from both files become merged. In case there are duplicate settings, the user’s settings take precedence over the global settings. ## MuleSoft Repositories When you create a new Mule project in Anypoint Studio, the required MuleSoft repositories are automatically added to the project. If you create the Mule project outside Studio, you have to manually add the repositories to the `pom.xml` file and also configure your credentials for Maven to access the enterprise repository. ### Configure MuleSoft Public Repositories To configure the public MuleSoft repositories, add the following to your project’s `pom.xml` file: ```xml anypoint-exchange Anypoint Exchange https://maven.anypoint.mulesoft.com/api/v3/maven default mulesoft-releases MuleSoft Releases Repository https://repository.mulesoft.org/releases/ default mulesoft-public MuleSoft Public Repository https://repository.mulesoft.org/nexus/content/repositories/public/ default mulesoft-releases MuleSoft Releases Repository default https://repository.mulesoft.org/releases/ false ``` ### Configure MuleSoft Enterprise Repository To add access to the enterprise repository to your project, you must obtain and install an Enterprise license, acquire access to the repository, and configure the repository in your project. #### Obtain and Install an Enterprise License See [Install an Enterprise License](https://docs.mulesoft.com/on-premises/latest/installing-an-enterprise-license), for instructions to acquire or install an Enterprise license #### Acquire Access to Enterprise Repositories If you are a MuleSoft customer and do not have credentials to access the [MuleSoft Enterprise repository](https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/), contact Support and request Nexus enterprise credentials. #### Configure Maven to Access MuleSoft Enterprise Repository To configure Maven to access the enterprise repository: 1. Navigate to `/.m2/settings.xml`. 2. Open `settings.xml` on all workstations that require access. If the `settings.xml` file does not exist, create it. Read more about the `settings.xml` file in the [Maven documentation](https://maven.apache.org/settings.html). 3. Add the following syntax to the `servers` section in each `settings.xml` file: ```xml ... MuleRepository YOUR_ID YOUR_PASSWORD ... ``` 4. Add the following syntax to the `profile` section in each `settings.xml` file: ```xml ... Mule true MuleRepository MuleRepository https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/ default true true ... ``` ## Useful Commands The following set of commands enables you to retrieve information about your Maven installation and to perform project-related tasks. ### Locate the Maven binary and other files (Unix) whereis mvn ### Locate Maven files such as global configuration files (Unix) locate maven ### Obtain Maven version mvn --version This also provides other information such as the Java home directory, locale and processor architecture. ### Obtain a List of Maven Commands and Options mvn -h ### Check the Manual Page for Maven (Unix) man mvn ### Create a Project mvn archetype:generate -DgroupId=com.company.app -DartifactId=myapp -DarchetypeArtifactId=myarchetypeid -DinteractiveMode=false ### Build a Project mvn package ### Clean a Project mvn clean ### Generate a Site mvn site ### Obtain a List of JAR Files Included in Your Artifact mvn dependency:build-classpath ### Obtain the Dependency Tree for Your Artifact mvn dependency:tree ## Deploying Mule Artifacts to a Central Maven Repository Using a central repository can save users' time when building applications. To deploy to a central repository, you need to deploy the Mule `POM` files and `JAR` artifacts to the desired repository. The deploy plugin is primarily used during the deploy phase, to add your artifacts to a remote repository for sharing with other developers and projects. ### Deploying pom.xml To deploy the `pom.xml` to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${project.groupId} -DartifactId=${project.artifactId} -Dversion=${version} -Dpackaging=pom -Dfile=${localPom.canonicalPath} -Durl=http:///nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. ### Deploying the JAR files To deploy a `JAR` file to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${pomProps.groupId} -DartifactId=${pomProps.artifactId} -Dversion=${pomProps.version} -Dpackaging=jar -Dfile=${f.canonicalPath} -DpomFile=${localPom.canonicalPath} -Durl=http://${your_repository_ip}/nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `your_repository_ip` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. If you wish to both install the `JAR` files locally and deploy them remotely, you can keep both locations in the argument definition. ## External Resources - [Apache Maven Home Page](https://maven.apache.org/index.html) - [Maven Getting Started Guide](https://maven.apache.org/guides/getting-started/index.html) - [Maven Deploy Plugin Reference](https://maven.apache.org/plugins/maven-deploy-plugin) - [POM Reference](https://maven.apache.org/pom.html) - [Settings Reference](https://maven.apache.org/settings.html) --- product: Mule Runtime version: 4.9 keywords: studio, maven, version control, dependencies, libraries --- # Maven Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. This page summarizes reference information that helps you work when using Maven with Mule. Refer to [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.9/using-maven-with-mule) for an introduction and overview. ## pom.xml File ```xml /pom.xml ``` Project Object Model file that defines settings for a Maven project describing an application. It includes all settings necessary to build the application such as build plugin configurations. Note that the `pom.xml` exists on a per-project basis and is distributed along with a project. ## settings.xml File ```xml /settings.xml /.m2/settings.xml ``` Contains global settings for your Maven installation. Unlike a project’s `pom.xml`, it defines system-wide settings and is not distributed with a project, since it can contain confidential information such as authentication credentials. The `settings.xml` file can reside in two locations: - In a system-wide settings folder: In this case, it is a _global_ `settings.xml` file that defines the settings for all Maven installations on the system, regardless of user. For example: /etc/maven2/settings.xml - In a user-specific settings folder: In this case, it is a _user_ `settings.xml` file that is relevant only for a specific user’s Maven installation. The default location is the `.m2` directory in the user’s home directory: /home/joe/.m2/settings.xml On a system with both global and user `settings.xml` files, the settings from both files become merged. In case there are duplicate settings, the user’s settings take precedence over the global settings. ## MuleSoft Repositories When you create a new Mule project in Anypoint Studio, the required MuleSoft repositories are automatically added to the project. If you create the Mule project outside Studio, you have to manually add the repositories to the `pom.xml` file and also configure your credentials for Maven to access the enterprise repository. ### Configure MuleSoft Public Repositories To configure the public MuleSoft repositories, add the following to your project’s `pom.xml` file: ```xml anypoint-exchange Anypoint Exchange https://maven.anypoint.mulesoft.com/api/v3/maven default mulesoft-releases MuleSoft Releases Repository https://repository.mulesoft.org/releases/ default mulesoft-public MuleSoft Public Repository https://repository.mulesoft.org/nexus/content/repositories/public/ default mulesoft-releases MuleSoft Releases Repository default https://repository.mulesoft.org/releases/ false ``` ### Configure MuleSoft Enterprise Repository To add access to the enterprise repository to your project, you must obtain and install an Enterprise license, acquire access to the repository, and configure the repository in your project. #### Obtain and Install an Enterprise License See [Install an Enterprise License](https://docs.mulesoft.com/on-premises/latest/installing-an-enterprise-license), for instructions to acquire or install an Enterprise license #### Acquire Access to Enterprise Repositories If you are a MuleSoft customer and do not have credentials to access the [MuleSoft Enterprise repository](https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/), contact Support and request Nexus enterprise credentials. #### Configure Maven to Access MuleSoft Enterprise Repository To configure Maven to access the enterprise repository: 1. Navigate to `/.m2/settings.xml`. 2. Open `settings.xml` on all workstations that require access. If the `settings.xml` file does not exist, create it. Read more about the `settings.xml` file in the [Maven documentation](https://maven.apache.org/settings.html). 3. Add the following syntax to the `servers` section in each `settings.xml` file: ```xml ... MuleRepository YOUR_ID YOUR_PASSWORD ... ``` 4. Add the following syntax to the `profile` section in each `settings.xml` file: ```xml ... Mule true MuleRepository MuleRepository https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/ default true true ... ``` ## Useful Commands The following set of commands enables you to retrieve information about your Maven installation and to perform project-related tasks. ### Locate the Maven binary and other files (Unix) whereis mvn ### Locate Maven files such as global configuration files (Unix) locate maven ### Obtain Maven version mvn --version This also provides other information such as the Java home directory, locale and processor architecture. ### Obtain a List of Maven Commands and Options mvn -h ### Check the Manual Page for Maven (Unix) man mvn ### Create a Project mvn archetype:generate -DgroupId=com.company.app -DartifactId=myapp -DarchetypeArtifactId=myarchetypeid -DinteractiveMode=false ### Build a Project mvn package ### Clean a Project mvn clean ### Generate a Site mvn site ### Obtain a List of JAR Files Included in Your Artifact mvn dependency:build-classpath ### Obtain the Dependency Tree for Your Artifact mvn dependency:tree ## Deploying Mule Artifacts to a Central Maven Repository Using a central repository can save users' time when building applications. To deploy to a central repository, you need to deploy the Mule `POM` files and `JAR` artifacts to the desired repository. The deploy plugin is primarily used during the deploy phase, to add your artifacts to a remote repository for sharing with other developers and projects. ### Deploying pom.xml To deploy the `pom.xml` to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${project.groupId} -DartifactId=${project.artifactId} -Dversion=${version} -Dpackaging=pom -Dfile=${localPom.canonicalPath} -Durl=http:///nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. ### Deploying the JAR files To deploy a `JAR` file to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${pomProps.groupId} -DartifactId=${pomProps.artifactId} -Dversion=${pomProps.version} -Dpackaging=jar -Dfile=${f.canonicalPath} -DpomFile=${localPom.canonicalPath} -Durl=http://${your_repository_ip}/nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `your_repository_ip` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. If you wish to both install the `JAR` files locally and deploy them remotely, you can keep both locations in the argument definition. ## External Resources - [Apache Maven Home Page](https://maven.apache.org/index.html) - [Maven Getting Started Guide](https://maven.apache.org/guides/getting-started/index.html) - [Maven Deploy Plugin Reference](https://maven.apache.org/plugins/maven-deploy-plugin) - [POM Reference](https://maven.apache.org/pom.html) - [Settings Reference](https://maven.apache.org/settings.html) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: studio, maven, version control, dependencies, libraries --- # Maven Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. This page summarizes reference information that helps you work when using Maven with Mule. Refer to [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/latest/using-maven-with-mule) for an introduction and overview. ## pom.xml File ```xml /pom.xml ``` Project Object Model file that defines settings for a Maven project describing an application. It includes all settings necessary to build the application such as build plugin configurations. Note that the `pom.xml` exists on a per-project basis and is distributed along with a project. ## settings.xml File ```xml /settings.xml /.m2/settings.xml ``` Contains global settings for your Maven installation. Unlike a project’s `pom.xml`, it defines system-wide settings and is not distributed with a project, since it can contain confidential information such as authentication credentials. The `settings.xml` file can reside in two locations: - In a system-wide settings folder: In this case, it is a _global_ `settings.xml` file that defines the settings for all Maven installations on the system, regardless of user. For example: /etc/maven2/settings.xml - In a user-specific settings folder: In this case, it is a _user_ `settings.xml` file that is relevant only for a specific user’s Maven installation. The default location is the `.m2` directory in the user’s home directory: /home/joe/.m2/settings.xml On a system with both global and user `settings.xml` files, the settings from both files become merged. In case there are duplicate settings, the user’s settings take precedence over the global settings. ## MuleSoft Repositories When you create a new Mule project in Anypoint Studio, the required MuleSoft repositories are automatically added to the project. If you create the Mule project outside Studio, you have to manually add the repositories to the `pom.xml` file and also configure your credentials for Maven to access the enterprise repository. ### Configure MuleSoft Public Repositories To configure the public MuleSoft repositories, add the following to your project’s `pom.xml` file: ```xml anypoint-exchange Anypoint Exchange https://maven.anypoint.mulesoft.com/api/v3/maven default mulesoft-releases MuleSoft Releases Repository https://repository.mulesoft.org/releases/ default mulesoft-public MuleSoft Public Repository https://repository.mulesoft.org/nexus/content/repositories/public/ default mulesoft-releases MuleSoft Releases Repository default https://repository.mulesoft.org/releases/ false ``` ### Configure MuleSoft Enterprise Repository To add access to the enterprise repository to your project, you must obtain and install an Enterprise license, acquire access to the repository, and configure the repository in your project. #### Obtain and Install an Enterprise License See [Install an Enterprise License](https://docs.mulesoft.com/on-premises/latest/installing-an-enterprise-license), for instructions to acquire or install an Enterprise license #### Acquire Access to Enterprise Repositories If you are a MuleSoft customer and do not have credentials to access the [MuleSoft Enterprise repository](https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/), contact Support and request Nexus enterprise credentials. #### Configure Maven to Access MuleSoft Enterprise Repository To configure Maven to access the enterprise repository: 1. Navigate to `/.m2/settings.xml`. 2. Open `settings.xml` on all workstations that require access. If the `settings.xml` file does not exist, create it. Read more about the `settings.xml` file in the [Maven documentation](https://maven.apache.org/settings.html). 3. Add the following syntax to the `servers` section in each `settings.xml` file: ```xml ... MuleRepository YOUR_ID YOUR_PASSWORD ... ``` 4. Add the following syntax to the `profile` section in each `settings.xml` file: ```xml ... Mule true MuleRepository MuleRepository https://repository.mulesoft.org/nexus-ee/content/repositories/releases-ee/ default true true ... ``` ## Useful Commands The following set of commands enables you to retrieve information about your Maven installation and to perform project-related tasks. ### Locate the Maven binary and other files (Unix) whereis mvn ### Locate Maven files such as global configuration files (Unix) locate maven ### Obtain Maven version mvn --version This also provides other information such as the Java home directory, locale and processor architecture. ### Obtain a List of Maven Commands and Options mvn -h ### Check the Manual Page for Maven (Unix) man mvn ### Create a Project mvn archetype:generate -DgroupId=com.company.app -DartifactId=myapp -DarchetypeArtifactId=myarchetypeid -DinteractiveMode=false ### Build a Project mvn package ### Clean a Project mvn clean ### Generate a Site mvn site ### Obtain a List of JAR Files Included in Your Artifact mvn dependency:build-classpath ### Obtain the Dependency Tree for Your Artifact mvn dependency:tree ## Deploying Mule Artifacts to a Central Maven Repository Using a central repository can save users' time when building applications. To deploy to a central repository, you need to deploy the Mule `POM` files and `JAR` artifacts to the desired repository. The deploy plugin is primarily used during the deploy phase, to add your artifacts to a remote repository for sharing with other developers and projects. ### Deploying pom.xml To deploy the `pom.xml` to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${project.groupId} -DartifactId=${project.artifactId} -Dversion=${version} -Dpackaging=pom -Dfile=${localPom.canonicalPath} -Durl=http:///nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. ### Deploying the JAR files To deploy a `JAR` file to a remote repository, use the following command: ```text mvn deploy:deploy-file -DgroupId=${pomProps.groupId} -DartifactId=${pomProps.artifactId} -Dversion=${pomProps.version} -Dpackaging=jar -Dfile=${f.canonicalPath} -DpomFile=${localPom.canonicalPath} -Durl=http://${your_repository_ip}/nexus/content/repositories/releases -DrepositoryId=releases ``` For the `-Durl` parameter, replace `your_repository_ip` with the correct IP address. Also, the `-DrepositoryId` needs to match with the credentials defined in the `settings.xml` file. If you wish to both install the `JAR` files locally and deploy them remotely, you can keep both locations in the argument definition. ## External Resources - [Apache Maven Home Page](https://maven.apache.org/index.html) - [Maven Getting Started Guide](https://maven.apache.org/guides/getting-started/index.html) - [Maven Deploy Plugin Reference](https://maven.apache.org/plugins/maven-deploy-plugin) - [POM Reference](https://maven.apache.org/pom.html) - [Settings Reference](https://maven.apache.org/settings.html) --- product: Mule Runtime version: 4.11 keywords: studio, maven, version control, dependencies, libraries, runtime --- # Maven Support in Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality, including the following features: - Anypoint Exchange - Connectors in Anypoint Exchange provide Maven dependency information. In Anypoint Exchange, you can click a connector asset and click **Dependency Snippets** to list the Maven `pom.xml` file dependency. - Anypoint Studio - All new projects created in Anypoint Studio 7 and later are configured with Maven by default. You can run the project with Maven from the command line, or run it directly from Anypoint Studio. - You can import an existing Maven project into Anypoint Studio and continue working on it. See [Importing and Exporting Projects](https://docs.mulesoft.com/studio/import-export-packages) for more details. - Mule Runtime Engine - You can integrate the packaging, testing, and deployment of your Mule applications with your Maven lifecycle using the [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/4.11/mmp-concept). ## Prerequisites You must be familiar with Maven concepts like managing `pom.xml` files and working with Maven plugins. If you are just getting started with Maven, we suggest you follow [Maven’s Getting Started tutorial](https://maven.apache.org/guides/getting-started/). ## Benefits Maven facilitates the management of your Mule applications both inside and outside of Anypoint Studio, providing the following benefits: - When you create a new Mule project using Anypoint Studio, you can be confident that you are working with the correct Mule project folder structure and the basic set of standard dependencies. - Anypoint Studio automatically manages your POM file every time you add new elements to your flow that require additional dependencies. - The Maven POM file makes sharing projects easier and more lightweight because the POM references the dependencies so that you don’t have to manually find and include every dependency within the project itself. - Using Maven to manage the builds ensures that the resulting final build is sanitized and standardized. - You can program automatic builds using external frameworks such as Bamboo for continuous integration. ## Recommendations - Use Anypoint Studio to design your applications. Anypoint Studio’s built-in Maven support minimizes the chances that you would have to manually update your POM file with new dependencies as you add to, or modify your applications. - Update your POM file and `settings.xml` when necessary. When updating your POM file, the `…` tag is mandatory. Depending on the type of project you are creating, valid values for this tag are `mule-application`, `mule-domain`, `mule-policy`, and `mule-domain-bundle`. For example, if you create a Mule project using Anypoint Studio, the tag is automatically configured as `mule-application`. If you create Maven projects from the command line using archetypes, you need to manage your POM file manually, and in some cases, adjust your `settings.xml` file to point to the MuleSoft Enterprise repository and supply credentials. In some cases, even if you manage your project with Anypoint Studio, you may need to make manual adjustments to your POM as well. - Use SNAPSHOT version. SNAPSHOT enables you to identify versions of your project as you work toward producing a stable product to release. For example, you can build a `1.0.0-SNAPSHOT` version of your project, test functionality, make changes, etc. until you are ready to release it as version `1.0.0`. Then you can build upon using a new version, `1.1.0-SNAPSHOT`. Example XML: ```xml com.mycompany my-application 1.0.0-SNAPSHOT mule-application ``` > [!NOTE] When using Maven for dependency management, use caution when including third-party > components in your projects. While MuleSoft maintains a secure repository, we cannot guarantee the > safety of components from external sources. Malicious attackers can create fake components and > distribute them on third-party repositories. Research and vet all third-party components before > incorporating them into your projects. This helps ensure the security and integrity of your > applications. ## Configure Your Maven Installation Even though Anypoint Studio automatically configures Maven to work with Mule when you create a new project, some scenarios require you to manually configure your Maven installation to work with Mule; for example when following continuous integration or continuous deployment (CI/CD) practices. When you manage your Maven installation, ensure that: - The `settings.xml` file is properly configured. - Configure your [Maven preferences](https://docs.mulesoft.com/studio/maven-preferences-reference) in Anypoint Studio to point to your Maven installation. - Configure access to [MuleSoft repositories](https://docs.mulesoft.com/mule-runtime/4.11/maven-reference#configure-mule-repositories). - The `pom.xml` file is properly configured. If you update your project outside Studio, keep the `pom.xml` file updated with any necessary adjustments. For additional information about Maven configuration, see the [Maven Reference](https://docs.mulesoft.com/mule-runtime/4.11/maven-reference). ## See Also - [Apache Maven](https://maven.apache.org/) - [Adjusting your Maven Preferences in Anypoint Studio](https://docs.mulesoft.com/studio/maven-preferences-reference) - [Importing and Exporting Projects in Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages) - [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/4.11/mmp-concept) - [Maven Reference](https://docs.mulesoft.com/mule-runtime/4.11/maven-reference) --- product: Mule Runtime version: 4.12 keywords: studio, maven, version control, dependencies, libraries, runtime --- # Maven Support in Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality, including the following features: - Anypoint Exchange - Connectors in Anypoint Exchange provide Maven dependency information. In Anypoint Exchange, you can click a connector asset and click **Dependency Snippets** to list the Maven `pom.xml` file dependency. - Anypoint Studio - All new projects created in Anypoint Studio 7 and later are configured with Maven by default. You can run the project with Maven from the command line, or run it directly from Anypoint Studio. - You can import an existing Maven project into Anypoint Studio and continue working on it. See [Importing and Exporting Projects](https://docs.mulesoft.com/studio/import-export-packages) for more details. - Mule Runtime Engine - You can integrate the packaging, testing, and deployment of your Mule applications with your Maven lifecycle using the [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/4.12/mmp-concept). ## Prerequisites You must be familiar with Maven concepts like managing `pom.xml` files and working with Maven plugins. If you are just getting started with Maven, we suggest you follow [Maven’s Getting Started tutorial](https://maven.apache.org/guides/getting-started/). ## Benefits Maven facilitates the management of your Mule applications both inside and outside of Anypoint Studio, providing the following benefits: - When you create a new Mule project using Anypoint Studio, you can be confident that you are working with the correct Mule project folder structure and the basic set of standard dependencies. - Anypoint Studio automatically manages your POM file every time you add new elements to your flow that require additional dependencies. - The Maven POM file makes sharing projects easier and more lightweight because the POM references the dependencies so that you don’t have to manually find and include every dependency within the project itself. - Using Maven to manage the builds ensures that the resulting final build is sanitized and standardized. - You can program automatic builds using external frameworks such as Bamboo for continuous integration. ## Recommendations - Use Anypoint Studio to design your applications. Anypoint Studio’s built-in Maven support minimizes the chances that you would have to manually update your POM file with new dependencies as you add to, or modify your applications. - Update your POM file and `settings.xml` when necessary. When updating your POM file, the `…` tag is mandatory. Depending on the type of project you are creating, valid values for this tag are `mule-application`, `mule-domain`, `mule-policy`, and `mule-domain-bundle`. For example, if you create a Mule project using Anypoint Studio, the tag is automatically configured as `mule-application`. If you create Maven projects from the command line using archetypes, you need to manage your POM file manually, and in some cases, adjust your `settings.xml` file to point to the MuleSoft Enterprise repository and supply credentials. In some cases, even if you manage your project with Anypoint Studio, you may need to make manual adjustments to your POM as well. - Use SNAPSHOT version. SNAPSHOT enables you to identify versions of your project as you work toward producing a stable product to release. For example, you can build a `1.0.0-SNAPSHOT` version of your project, test functionality, make changes, etc. until you are ready to release it as version `1.0.0`. Then you can build upon using a new version, `1.1.0-SNAPSHOT`. Example XML: ```xml com.mycompany my-application 1.0.0-SNAPSHOT mule-application ``` > [!NOTE] When using Maven for dependency management, use caution when including third-party > components in your projects. While MuleSoft maintains a secure repository, we cannot guarantee the > safety of components from external sources. Malicious attackers can create fake components and > distribute them on third-party repositories. Research and vet all third-party components before > incorporating them into your projects. This helps ensure the security and integrity of your > applications. ## Configure Your Maven Installation Even though Anypoint Studio automatically configures Maven to work with Mule when you create a new project, some scenarios require you to manually configure your Maven installation to work with Mule; for example when following continuous integration or continuous deployment (CI/CD) practices. When you manage your Maven installation, ensure that: - The `settings.xml` file is properly configured. - Configure your [Maven preferences](https://docs.mulesoft.com/studio/maven-preferences-reference) in Anypoint Studio to point to your Maven installation. - Configure access to [MuleSoft repositories](https://docs.mulesoft.com/mule-runtime/4.12/maven-reference#configure-mule-repositories). - The `pom.xml` file is properly configured. If you update your project outside Studio, keep the `pom.xml` file updated with any necessary adjustments. For additional information about Maven configuration, see the [Maven Reference](https://docs.mulesoft.com/mule-runtime/4.12/maven-reference). ## See Also - [Apache Maven](https://maven.apache.org/) - [Adjusting your Maven Preferences in Anypoint Studio](https://docs.mulesoft.com/studio/maven-preferences-reference) - [Importing and Exporting Projects in Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages) - [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/4.12/mmp-concept) - [Maven Reference](https://docs.mulesoft.com/mule-runtime/4.12/maven-reference) --- product: Mule Runtime version: 4.3 keywords: studio, maven, version control, dependencies, libraries, runtime --- # Maven Support in Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality, including the following features: - Anypoint Exchange - Connectors in Anypoint Exchange provide Maven dependency information. In Anypoint Exchange, you can click a connector asset and click **Dependency Snippets** to list the Maven `pom.xml` file dependency. - Anypoint Studio - All new projects created in Anypoint Studio 7 and later are configured with Maven by default. You can run the project with Maven from the command line, or run it directly from Anypoint Studio. - You can import an existing Maven project into Anypoint Studio and continue working on it. See [Importing and Exporting Projects](https://docs.mulesoft.com/studio/import-export-packages) for more details. - Mule Runtime Engine - You can integrate the packaging, testing, and deployment of your Mule applications with your Maven lifecycle using the [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/4.3/mmp-concept). ## Prerequisites You must be familiar with Maven concepts like managing `pom.xml` files and working with Maven plugins. If you are just getting started with Maven, we suggest you follow [Maven’s Getting Started tutorial](https://maven.apache.org/guides/getting-started/). ## Benefits Maven facilitates the management of your Mule applications both inside and outside of Anypoint Studio, providing the following benefits: - When you create a new Mule project using Anypoint Studio, you can be confident that you are working with the correct Mule project folder structure and the basic set of standard dependencies. - Anypoint Studio automatically manages your POM file every time you add new elements to your flow that require additional dependencies. - The Maven POM file makes sharing projects easier and more lightweight because the POM references the dependencies so that you don’t have to manually find and include every dependency within the project itself. - Using Maven to manage the builds ensures that the resulting final build is sanitized and standardized. - You can program automatic builds using external frameworks such as Bamboo for continuous integration. ## Recommendations - Use Anypoint Studio to design your applications. Anypoint Studio’s built-in Maven support minimizes the chances that you would have to manually update your POM file with new dependencies as you add to, or modify your applications. - Update your POM file and `settings.xml` when necessary. When updating your POM file, the `…` tag is mandatory. Depending on the type of project you are creating, valid values for this tag are `mule-application`, `mule-domain`, `mule-policy`, and `mule-domain-bundle`. For example, if you create a Mule project using Anypoint Studio, the tag is automatically configured as `mule-application`. If you create Maven projects from the command line using archetypes, you need to manage your POM file manually, and in some cases, adjust your `settings.xml` file to point to the MuleSoft Enterprise repository and supply credentials. In some cases, even if you manage your project with Anypoint Studio, you may need to make manual adjustments to your POM as well. - Use SNAPSHOT version. SNAPSHOT enables you to identify versions of your project as you work toward producing a stable product to release. For example, you can build a `1.0.0-SNAPSHOT` version of your project, test functionality, make changes, etc. until you are ready to release it as version `1.0.0`. Then you can build upon using a new version, `1.1.0-SNAPSHOT`. Example XML: ```xml com.mycompany my-application 1.0.0-SNAPSHOT mule-application ``` ## Configure Your Maven Installation Even though Anypoint Studio automatically configures Maven to work with Mule when you create a new project, some scenarios require you to manually configure your Maven installation to work with Mule; for example when following continuous integration or continuous deployment (CI/CD) practices. When you manage your Maven installation, ensure that: - The `settings.xml` file is properly configured. - Configure your [Maven preferences](https://docs.mulesoft.com/studio/maven-preferences-reference) in Anypoint Studio to point to your Maven installation. - Configure access to [MuleSoft repositories](https://docs.mulesoft.com/mule-runtime/4.3/maven-reference#configure-mule-repositories). - The `pom.xml` file is properly configured. If you update your project outside Studio, keep the `pom.xml` file updated with any necessary adjustments. For additional information about Maven configuration, see the [Maven Reference](https://docs.mulesoft.com/mule-runtime/4.3/maven-reference). ## See Also - [Apache Maven](https://maven.apache.org/) - [Adjusting your Maven Preferences in Anypoint Studio](https://docs.mulesoft.com/studio/maven-preferences-reference) - [Importing and Exporting Projects in Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages) - [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/4.3/mmp-concept) - [Maven Reference](https://docs.mulesoft.com/mule-runtime/4.3/maven-reference) --- product: Mule Runtime version: 4.4 keywords: studio, maven, version control, dependencies, libraries, runtime --- # Maven Support in Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality, including the following features: - Anypoint Exchange - Connectors in Anypoint Exchange provide Maven dependency information. In Anypoint Exchange, you can click a connector asset and click **Dependency Snippets** to list the Maven `pom.xml` file dependency. - Anypoint Studio - All new projects created in Anypoint Studio 7 and later are configured with Maven by default. You can run the project with Maven from the command line, or run it directly from Anypoint Studio. - You can import an existing Maven project into Anypoint Studio and continue working on it. See [Importing and Exporting Projects](https://docs.mulesoft.com/studio/import-export-packages) for more details. - Mule Runtime Engine - You can integrate the packaging, testing, and deployment of your Mule applications with your Maven lifecycle using the [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/4.4/mmp-concept). ## Prerequisites You must be familiar with Maven concepts like managing `pom.xml` files and working with Maven plugins. If you are just getting started with Maven, we suggest you follow [Maven’s Getting Started tutorial](https://maven.apache.org/guides/getting-started/). ## Benefits Maven facilitates the management of your Mule applications both inside and outside of Anypoint Studio, providing the following benefits: - When you create a new Mule project using Anypoint Studio, you can be confident that you are working with the correct Mule project folder structure and the basic set of standard dependencies. - Anypoint Studio automatically manages your POM file every time you add new elements to your flow that require additional dependencies. - The Maven POM file makes sharing projects easier and more lightweight because the POM references the dependencies so that you don’t have to manually find and include every dependency within the project itself. - Using Maven to manage the builds ensures that the resulting final build is sanitized and standardized. - You can program automatic builds using external frameworks such as Bamboo for continuous integration. ## Recommendations - Use Anypoint Studio to design your applications. Anypoint Studio’s built-in Maven support minimizes the chances that you would have to manually update your POM file with new dependencies as you add to, or modify your applications. - Update your POM file and `settings.xml` when necessary. When updating your POM file, the `…` tag is mandatory. Depending on the type of project you are creating, valid values for this tag are `mule-application`, `mule-domain`, `mule-policy`, and `mule-domain-bundle`. For example, if you create a Mule project using Anypoint Studio, the tag is automatically configured as `mule-application`. If you create Maven projects from the command line using archetypes, you need to manage your POM file manually, and in some cases, adjust your `settings.xml` file to point to the MuleSoft Enterprise repository and supply credentials. In some cases, even if you manage your project with Anypoint Studio, you may need to make manual adjustments to your POM as well. - Use SNAPSHOT version. SNAPSHOT enables you to identify versions of your project as you work toward producing a stable product to release. For example, you can build a `1.0.0-SNAPSHOT` version of your project, test functionality, make changes, etc. until you are ready to release it as version `1.0.0`. Then you can build upon using a new version, `1.1.0-SNAPSHOT`. Example XML: ```xml com.mycompany my-application 1.0.0-SNAPSHOT mule-application ``` ## Configure Your Maven Installation Even though Anypoint Studio automatically configures Maven to work with Mule when you create a new project, some scenarios require you to manually configure your Maven installation to work with Mule; for example when following continuous integration or continuous deployment (CI/CD) practices. When you manage your Maven installation, ensure that: - The `settings.xml` file is properly configured. - Configure your [Maven preferences](https://docs.mulesoft.com/studio/maven-preferences-reference) in Anypoint Studio to point to your Maven installation. - Configure access to [MuleSoft repositories](https://docs.mulesoft.com/mule-runtime/4.4/maven-reference#configure-mule-repositories). - The `pom.xml` file is properly configured. If you update your project outside Studio, keep the `pom.xml` file updated with any necessary adjustments. For additional information about Maven configuration, see the [Maven Reference](https://docs.mulesoft.com/mule-runtime/4.4/maven-reference). ## See Also - [Apache Maven](https://maven.apache.org/) - [Adjusting your Maven Preferences in Anypoint Studio](https://docs.mulesoft.com/studio/maven-preferences-reference) - [Importing and Exporting Projects in Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages) - [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/4.4/mmp-concept) - [Maven Reference](https://docs.mulesoft.com/mule-runtime/4.4/maven-reference) --- product: Mule Runtime version: 4.6 keywords: studio, maven, version control, dependencies, libraries, runtime --- # Maven Support in Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality, including the following features: - Anypoint Exchange - Connectors in Anypoint Exchange provide Maven dependency information. In Anypoint Exchange, you can click a connector asset and click **Dependency Snippets** to list the Maven `pom.xml` file dependency. - Anypoint Studio - All new projects created in Anypoint Studio 7 and later are configured with Maven by default. You can run the project with Maven from the command line, or run it directly from Anypoint Studio. - You can import an existing Maven project into Anypoint Studio and continue working on it. See [Importing and Exporting Projects](https://docs.mulesoft.com/studio/import-export-packages) for more details. - Mule Runtime Engine - You can integrate the packaging, testing, and deployment of your Mule applications with your Maven lifecycle using the [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/4.6/mmp-concept). ## Prerequisites You must be familiar with Maven concepts like managing `pom.xml` files and working with Maven plugins. If you are just getting started with Maven, we suggest you follow [Maven’s Getting Started tutorial](https://maven.apache.org/guides/getting-started/). ## Benefits Maven facilitates the management of your Mule applications both inside and outside of Anypoint Studio, providing the following benefits: - When you create a new Mule project using Anypoint Studio, you can be confident that you are working with the correct Mule project folder structure and the basic set of standard dependencies. - Anypoint Studio automatically manages your POM file every time you add new elements to your flow that require additional dependencies. - The Maven POM file makes sharing projects easier and more lightweight because the POM references the dependencies so that you don’t have to manually find and include every dependency within the project itself. - Using Maven to manage the builds ensures that the resulting final build is sanitized and standardized. - You can program automatic builds using external frameworks such as Bamboo for continuous integration. ## Recommendations - Use Anypoint Studio to design your applications. Anypoint Studio’s built-in Maven support minimizes the chances that you would have to manually update your POM file with new dependencies as you add to, or modify your applications. - Update your POM file and `settings.xml` when necessary. When updating your POM file, the `…` tag is mandatory. Depending on the type of project you are creating, valid values for this tag are `mule-application`, `mule-domain`, `mule-policy`, and `mule-domain-bundle`. For example, if you create a Mule project using Anypoint Studio, the tag is automatically configured as `mule-application`. If you create Maven projects from the command line using archetypes, you need to manage your POM file manually, and in some cases, adjust your `settings.xml` file to point to the MuleSoft Enterprise repository and supply credentials. In some cases, even if you manage your project with Anypoint Studio, you may need to make manual adjustments to your POM as well. - Use SNAPSHOT version. SNAPSHOT enables you to identify versions of your project as you work toward producing a stable product to release. For example, you can build a `1.0.0-SNAPSHOT` version of your project, test functionality, make changes, etc. until you are ready to release it as version `1.0.0`. Then you can build upon using a new version, `1.1.0-SNAPSHOT`. Example XML: ```xml com.mycompany my-application 1.0.0-SNAPSHOT mule-application ``` > [!NOTE] When using Maven for dependency management, use caution when including third-party > components in your projects. While MuleSoft maintains a secure repository, we cannot guarantee the > safety of components from external sources. Malicious attackers can create fake components and > distribute them on third-party repositories. Research and vet all third-party components before > incorporating them into your projects. This helps ensure the security and integrity of your > applications. ## Configure Your Maven Installation Even though Anypoint Studio automatically configures Maven to work with Mule when you create a new project, some scenarios require you to manually configure your Maven installation to work with Mule; for example when following continuous integration or continuous deployment (CI/CD) practices. When you manage your Maven installation, ensure that: - The `settings.xml` file is properly configured. - Configure your [Maven preferences](https://docs.mulesoft.com/studio/maven-preferences-reference) in Anypoint Studio to point to your Maven installation. - Configure access to [MuleSoft repositories](https://docs.mulesoft.com/mule-runtime/4.6/maven-reference#configure-mule-repositories). - The `pom.xml` file is properly configured. If you update your project outside Studio, keep the `pom.xml` file updated with any necessary adjustments. For additional information about Maven configuration, see the [Maven Reference](https://docs.mulesoft.com/mule-runtime/4.6/maven-reference). ## See Also - [Apache Maven](https://maven.apache.org/) - [Adjusting your Maven Preferences in Anypoint Studio](https://docs.mulesoft.com/studio/maven-preferences-reference) - [Importing and Exporting Projects in Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages) - [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/4.6/mmp-concept) - [Maven Reference](https://docs.mulesoft.com/mule-runtime/4.6/maven-reference) --- product: Mule Runtime version: 4.9 keywords: studio, maven, version control, dependencies, libraries, runtime --- # Maven Support in Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality, including the following features: - Anypoint Exchange - Connectors in Anypoint Exchange provide Maven dependency information. In Anypoint Exchange, you can click a connector asset and click **Dependency Snippets** to list the Maven `pom.xml` file dependency. - Anypoint Studio - All new projects created in Anypoint Studio 7 and later are configured with Maven by default. You can run the project with Maven from the command line, or run it directly from Anypoint Studio. - You can import an existing Maven project into Anypoint Studio and continue working on it. See [Importing and Exporting Projects](https://docs.mulesoft.com/studio/import-export-packages) for more details. - Mule Runtime Engine - You can integrate the packaging, testing, and deployment of your Mule applications with your Maven lifecycle using the [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/4.9/mmp-concept). ## Prerequisites You must be familiar with Maven concepts like managing `pom.xml` files and working with Maven plugins. If you are just getting started with Maven, we suggest you follow [Maven’s Getting Started tutorial](https://maven.apache.org/guides/getting-started/). ## Benefits Maven facilitates the management of your Mule applications both inside and outside of Anypoint Studio, providing the following benefits: - When you create a new Mule project using Anypoint Studio, you can be confident that you are working with the correct Mule project folder structure and the basic set of standard dependencies. - Anypoint Studio automatically manages your POM file every time you add new elements to your flow that require additional dependencies. - The Maven POM file makes sharing projects easier and more lightweight because the POM references the dependencies so that you don’t have to manually find and include every dependency within the project itself. - Using Maven to manage the builds ensures that the resulting final build is sanitized and standardized. - You can program automatic builds using external frameworks such as Bamboo for continuous integration. ## Recommendations - Use Anypoint Studio to design your applications. Anypoint Studio’s built-in Maven support minimizes the chances that you would have to manually update your POM file with new dependencies as you add to, or modify your applications. - Update your POM file and `settings.xml` when necessary. When updating your POM file, the `…` tag is mandatory. Depending on the type of project you are creating, valid values for this tag are `mule-application`, `mule-domain`, `mule-policy`, and `mule-domain-bundle`. For example, if you create a Mule project using Anypoint Studio, the tag is automatically configured as `mule-application`. If you create Maven projects from the command line using archetypes, you need to manage your POM file manually, and in some cases, adjust your `settings.xml` file to point to the MuleSoft Enterprise repository and supply credentials. In some cases, even if you manage your project with Anypoint Studio, you may need to make manual adjustments to your POM as well. - Use SNAPSHOT version. SNAPSHOT enables you to identify versions of your project as you work toward producing a stable product to release. For example, you can build a `1.0.0-SNAPSHOT` version of your project, test functionality, make changes, etc. until you are ready to release it as version `1.0.0`. Then you can build upon using a new version, `1.1.0-SNAPSHOT`. Example XML: ```xml com.mycompany my-application 1.0.0-SNAPSHOT mule-application ``` > [!NOTE] When using Maven for dependency management, use caution when including third-party > components in your projects. While MuleSoft maintains a secure repository, we cannot guarantee the > safety of components from external sources. Malicious attackers can create fake components and > distribute them on third-party repositories. Research and vet all third-party components before > incorporating them into your projects. This helps ensure the security and integrity of your > applications. ## Configure Your Maven Installation Even though Anypoint Studio automatically configures Maven to work with Mule when you create a new project, some scenarios require you to manually configure your Maven installation to work with Mule; for example when following continuous integration or continuous deployment (CI/CD) practices. When you manage your Maven installation, ensure that: - The `settings.xml` file is properly configured. - Configure your [Maven preferences](https://docs.mulesoft.com/studio/maven-preferences-reference) in Anypoint Studio to point to your Maven installation. - Configure access to [MuleSoft repositories](https://docs.mulesoft.com/mule-runtime/4.9/maven-reference#configure-mule-repositories). - The `pom.xml` file is properly configured. If you update your project outside Studio, keep the `pom.xml` file updated with any necessary adjustments. For additional information about Maven configuration, see the [Maven Reference](https://docs.mulesoft.com/mule-runtime/4.9/maven-reference). ## See Also - [Apache Maven](https://maven.apache.org/) - [Adjusting your Maven Preferences in Anypoint Studio](https://docs.mulesoft.com/studio/maven-preferences-reference) - [Importing and Exporting Projects in Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages) - [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/4.9/mmp-concept) - [Maven Reference](https://docs.mulesoft.com/mule-runtime/4.9/maven-reference) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: studio, maven, version control, dependencies, libraries, runtime --- # Maven Support in Mule > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality, including the following features: - Anypoint Exchange - Connectors in Anypoint Exchange provide Maven dependency information. In Anypoint Exchange, you can click a connector asset and click **Dependency Snippets** to list the Maven `pom.xml` file dependency. - Anypoint Studio - All new projects created in Anypoint Studio 7 and later are configured with Maven by default. You can run the project with Maven from the command line, or run it directly from Anypoint Studio. - You can import an existing Maven project into Anypoint Studio and continue working on it. See [Importing and Exporting Projects](https://docs.mulesoft.com/studio/import-export-packages) for more details. - Mule Runtime Engine - You can integrate the packaging, testing, and deployment of your Mule applications with your Maven lifecycle using the [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept). ## Prerequisites You must be familiar with Maven concepts like managing `pom.xml` files and working with Maven plugins. If you are just getting started with Maven, we suggest you follow [Maven’s Getting Started tutorial](https://maven.apache.org/guides/getting-started/). ## Benefits Maven facilitates the management of your Mule applications both inside and outside of Anypoint Studio, providing the following benefits: - When you create a new Mule project using Anypoint Studio, you can be confident that you are working with the correct Mule project folder structure and the basic set of standard dependencies. - Anypoint Studio automatically manages your POM file every time you add new elements to your flow that require additional dependencies. - The Maven POM file makes sharing projects easier and more lightweight because the POM references the dependencies so that you don’t have to manually find and include every dependency within the project itself. - Using Maven to manage the builds ensures that the resulting final build is sanitized and standardized. - You can program automatic builds using external frameworks such as Bamboo for continuous integration. ## Recommendations - Use Anypoint Studio to design your applications. Anypoint Studio’s built-in Maven support minimizes the chances that you would have to manually update your POM file with new dependencies as you add to, or modify your applications. - Update your POM file and `settings.xml` when necessary. When updating your POM file, the `…` tag is mandatory. Depending on the type of project you are creating, valid values for this tag are `mule-application`, `mule-domain`, `mule-policy`, and `mule-domain-bundle`. For example, if you create a Mule project using Anypoint Studio, the tag is automatically configured as `mule-application`. If you create Maven projects from the command line using archetypes, you need to manage your POM file manually, and in some cases, adjust your `settings.xml` file to point to the MuleSoft Enterprise repository and supply credentials. In some cases, even if you manage your project with Anypoint Studio, you may need to make manual adjustments to your POM as well. - Use SNAPSHOT version. SNAPSHOT enables you to identify versions of your project as you work toward producing a stable product to release. For example, you can build a `1.0.0-SNAPSHOT` version of your project, test functionality, make changes, etc. until you are ready to release it as version `1.0.0`. Then you can build upon using a new version, `1.1.0-SNAPSHOT`. Example XML: ```xml com.mycompany my-application 1.0.0-SNAPSHOT mule-application ``` > [!NOTE] When using Maven for dependency management, use caution when including third-party > components in your projects. While MuleSoft maintains a secure repository, we cannot guarantee the > safety of components from external sources. Malicious attackers can create fake components and > distribute them on third-party repositories. Research and vet all third-party components before > incorporating them into your projects. This helps ensure the security and integrity of your > applications. ## Configure Your Maven Installation Even though Anypoint Studio automatically configures Maven to work with Mule when you create a new project, some scenarios require you to manually configure your Maven installation to work with Mule; for example when following continuous integration or continuous deployment (CI/CD) practices. When you manage your Maven installation, ensure that: - The `settings.xml` file is properly configured. - Configure your [Maven preferences](https://docs.mulesoft.com/studio/maven-preferences-reference) in Anypoint Studio to point to your Maven installation. - Configure access to [MuleSoft repositories](https://docs.mulesoft.com/mule-runtime/latest/maven-reference#configure-mule-repositories). - The `pom.xml` file is properly configured. If you update your project outside Studio, keep the `pom.xml` file updated with any necessary adjustments. For additional information about Maven configuration, see the [Maven Reference](https://docs.mulesoft.com/mule-runtime/latest/maven-reference). ## See Also - [Apache Maven](https://maven.apache.org/) - [Adjusting your Maven Preferences in Anypoint Studio](https://docs.mulesoft.com/studio/maven-preferences-reference) - [Importing and Exporting Projects in Anypoint Studio](https://docs.mulesoft.com/studio/import-export-packages) - [Mule Maven plugin](https://docs.mulesoft.com/mule-runtime/latest/mmp-concept) - [Maven Reference](https://docs.mulesoft.com/mule-runtime/latest/maven-reference) --- product: Mule Runtime version: 4.11 keywords: tracing, correlation, id, logging, mdc, variables, anypoint, studio --- # MDC Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mapped Diagnostic Context (MDC) enriches logging and improves tracking by providing more context or information in the logs for the current Mule event. By default, Mule logs two MDC entries: `processor`, which shows the location of the current event, and `event`, which shows the correlation ID of the event. Mule Tracing module enables you to enhance your logs by adding, removing, and clearing variables from the logging context for a given Mule event. The logging context exists for the entire execution of the corresponding event. ## Prerequisites To use the MDC Logging operations, complete the following tasks: - Install the Mule Tracing module in your application. - Change the pattern layouts in the `log4j2.xml` file to `MDC`. > [!NOTE] You can use MDC Logging with Anypoint Runtime Fabric or CloudHub 2.0. However, if you are > using CloudHub 1.0 to deploy your Mule applications, MDC logging isn’t supported. ## Install the Mule Tracing Module Follow the next steps to install the Mule Tracing module in your application. 1. Open your Mule project in Anypoint Studio. 2. Go to the Mule Palette. 3. Select **Search in Exchange**, and search for the Mule Tracing module. 4. Select the module and click **Add**. 5. Click **Finish**. ## Change the Pattern Layouts in the log4j2.xml File This change instructs Mule to automatically add the MDC context, which includes the correlation ID and the processor path. You can modify the `log4j2.xml` file of your Mule application or the file of your Mule instance, which is located in `/conf/log4j2.xml`. Follow these steps to change the pattern layouts to MDC: 1. Open the `log4j2.xml` file for editing. 2. Replace `[processor: %X{processorPath}; event: %X{correlationId}]` with `[%MDC]`. ### Example log4j2.xml File Configurations Example: Default log4j2.xml file without MDC logging. Example: Updated log4j2.xml file with MDC logging. ## Available Operations
XML ElementDescriptionAccepted Attributes

set-logging-variable

Sets a logging variable and its value.

Attribute NameDescription

variableName

The name of the variable to log.

value

The value to assign to the variable. Accepts DataWeave expressions.

remove-logging-variable

Removes a logging variable.

Attribute NameDescription

variableName

The name of the variable to remove.

clear-logging-variables

Removes all the logging variables. This option doesn’t remove the processor path or the correlation ID.

None

## Configure MDC Logging in Your Application To configure MDC logging, add any of the available operations to your Mule application flow and specify the corresponding attributes. For example, to configure a logging variable, insert the `` XML element into your application flow: ... ... After executing the flow, the output logs are: INFO 2021-04-08 16:58:26,882 \[\[MuleRuntime\].uber.15: \[test-project-app\].exampleFlow.CPU\_LITE @18f679\] \[{correlationId=c85e16c0-98a4-11eb-bc34-cac765a2219b, processorPath=exampleFlow/processors/2, testVar=testValue}\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: Example This logging context affects any output of a Logger component and any internal logging that Mule runtime produces. Therefore, you can add more context to the event that Mule is processing if you need additional information for tracking down any potential issue, for example, when an unexpected error occurs. ## Example Consider the following application: ![Logger and variable setting components in a Mule error handling flow](/mulesoft/current/en-us/mule-runtime/4.11/_images/mruntime-mdc-example.png) After sending the following request: curl --location --request GET '0.0.0.0:8081/order' \\ --header 'Content-Type: application/json' \\ --data-raw '{ "orderId": 548102842, "customerId": "ARG-12934", "items": \[ "CP-123", "CP-452" \] }' The output log is: INFO 2021-04-09 11:14:38,409 \[\[MuleRuntime\].uber.05: \[tracing-module\].tracing-moduleFlow.CPU\_LITE @34a62707\] \[processor: tracing-moduleFlow/processors/2; event: eb2b2461-993d-11eb-8a64-4865ee1fd814\] {correlationId=eb2b2461-993d-11eb-8a64-4865ee1fd814, customerId=ARG-12934, processorPath=tracing-moduleFlow/processors/2, requestPath=GET:/order} org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "orderId": 548102842, "customerId": "ARG-12934", "items": \[ "CP-123", "CP-452" \] } ## See Also - [Configuring Logging](https://docs.mulesoft.com/mule-runtime/4.11/logging-in-mule) --- product: Mule Runtime version: 4.12 keywords: tracing, correlation, id, logging, mdc, variables, anypoint, studio --- # MDC Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mapped Diagnostic Context (MDC) enriches logging and improves tracking by providing more context or information in the logs for the current Mule event. By default, Mule logs two MDC entries: `processor`, which shows the location of the current event, and `event`, which shows the correlation ID of the event. Mule Tracing module enables you to enhance your logs by adding, removing, and clearing variables from the logging context for a given Mule event. The logging context exists for the entire execution of the corresponding event. ## Prerequisites To use the MDC Logging operations, complete the following tasks: - Install the Mule Tracing module in your application. - Change the pattern layouts in the `log4j2.xml` file to `MDC`. > [!NOTE] You can use MDC Logging with Anypoint Runtime Fabric or CloudHub 2.0. However, if you are > using CloudHub 1.0 to deploy your Mule applications, MDC logging isn’t supported. ## Install the Mule Tracing Module Follow the next steps to install the Mule Tracing module in your application. 1. Open your Mule project in Anypoint Studio. 2. Go to the Mule Palette. 3. Select **Search in Exchange**, and search for the Mule Tracing module. 4. Select the module and click **Add**. 5. Click **Finish**. ## Change the Pattern Layouts in the log4j2.xml File This change instructs Mule to automatically add the MDC context, which includes the correlation ID and the processor path. You can modify the `log4j2.xml` file of your Mule application or the file of your Mule instance, which is located in `/conf/log4j2.xml`. Follow these steps to change the pattern layouts to MDC: 1. Open the `log4j2.xml` file for editing. 2. Replace `[processor: %X{processorPath}; event: %X{correlationId}]` with `[%MDC]`. ### Example log4j2.xml File Configurations Example: Default log4j2.xml file without MDC logging. Example: Updated log4j2.xml file with MDC logging. ## Available Operations
XML ElementDescriptionAccepted Attributes

set-logging-variable

Sets a logging variable and its value.

Attribute NameDescription

variableName

The name of the variable to log.

value

The value to assign to the variable. Accepts DataWeave expressions.

remove-logging-variable

Removes a logging variable.

Attribute NameDescription

variableName

The name of the variable to remove.

clear-logging-variables

Removes all the logging variables. This option doesn’t remove the processor path or the correlation ID.

None

## Configure MDC Logging in Your Application To configure MDC logging, add any of the available operations to your Mule application flow and specify the corresponding attributes. For example, to configure a logging variable, insert the `` XML element into your application flow: ... ... After executing the flow, the output logs are: INFO 2021-04-08 16:58:26,882 \[\[MuleRuntime\].uber.15: \[test-project-app\].exampleFlow.CPU\_LITE @18f679\] \[{correlationId=c85e16c0-98a4-11eb-bc34-cac765a2219b, processorPath=exampleFlow/processors/2, testVar=testValue}\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: Example This logging context affects any output of a Logger component and any internal logging that Mule runtime produces. Therefore, you can add more context to the event that Mule is processing if you need additional information for tracking down any potential issue, for example, when an unexpected error occurs. ## Example Consider the following application: ![Logger and variable setting components in a Mule error handling flow](/mulesoft/current/en-us/mule-runtime/4.12/_images/mruntime-mdc-example.png) After sending the following request: curl --location --request GET '0.0.0.0:8081/order' \\ --header 'Content-Type: application/json' \\ --data-raw '{ "orderId": 548102842, "customerId": "ARG-12934", "items": \[ "CP-123", "CP-452" \] }' The output log is: INFO 2021-04-09 11:14:38,409 \[\[MuleRuntime\].uber.05: \[tracing-module\].tracing-moduleFlow.CPU\_LITE @34a62707\] \[processor: tracing-moduleFlow/processors/2; event: eb2b2461-993d-11eb-8a64-4865ee1fd814\] {correlationId=eb2b2461-993d-11eb-8a64-4865ee1fd814, customerId=ARG-12934, processorPath=tracing-moduleFlow/processors/2, requestPath=GET:/order} org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "orderId": 548102842, "customerId": "ARG-12934", "items": \[ "CP-123", "CP-452" \] } ## See Also - [Configuring Logging](https://docs.mulesoft.com/mule-runtime/4.12/logging-in-mule) --- product: Mule Runtime version: 4.4 keywords: tracing, correlation, id, logging, mdc, variables, anypoint, studio --- # MDC Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mapped Diagnostic Context (MDC) enriches logging and improves tracking by providing more context or information in the logs for the current Mule event. By default, Mule logs two MDC entries: `processor`, which shows the location of the current event, and `event`, which shows the correlation ID of the event. Mule Tracing module enables you to enhance your logs by adding, removing, and clearing variables from the logging context for a given Mule event. The logging context exists for the entire execution of the corresponding event. ## Prerequisites To use the MDC Logging operations, complete the following tasks: - Install the Mule Tracing module in your application. - Change the pattern layouts in the `log4j2.xml` file to `MDC`. > [!NOTE] If you are using Anypoint Runtime Fabric or CloudHub 2.0 to deploy your Mule applications, > MDC logging isn’t supported. ## Install the Mule Tracing Module Follow the next steps to install the Mule Tracing module in your application. 1. Open your Mule project in Anypoint Studio. 2. Go to the Mule Palette. 3. Select **Search in Exchange**, and search for the Mule Tracing module. 4. Select the module and click **Add**. 5. Click **Finish**. ## Change the Pattern Layouts in the log4j2.xml File This change instructs Mule to automatically add the MDC context, which includes the correlation ID and the processor path. You can modify the `log4j2.xml` file of your Mule application or the file of your Mule instance, which is located in `/conf/log4j2.xml`. Follow these steps to change the pattern layouts to MDC: 1. Open the `log4j2.xml` file for editing. 2. Replace `[processor: %X{processorPath}; event: %X{correlationId}]` with `[%MDC]`. ### Example log4j2.xml File Configurations Example: Default log4j2.xml file without MDC logging. Example: Updated log4j2.xml file with MDC logging. ## Available Operations
XML ElementDescriptionAccepted Attributes

set-logging-variable

Sets a logging variable and its value.

Attribute NameDescription

variableName

The name of the variable to log.

value

The value to assign to the variable. Accepts DataWeave expressions.

remove-logging-variable

Removes a logging variable.

Attribute NameDescription

variableName

The name of the variable to remove.

clear-logging-variables

Removes all the logging variables. This option does not remove the processor path or the correlation ID.

None

## Configure MDC Logging in Your Application To configure MDC logging, add any of the available operations to your Mule application flow and specify the corresponding attributes. For example, to configure a logging variable, insert the `` XML element into your application flow: ... ... After executing the flow, the output logs are: INFO 2021-04-08 16:58:26,882 \[\[MuleRuntime\].uber.15: \[test-project-app\].exampleFlow.CPU\_LITE @18f679\] \[{correlationId=c85e16c0-98a4-11eb-bc34-cac765a2219b, processorPath=exampleFlow/processors/2, testVar=testValue}\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: Example This logging context affects any output of a Logger component and any internal logging that Mule runtime produces. Therefore, you can add more context to the event that Mule is processing if you need additional information for tracking down any potential issue, for example, when an unexpected error occurs. ## Example Consider the following application: ![MDC Logging Example](/mulesoft/current/en-us/mule-runtime/4.4/_images/mruntime-mdc-example.png) After sending the following request: curl --location --request GET '0.0.0.0:8081/order' \\ --header 'Content-Type: application/json' \\ --data-raw '{ "orderId": 548102842, "customerId": "ARG-12934", "items": \[ "CP-123", "CP-452" \] }' The output log is: INFO 2021-04-09 11:14:38,409 \[\[MuleRuntime\].uber.05: \[tracing-module\].tracing-moduleFlow.CPU\_LITE @34a62707\] \[processor: tracing-moduleFlow/processors/2; event: eb2b2461-993d-11eb-8a64-4865ee1fd814\] {correlationId=eb2b2461-993d-11eb-8a64-4865ee1fd814, customerId=ARG-12934, processorPath=tracing-moduleFlow/processors/2, requestPath=GET:/order} org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "orderId": 548102842, "customerId": "ARG-12934", "items": \[ "CP-123", "CP-452" \] } ## See Also - [Configuring Logging](https://docs.mulesoft.com/mule-runtime/4.4/logging-in-mule) --- product: Mule Runtime version: 4.6 keywords: tracing, correlation, id, logging, mdc, variables, anypoint, studio --- # MDC Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mapped Diagnostic Context (MDC) enriches logging and improves tracking by providing more context or information in the logs for the current Mule event. By default, Mule logs two MDC entries: `processor`, which shows the location of the current event, and `event`, which shows the correlation ID of the event. Mule Tracing module enables you to enhance your logs by adding, removing, and clearing variables from the logging context for a given Mule event. The logging context exists for the entire execution of the corresponding event. ## Prerequisites To use the MDC Logging operations, complete the following tasks: - Install the Mule Tracing module in your application. - Change the pattern layouts in the `log4j2.xml` file to `MDC`. > [!NOTE] If you are using Anypoint Runtime Fabric or CloudHub 2.0 to deploy your Mule applications, > MDC logging isn’t supported. ## Install the Mule Tracing Module Follow the next steps to install the Mule Tracing module in your application. 1. Open your Mule project in Anypoint Studio. 2. Go to the Mule Palette. 3. Select **Search in Exchange**, and search for the Mule Tracing module. 4. Select the module and click **Add**. 5. Click **Finish**. ## Change the Pattern Layouts in the log4j2.xml File This change instructs Mule to automatically add the MDC context, which includes the correlation ID and the processor path. You can modify the `log4j2.xml` file of your Mule application or the file of your Mule instance, which is located in `/conf/log4j2.xml`. Follow these steps to change the pattern layouts to MDC: 1. Open the `log4j2.xml` file for editing. 2. Replace `[processor: %X{processorPath}; event: %X{correlationId}]` with `[%MDC]`. ### Example log4j2.xml File Configurations Example: Default log4j2.xml file without MDC logging. Example: Updated log4j2.xml file with MDC logging. ## Available Operations
XML ElementDescriptionAccepted Attributes

set-logging-variable

Sets a logging variable and its value.

Attribute NameDescription

variableName

The name of the variable to log.

value

The value to assign to the variable. Accepts DataWeave expressions.

remove-logging-variable

Removes a logging variable.

Attribute NameDescription

variableName

The name of the variable to remove.

clear-logging-variables

Removes all the logging variables. This option does not remove the processor path or the correlation ID.

None

## Configure MDC Logging in Your Application To configure MDC logging, add any of the available operations to your Mule application flow and specify the corresponding attributes. For example, to configure a logging variable, insert the `` XML element into your application flow: ... ... After executing the flow, the output logs are: INFO 2021-04-08 16:58:26,882 \[\[MuleRuntime\].uber.15: \[test-project-app\].exampleFlow.CPU\_LITE @18f679\] \[{correlationId=c85e16c0-98a4-11eb-bc34-cac765a2219b, processorPath=exampleFlow/processors/2, testVar=testValue}\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: Example This logging context affects any output of a Logger component and any internal logging that Mule runtime produces. Therefore, you can add more context to the event that Mule is processing if you need additional information for tracking down any potential issue, for example, when an unexpected error occurs. ## Example Consider the following application: ![MDC Logging Example](/mulesoft/current/en-us/mule-runtime/4.6/_images/mruntime-mdc-example.png) After sending the following request: curl --location --request GET '0.0.0.0:8081/order' \\ --header 'Content-Type: application/json' \\ --data-raw '{ "orderId": 548102842, "customerId": "ARG-12934", "items": \[ "CP-123", "CP-452" \] }' The output log is: INFO 2021-04-09 11:14:38,409 \[\[MuleRuntime\].uber.05: \[tracing-module\].tracing-moduleFlow.CPU\_LITE @34a62707\] \[processor: tracing-moduleFlow/processors/2; event: eb2b2461-993d-11eb-8a64-4865ee1fd814\] {correlationId=eb2b2461-993d-11eb-8a64-4865ee1fd814, customerId=ARG-12934, processorPath=tracing-moduleFlow/processors/2, requestPath=GET:/order} org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "orderId": 548102842, "customerId": "ARG-12934", "items": \[ "CP-123", "CP-452" \] } ## See Also - [Configuring Logging](https://docs.mulesoft.com/mule-runtime/4.6/logging-in-mule) --- product: Mule Runtime version: 4.9 keywords: tracing, correlation, id, logging, mdc, variables, anypoint, studio --- # MDC Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mapped Diagnostic Context (MDC) enriches logging and improves tracking by providing more context or information in the logs for the current Mule event. By default, Mule logs two MDC entries: `processor`, which shows the location of the current event, and `event`, which shows the correlation ID of the event. Mule Tracing module enables you to enhance your logs by adding, removing, and clearing variables from the logging context for a given Mule event. The logging context exists for the entire execution of the corresponding event. ## Prerequisites To use the MDC Logging operations, complete the following tasks: - Install the Mule Tracing module in your application. - Change the pattern layouts in the `log4j2.xml` file to `MDC`. > [!NOTE] You can use MDC Logging with Anypoint Runtime Fabric or CloudHub 2.0. However, if you are > using CloudHub 1.0 to deploy your Mule applications, MDC logging isn’t supported. ## Install the Mule Tracing Module Follow the next steps to install the Mule Tracing module in your application. 1. Open your Mule project in Anypoint Studio. 2. Go to the Mule Palette. 3. Select **Search in Exchange**, and search for the Mule Tracing module. 4. Select the module and click **Add**. 5. Click **Finish**. ## Change the Pattern Layouts in the log4j2.xml File This change instructs Mule to automatically add the MDC context, which includes the correlation ID and the processor path. You can modify the `log4j2.xml` file of your Mule application or the file of your Mule instance, which is located in `/conf/log4j2.xml`. Follow these steps to change the pattern layouts to MDC: 1. Open the `log4j2.xml` file for editing. 2. Replace `[processor: %X{processorPath}; event: %X{correlationId}]` with `[%MDC]`. ### Example log4j2.xml File Configurations Example: Default log4j2.xml file without MDC logging. Example: Updated log4j2.xml file with MDC logging. ## Available Operations
XML ElementDescriptionAccepted Attributes

set-logging-variable

Sets a logging variable and its value.

Attribute NameDescription

variableName

The name of the variable to log.

value

The value to assign to the variable. Accepts DataWeave expressions.

remove-logging-variable

Removes a logging variable.

Attribute NameDescription

variableName

The name of the variable to remove.

clear-logging-variables

Removes all the logging variables. This option doesn’t remove the processor path or the correlation ID.

None

## Configure MDC Logging in Your Application To configure MDC logging, add any of the available operations to your Mule application flow and specify the corresponding attributes. For example, to configure a logging variable, insert the `` XML element into your application flow: ... ... After executing the flow, the output logs are: INFO 2021-04-08 16:58:26,882 \[\[MuleRuntime\].uber.15: \[test-project-app\].exampleFlow.CPU\_LITE @18f679\] \[{correlationId=c85e16c0-98a4-11eb-bc34-cac765a2219b, processorPath=exampleFlow/processors/2, testVar=testValue}\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: Example This logging context affects any output of a Logger component and any internal logging that Mule runtime produces. Therefore, you can add more context to the event that Mule is processing if you need additional information for tracking down any potential issue, for example, when an unexpected error occurs. ## Example Consider the following application: ![Logger and variable setting components in a Mule error handling flow](/mulesoft/current/en-us/mule-runtime/4.9/_images/mruntime-mdc-example.png) After sending the following request: curl --location --request GET '0.0.0.0:8081/order' \\ --header 'Content-Type: application/json' \\ --data-raw '{ "orderId": 548102842, "customerId": "ARG-12934", "items": \[ "CP-123", "CP-452" \] }' The output log is: INFO 2021-04-09 11:14:38,409 \[\[MuleRuntime\].uber.05: \[tracing-module\].tracing-moduleFlow.CPU\_LITE @34a62707\] \[processor: tracing-moduleFlow/processors/2; event: eb2b2461-993d-11eb-8a64-4865ee1fd814\] {correlationId=eb2b2461-993d-11eb-8a64-4865ee1fd814, customerId=ARG-12934, processorPath=tracing-moduleFlow/processors/2, requestPath=GET:/order} org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "orderId": 548102842, "customerId": "ARG-12934", "items": \[ "CP-123", "CP-452" \] } ## See Also - [Configuring Logging](https://docs.mulesoft.com/mule-runtime/4.9/logging-in-mule) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: tracing, correlation, id, logging, mdc, variables, anypoint, studio --- # MDC Logging > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mapped Diagnostic Context (MDC) enriches logging and improves tracking by providing more context or information in the logs for the current Mule event. By default, Mule logs two MDC entries: `processor`, which shows the location of the current event, and `event`, which shows the correlation ID of the event. Mule Tracing module enables you to enhance your logs by adding, removing, and clearing variables from the logging context for a given Mule event. The logging context exists for the entire execution of the corresponding event. ## Prerequisites To use the MDC Logging operations, complete the following tasks: - Install the Mule Tracing module in your application. - Change the pattern layouts in the `log4j2.xml` file to `MDC`. > [!NOTE] You can use MDC Logging with Anypoint Runtime Fabric or CloudHub 2.0. However, if you are > using CloudHub 1.0 to deploy your Mule applications, MDC logging isn’t supported. ## Install the Mule Tracing Module Follow the next steps to install the Mule Tracing module in your application. 1. Open your Mule project in Anypoint Studio. 2. Go to the Mule Palette. 3. Select **Search in Exchange**, and search for the Mule Tracing module. 4. Select the module and click **Add**. 5. Click **Finish**. ## Change the Pattern Layouts in the log4j2.xml File This change instructs Mule to automatically add the MDC context, which includes the correlation ID and the processor path. You can modify the `log4j2.xml` file of your Mule application or the file of your Mule instance, which is located in `/conf/log4j2.xml`. Follow these steps to change the pattern layouts to MDC: 1. Open the `log4j2.xml` file for editing. 2. Replace `[processor: %X{processorPath}; event: %X{correlationId}]` with `[%MDC]`. ### Example log4j2.xml File Configurations Example: Default log4j2.xml file without MDC logging. Example: Updated log4j2.xml file with MDC logging. ## Available Operations
XML ElementDescriptionAccepted Attributes

set-logging-variable

Sets a logging variable and its value.

Attribute NameDescription

variableName

The name of the variable to log.

value

The value to assign to the variable. Accepts DataWeave expressions.

remove-logging-variable

Removes a logging variable.

Attribute NameDescription

variableName

The name of the variable to remove.

clear-logging-variables

Removes all the logging variables. This option doesn’t remove the processor path or the correlation ID.

None

## Configure MDC Logging in Your Application To configure MDC logging, add any of the available operations to your Mule application flow and specify the corresponding attributes. For example, to configure a logging variable, insert the `` XML element into your application flow: ... ... After executing the flow, the output logs are: INFO 2021-04-08 16:58:26,882 \[\[MuleRuntime\].uber.15: \[test-project-app\].exampleFlow.CPU\_LITE @18f679\] \[{correlationId=c85e16c0-98a4-11eb-bc34-cac765a2219b, processorPath=exampleFlow/processors/2, testVar=testValue}\] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: Example This logging context affects any output of a Logger component and any internal logging that Mule runtime produces. Therefore, you can add more context to the event that Mule is processing if you need additional information for tracking down any potential issue, for example, when an unexpected error occurs. ## Example Consider the following application: ![Logger and variable setting components in a Mule error handling flow](/mulesoft/current/en-us/mule-runtime/latest/_images/mruntime-mdc-example.png) After sending the following request: curl --location --request GET '0.0.0.0:8081/order' \\ --header 'Content-Type: application/json' \\ --data-raw '{ "orderId": 548102842, "customerId": "ARG-12934", "items": \[ "CP-123", "CP-452" \] }' The output log is: INFO 2021-04-09 11:14:38,409 \[\[MuleRuntime\].uber.05: \[tracing-module\].tracing-moduleFlow.CPU\_LITE @34a62707\] \[processor: tracing-moduleFlow/processors/2; event: eb2b2461-993d-11eb-8a64-4865ee1fd814\] {correlationId=eb2b2461-993d-11eb-8a64-4865ee1fd814, customerId=ARG-12934, processorPath=tracing-moduleFlow/processors/2, requestPath=GET:/order} org.mule.runtime.core.internal.processor.LoggerMessageProcessor: { "orderId": 548102842, "customerId": "ARG-12934", "items": \[ "CP-123", "CP-452" \] } ## See Also - [Configuring Logging](https://docs.mulesoft.com/mule-runtime/latest/logging-in-mule) --- product: Mule Runtime version: 4.3 --- # Migrate Applications Managed by API Manager > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You migrate your existing Mule 3 applications that are managed by API Manager to Mule 4 using the following steps: 1. [Prepare for your migration](#prepare-migration) Based on how your existing Mule 3 application is configured, carefully review the prerequisites to prepare for your migration. 2. [Determine your migration approach](#determine-migration-approach) Based on several factors, such as whether the migration requires taking downtime, removing applied policies, migrating contracts, or creating an instance for the migration. 3. [Perform the migration](#perform-migration) Migrate your application. ## Prepare to Migrate Your Mule 3 Applications Before you migrate your existing API-managed Mule 3 applications to Mule 4, carefully review the following guidelines and determine: - How your Mule 3 application is managed: basic endpoint, integration application, or complex proxy To migrate your application in this scenario, first [review how to migrate API gateways](https://docs.mulesoft.com/mule-runtime/latest/) to prepare, and then [migrate to Mule 4](https://docs.mulesoft.com/mule-runtime/latest/). - How your application is secured: default or custom policies If you applied custom policies to your Mule 3 API, follow [Migrating API Policies](https://docs.mulesoft.com/mule-runtime/latest/). If you have applied an out-of-the-box proxy, you can recreate the proxy by using the API Manager UI. - Whether you have classified your API If you have not classified your API, first [classify an API Instance into an Environment](https://docs.mulesoft.com/api-manager/latest/classify-api-task). ## Determine Your Migration Approach You migrate your API Manager-managed Mule 3 application by creating a new API instance. Before migrating to Mule 4, carefully consider the following factors to determine the approach that best suits your requirements:
Migration FactorCreate API Instance

Requires downtime

No

Requires removing applied policies

No

Requires migrating contracts

Yes

Provides API metrics continuity on API Instance

No

## Perform the Migration You can migrate your Mule 3 application using: - [A New API Instance](#migrate-with-new-api) ### Migrate Using a New API Instance Use the high-level proposal illustrated in the following diagram to use a new API instance for configuring an independent Mule runtime instance on Mule 4: ![new instance migration mule4](/mulesoft/current/en-us/mule-runtime/4.3/_images/new-instance-migration-mule4.png) If your Mule application is not a proxy, this same proposal applies to your migration procedure, without the backend component. To migrate your Mule 3 API to Mule 4 using a new API instance: 1. From the **API Administration** page in API Manager, select **Manage API** > **Create new API**. Use an instance label to identify this new API instance. 2. On the **Endpoint Configuration** window, select `Mule 4` in **Mule version** and save. 3. From the left navigation pane in API Manager, apply alerts, SLA tiers, and policies to your API. 4. If your API uses contract-based policies, for example Client ID Enforcement policy, [migrate the contracts](#migrate-contracts) of the API instance. 5. If you completed configuring your API, start your Mule 4 application and try sending it requests. 6. After successfully validating your application, undeploy your Mule 3 application. ### Migrate Contracts Before migrating your application by creating a new API instance, migrate existing API contracts to your new Mule 4 environment. **Task Prerequisite** Before you migrate your contracts, ensure that you have the following roles: - Organization Administrator of the root organization - Application Owner of every application that has a contract with the source API To migrate contracts using the Anypoint Platform UI: 1. Go to **API Manager** > **Client Applications** and select the application. Ensure that the `API` option is selected in the **Contracts** field. 2. On the right navigation, scroll down to the **Owners** field and add your name. 3. From **Exchange**, select your API instance and request access. 4. From **API Manager**, grant yourself the access. To automate the request approval process: 1. Add owners for the application: ```text curl 'https://anypoint.mulesoft.com/apiplatform/repository/v2/organizations//applications//owners' \ -H 'Content-Type: application/json;charset=UTF-8' \ -H 'Authorization: Bearer ' \ --data-raw '{"id":"/applications//contracts' \ -H 'authorization: bearer ' \ -H 'content-type: application/json' \ --data-raw '{"apiId":"","environmentId":"","instanceType":"api","acceptedTerms":true,"organizationId":"","groupId":"","assetId":"","version":"","versionGroup":""}' ``` 3. Approve contracts: ```text curl 'https://anypoint.mulesoft.com/apimanager/xapi/v1/organizations//environments//apis//contracts//approve' \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json;charset=UTF-8' \ --data-raw '{}' ``` ## Migrating to the Latest Mule 3 Version If you are not ready to migrate to Mule 4 and you need to migrate to the latest version of Mule 3, see xref:release-notes::mule-runtime/updating-mule-versions.adoc\[Upgrading Mule Runtime Engine(Versions 3.x to 3.n). Carefully review the release notes for the Mule version to which you are migrating. When you start the new Mule runtime with the same application pointing to the same API instance, your existent API is instantly managed with the latest Mule 3.x version. You do not need to perform any additional steps in API Manager. --- product: Mule Runtime version: 4.4 --- # Migrate Applications Managed by API Manager > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You migrate your existing Mule 3 applications that are managed by API Manager to Mule 4 using the following steps: 1. [Prepare for your migration](#prepare-migration) Based on how your existing Mule 3 application is configured, carefully review the prerequisites to prepare for your migration. 2. [Determine your migration approach](#determine-migration-approach) Based on several factors, such as whether the migration requires taking downtime, removing applied policies, migrating contracts, or creating an instance for the migration. 3. [Perform the migration](#perform-migration) Migrate your application. ## Prepare to Migrate Your Mule 3 Applications Before you migrate your existing API-managed Mule 3 applications to Mule 4, carefully review the following guidelines and determine: - How your Mule 3 application is managed: basic endpoint, integration application, or complex proxy To migrate your application in this scenario, first [review how to migrate API gateways](https://docs.mulesoft.com/mule-runtime/latest/) to prepare, and then [migrate to Mule 4](https://docs.mulesoft.com/mule-runtime/latest/). - How your application is secured: default or custom policies If you applied custom policies to your Mule 3 API, follow [Migrating API Policies](https://docs.mulesoft.com/mule-runtime/latest/). If you have applied an out-of-the-box proxy, you can recreate the proxy by using the API Manager UI. - Whether you have classified your API If you have not classified your API, first [classify an API Instance into an Environment](https://docs.mulesoft.com/api-manager/latest/classify-api-task). ## Determine Your Migration Approach You migrate your API Manager-managed Mule 3 application by creating a new API instance. Before migrating to Mule 4, carefully consider the following factors to determine the approach that best suits your requirements:
Migration FactorCreate API Instance

Requires downtime

No

Requires removing applied policies

No

Requires migrating contracts

Yes

Provides API metrics continuity on API Instance

No

## Perform the Migration You can migrate your Mule 3 application using: - [A New API Instance](#migrate-with-new-api) ### Migrate Using a New API Instance Use the high-level proposal illustrated in the following diagram to use a new API instance for configuring an independent Mule runtime instance on Mule 4: ![new instance migration mule4](/mulesoft/current/en-us/mule-runtime/4.4/_images/new-instance-migration-mule4.png) If your Mule application is not a proxy, this same proposal applies to your migration procedure, without the backend component. To migrate your Mule 3 API to Mule 4 using a new API instance: 1. From the **API Administration** page in API Manager, select **Manage API** > **Create new API**. Use an instance label to identify this new API instance. 2. On the **Endpoint Configuration** window, select `Mule 4` in **Mule version** and save. 3. From the left navigation pane in API Manager, apply alerts, SLA tiers, and policies to your API. 4. If your API uses contract-based policies, for example Client ID Enforcement policy, [migrate the contracts](#migrate-contracts) of the API instance. 5. If you completed configuring your API, start your Mule 4 application and try sending it requests. 6. After successfully validating your application, undeploy your Mule 3 application. ### Migrate Contracts Before migrating your application by creating a new API instance, migrate existing API contracts to your new Mule 4 environment. **Task Prerequisite** Before you migrate your contracts, ensure that you have the following roles: - Organization Administrator of the root organization - Application Owner of every application that has a contract with the source API To migrate contracts using the Anypoint Platform UI: 1. Go to **API Manager** > **Client Applications** and select the application. Ensure that the `API` option is selected in the **Contracts** field. 2. On the right navigation, scroll down to the **Owners** field and add your name. 3. From **Exchange**, select your API instance and request access. 4. From **API Manager**, grant yourself the access. To automate the request approval process: 1. Add owners for the application: ```text curl 'https://anypoint.mulesoft.com/apiplatform/repository/v2/organizations//applications//owners' \ -H 'Content-Type: application/json;charset=UTF-8' \ -H 'Authorization: Bearer ' \ --data-raw '{"id":"/applications//contracts' \ -H 'authorization: bearer ' \ -H 'content-type: application/json' \ --data-raw '{"apiId":"","environmentId":"","instanceType":"api","acceptedTerms":true,"organizationId":"","groupId":"","assetId":"","version":"","versionGroup":""}' ``` 3. Approve contracts: ```text curl 'https://anypoint.mulesoft.com/apimanager/xapi/v1/organizations//environments//apis//contracts//approve' \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json;charset=UTF-8' \ --data-raw '{}' ``` ## Migrating to the Latest Mule 3 Version If you are not ready to migrate to Mule 4 and you need to migrate to the latest version of Mule 3, see [Upgrading Mule Runtime Engine(Versions 3.x to 3.n)](https://docs.mulesoft.com/release-notes/mule-runtime/updating-mule-versions). Carefully review the release notes for the Mule version to which you are migrating. When you start the new Mule runtime with the same application pointing to the same API instance, your existent API is instantly managed with the latest Mule 3.x version. You do not need to perform any additional steps in API Manager. # Migrating an APIkit-based Application This example covers the necessary steps for successfully migrate an APIkit-based application from Mule 3 to Mule 4. The following REST API performs CRUD (create, read, update and delete) operations over a MySQL database. ![api-main in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-main.png) ![api-console in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-console.png) ![get:/product:api-config flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-get-products.png) ![get:/product/{id}:api-config flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-get-product-id.png) ![post:/product:application/json:api-config flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-post-product.png) ![delete:/product/{id}:api-config flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-delete-product.png) ![put:/product/{id}:application/json:api-config flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-put-product.png) ![api-apiKitGlobalExceptionMapping flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-globalexceptionmapping.png) ## [](#migrating-property-placeholders)Migrating Property Placeholders Mule 4 supports property placeholders either as `.yaml` or `.properties` configuration files. 1. Create a folder with the name `config` under `/src/main/resources` project directory. 2. Create a configuration file with the name `configuration.yaml` inside the newly created config folder. 3. Migrate property placeholders from `.properties` to `.yaml` format. configuration.properties http.host=0.0.0.0 http.port=8081 mysql.password=pa$$w0rd mysql.port=3306 mysql.user=admin mysql.database=products mysql.host=corp.services.com autodiscovery.api.version=1.0.0:1762946 autodiscovery.api.name=groupId:com.mulesoft.retailer.manufacturingit.apis:assetId:product-api-database anypoint.platform.client\_id=1f702j71hu9z2x88v9vd19v7h248s589 anypoint.platform.client\_secret=87v8V47668701Dd574B0531255d6287d configuration.yaml http: host: "0.0.0.0" port: "8081" mysql: password: "pa$$w0rd" port: "3306" user: "admin" database: "products" host: "corp.services.com" autodiscovery: api: name: "groupId:com.mulesoft.retailer.manufacturingit.apis:assetId:product-api-database" version: "1.0.0:1762946" anypoint: platform: client\_id: "1f702j71hu9z2x88v9vd19v7h248s589" client\_secret: "87v8V47668701Dd574B0531255d6287d" 4. Replace the standard Spring element `` with the new Global Element `configuration-properties`. Configuration XML for Property Placeholders in Studio 6. ```xml ``` The `file` attribute points to the new configuration file in YAML format located under `/src/main/resources/config` folder. Configuration XML for Property Placeholders in Studio 7. ```xml ``` ## [](#migrating-global-http-listener-configuration)Migrating Global HTTP Listener Configuration Configuration XML for Global HTTP Listener Configuration in Studio 6. ```xml ``` The minimal configuration requires specifying `host` and `port` in the inner `http:listener-connection` element. We use the placeholders defined in the previous step. Configuration XML for Global HTTP Listener Configuration in Studio 7. ```xml ``` ## [](#migrating-mysql-global-configuration)Migrating MySQL Global Configuration The database connector facilitates setting up _Derby_, _MySQL_ and _Oracle_ databases for use in a Mule app. 1. In the Mule Palette, click `Add Module` and select `Database Connector` among the available modules. 2. Add a `Database Config` Global Configuration Element. 3. In Database Config > Connection, select MySQL Connection. 4. In MySQL JDBC Driver, click Add Dependency and configure the Maven information for the driver. mysql mysql-connector-java 5.1.6 5. Complete MySQL Global Configuration with `host`, `port`, `user`, `password` and `database` using previously defined placeholders. Configuration XML for MySQL Global Configuration in Studio 6. ```xml ``` Configuration XML for MySQL Global Configuration in Studio 7. ```xml ``` ## [](#migrating-api-autodiscovery-configuration)Migrating API Autodiscovery Configuration The `api-platform-gw` global element is required for registering an API in Anypoint Platform. Configuration XML for API Autodiscovery Configuration in Studio 6. ```xml ``` In Mule Runtime 4.x, the `apiName`, `version`, and `create` attributes were removed. Just the `apiId` and `flowRef` attributes are required. `apiId` is generated by API Manager and visible on the API instance dashboard. For API Autodiscovery Configuration in Mule Runtime 4.x: 1. Add the following Namespace, Schema `global.xml` Configuration file. xmlns:api-gateway="http://www.mulesoft.org/schema/mule/api-gateway" http://www.mulesoft.org/schema/mule/api-gateway http://www.mulesoft.org/schema/mule/api-gateway/current/mule-api-gateway.xsd 2. Add the required Autodiscovery Dependency Information to project `pom.xml` file. com.mulesoft.anypoint mule-module-autodiscovery 4.0.0 Configuration XML for API Autodiscovery Configuration in Studio 7. ```xml ``` ## [](#migrating-global-validation-configuration)Migrating Global Validation Configuration Configuration XML for Global Validation Configuration in Studio 6. ```xml ``` Opposite to Mule Runtime 3.x, adding the Validation Module to the Mule Palette is required to proceed with the configuration. 1. In the Mule Palette, click `Add Module` and select `Validation Module` among the available modules. 2. Add a `Validation Config` Global Configuration Element. Configuration XML for Global Validation Configuration in Studio 7. ```xml ``` ## [](#migrating-get-products-flow)Migrating _get-products-flow_ `get-products-flow` returns products from the database filtering by `Product Category` and/or `Product Name` also supporting paginated queries with `offset` and `maxResults` parameters. ![get-products-flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-get-products-flow.png) Figure 1. get-products-flow in Studio 6 Configuration XML for get-products-flow in Studio 6. ```xml ``` 1. There are no changes regarding `get-products-flow` definition. ```xml ``` 2. Create a package with the name `variables` under `src/main/resources` folder. 3. Create the file `set-queryCategory-variable.dwl` under `src/main/resources/variables` folder and write a DW script for setting `queryCategory` flow variable. %dw 2.0 output application/java var queryCategory = attributes.queryParams.category --- if (queryCategory != null) queryCategory else '%%' 4. Create the file `set-queryLimit-variable.dwl` under `src/main/resources/variables` folder and write a DW script for setting `queryLimit` flow variable. %dw 2.0 output application/java --- attributes.queryParams.maxResults as Number 5. Create the file `set-queryName-variable.dwl` under `src/main/resources/variables` folder and write a DW script for setting `queryName` flow variable. %dw 2.0 output application/java var queryName = attributes.queryParams.name --- if (queryName != null) queryName else '%%' 6. Create the file `set-queryOffset-variable.dwl` under `src/main/resources/variables` folder and write a DW script for setting `queryOffset` flow variable. %dw 2.0 output application/java --- attributes.queryParams.offset as Number 7. Add a `Transform component` to replace the logic inside `message-properties-transformer` and set the variables `queryOffset`, `queryLimit`, `queryName` and `queryCategory` referencing to its DW script. ```xml ``` 8. Add a `db:select` element, referencing the MySQL Global Configuration. Use the colon (:) syntax in parametrized queries. Parameters must be supplied as key-value pairs into the `db:input-parameters` element. ```xml SELECT p.id, p.name, p.description, p.product_number, p.manufactured, p.colors, p.categories, p.stock, p.safety_stock_level, p.standard_cost, p.list_price, p.size, p.size_unit_measure_code, p.weight, p.weight_unit_measure_code, p.days_to_manufacture, p.images, p.modified_date, p.created_date FROM product p WHERE LOWER(p.name) like :name AND LOWER(p.categories) like :category LIMIT :limit OFFSET :offset ``` 9. Create a package with the name `mappings` under `src/main/resources` folder. 10. Create the file `get-products-response.dwl` under `src/main/resources/mappings` folder. 11. Migrate `get-products-response.dwl` DW 1.0 script to DW 2.0. Transformation for get-products-response in DW 1.0. %dw 1.0 %output application/json --- payload map { id: $.id, categories: ($.categories default "") splitBy ",", colors: ($.colors default "") splitBy ",", images: ($.images default "") splitBy ",", createdDate: $.created\_date as :string {format: "yyyy-MM-dd"}, modifiedDate: $.modified\_date as :string {format: "yyyy-MM-dd"}, safetyStockLevel: $.safety\_stock\_level as :number, stock: $.stock as :number, daysToManufacture: $.days\_to\_manufacture, name: $.name, description: $.description, listPrice: $.list\_price, manufactured: $.manufactured, productNumber: $.product\_number, size: $.size, sizeUnitMeasureCode: $.size\_unit\_measure\_code, standardCost: $.standard\_cost, weightUnitMeasureCode: $.weight\_unit\_measure\_code, weight: $.weight } Transformation for get-products-response in DW 2.0. %dw 2.0 output application/json --- payload map { id: $.id, categories: ($.categories default "") splitBy ",", colors: ($.colors default "") splitBy ",", images: ($.images default "") splitBy ",", createdDate: $.created\_date as String {format: "yyyy-MM-dd"}, modifiedDate: $.modified\_date as String {format: "yyyy-MM-dd"}, safetyStockLevel: $.safety\_stock\_level as Number, stock: $.stock as Number, daysToManufacture: $.days\_to\_manufacture, name: $.name, description: $.description, listPrice: $.list\_price, manufactured: $.manufactured, productNumber: $.product\_number, size: $.size, sizeUnitMeasureCode: $.size\_unit\_measure\_code, standardCost: $.standard\_cost, weightUnitMeasureCode: $.weight\_unit\_measure\_code, weight: $.weight } 12. Finally, add a `Transform component` that sets the payload using the DW 2.0 transformation. ```xml ``` Configuration XML for get-products-flow in Studio 7. ```xml SELECT p.id, p.name, p.description, p.product_number, p.manufactured, p.colors, p.categories, p.stock, p.safety_stock_level, p.standard_cost, p.list_price, p.size, p.size_unit_measure_code, p.weight, p.weight_unit_measure_code, p.days_to_manufacture, p.images, p.modified_date, p.created_date FROM product p WHERE LOWER(p.name) like :name AND LOWER(p.categories) like :category LIMIT :limit OFFSET :offset ``` ![get-products-flow in Studio 7](/mulesoft/current/en-us/mule-runtime/4.3/_images/m4-apikit-based-example-get-products-flow.png) Figure 2. get-products-flow in Studio 7 ## [](#migrating-get-product-by-id-flow)Migrating _get-product-by-id-flow_ `get-product-by-id-flow` returns a product from the database filtering by `id`. If there isn’t a product with the required id, an `HTTP 404 Not Found` error is returned. ![get-product-by-id-flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-get-product-by-id-flow.png) Figure 3. get-product-by-id-flow in Studio 6 Configuration XML for get-product-by-id-flow in Studio 6. ```xml ``` 1. There are no changes regarding `get-product-by-id-flow` definition. ```xml ``` 2. Create `set-productId-variable.dwl` under `src/main/resources/variables` folder. Add the following logic for getting the `id` from `uriParams`. %dw 2.0 output application/java --- attributes.uriParams.id 3. Add a `Transform component` that references the DW script that sets a variable with the `productId` value received as a `URI parameter`. ```xml ``` 4. Add a `db:select` element, referencing the MySQL Global Configuration. Use the colon (:) syntax in parametrized queries. Parameters must be supplied as key-value pairs into the `db:input-parameters` element. ```xml SELECT p.id, p.name, p.description, p.product_number, p.manufactured, p.colors, p.categories, p.stock, p.safety_stock_level, p.standard_cost, p.list_price, p.size, p.size_unit_measure_code, p.weight, p.weight_unit_measure_code, p.days_to_manufacture, p.images, p.modified_date, p.created_date FROM product p where p.id = :id ``` 5. Add a `validation:is-true` element after the `db:select` that checks if the query has returned results. If not, throw an `APP:NOT_FOUND` error. Notice that as `MEL` has been replaced by `DataWeave` as the default expression language, `[payload.size() > 0]` is rewritten as `[sizeOf(payload) > 0]`. ```xml ``` 6. Create `get-product-by-id-response.dwl` file under `src/main/resources/mappings` folder and migrate DataWeave script for building JSON response from 1.0 to 2.0. Transformation for get-product-by-id-response in DW 1.0. %dw 1.0 %output application/json %var product = payload\[0\] --- { id: product.id, name: product.name, description: product.description, manufactured: product.manufactured, productNumber: product.product\_number, colors: (product.colors default "") splitBy "," , categories:(product.categories default "") splitBy "," , safetyStockLevel: product.safety\_socket\_level, standardCost: (product.standard\_cost default "0.0") as :string {format: "##.##"} as :number, listPrice: (product.list\_price default "0.0") as :string {format: "##.##"} as :number, stock: product.stock, safetyStockLevel: product.safety\_stock\_level, daysToManufacture: product.days\_to\_manufacture, size: product.size, sizeUnitMeasureCode: product.size\_unit\_measure\_code, weight: product.weight, weightUnitMeasureCode: product.weight\_unit\_measure\_code, daysToManufacture: product.days\_to\_manufacture, images: (product.images splitBy "," default null), modifiedDate: (product.modified\_date default "") as :date {format: "yyyy-MM-dd"}, createdDate: (product.created\_date default "") as :date {format: "yyyy-MM-dd"} } Transformation for get-product-by-id-response.dwl in DW 2.0. %dw 2.0 output application/json var product = payload\[0\] --- { id: product.id, name: product.name, description: product.description, manufactured: product.manufactured, productNumber: product.product\_number, colors: (product.colors default "") splitBy "," , categories:(product.categories default "") splitBy "," , safetyStockLevel: product.safety\_socket\_level, standardCost: (product.standard\_cost default "0.0") as String {format: "##.##"} as Number, listPrice: (product.list\_price default "0.0") as String {format: "##.##"} as Number, stock: product.stock, safetyStockLevel: product.safety\_stock\_level, daysToManufacture: product.days\_to\_manufacture, size: product.size, sizeUnitMeasureCode: product.size\_unit\_measure\_code, weight: product.weight, weightUnitMeasureCode: product.weight\_unit\_measure\_code, daysToManufacture: product.days\_to\_manufacture, images: (product.images splitBy "," default null), modifiedDate: (product.modified\_date default "") as Date {format: "yyyy-MM-dd"}, createdDate: (product.created\_date default "") as Date {format: "yyyy-MM-dd"} } 7. Finally, add a `Transform component` that sets the payload using the DW 2.0 transformation. ```xml ``` Configuration XML for get-product-by-id-flow in Studio 7. ```xml SELECT p.id, p.name, p.description, p.product_number, p.manufactured, p.colors, p.categories, p.stock, p.safety_stock_level, p.standard_cost, p.list_price, p.size, p.size_unit_measure_code, p.weight, p.weight_unit_measure_code, p.days_to_manufacture, p.images, p.modified_date, p.created_date FROM product p where p.id = :id ``` ![get-product-by-id-flow in Studio 7](/mulesoft/current/en-us/mule-runtime/4.3/_images/m4-apikit-based-example-get-product-by-id-flow.png) Figure 4. get-product-by-id-flow in Studio 7 ## [](#migrating-post-product-flow)Migrating _post-product-flow_ `post-product-flow` inserts a product in the database. ![post-product-flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-post-product-flow.png) Figure 5. post-product-flow in Studio 6 Configuration XML for post-product-flow in Studio 6. ```xml ``` 1. There are no changes regarding `post-product-flow` definition. ```xml ``` 2. Create a `json-to-java.dwl` file into `src/main/resources/mappings` folder to transform the JSON request into a JAVA map. %dw 2.0 output application/java --- payload 3. Create a `json-product-to-java.dwl` file into `src/main/resources/mappings` and migrate the original script from DW 1.0 to 2.0. Transformation for json-product-to-java.dwl in DW 1.0. %dw 1.0 %output application/java --- { categories: payload.categories joinBy ",", colors: payload.colors joinBy ",", daysToManufacture: payload.daysToManufacture, description: payload.description, images: payload.images joinBy ",", listPrice: payload.listPrice, (manufactured: 1) when payload.manufactured == true, (manufactured: 0) when payload.manufactured == false, name: payload.name, productNumber: payload.productNumber, safetyStockLevel: payload.safetyStockLevel, size: payload.size, sizeUnitMeasureCode: payload.sizeUnitMeasureCode, standardCost: payload.standardCost, stock: payload.stock, weight: payload.weight, weightUnitMeasureCode: payload.weightUnitMeasureCode } Transformation for json-product-to-java.dwl in DW 2.0. %dw 2.0 output application/java fun getManufacturedCode(value) = if (value == true) 1 else 0 --- { categories: payload.categories joinBy ",", colors: payload.colors joinBy ",", daysToManufacture: payload.daysToManufacture, description: payload.description, images: payload.images joinBy ",", listPrice: payload.listPrice, manufactured: getManufacturedCode(payload.manufactured), name: payload.name, productNumber: payload.productNumber, safetyStockLevel: payload.safetyStockLevel, size: payload.size, sizeUnitMeasureCode: payload.sizeUnitMeasureCode, standardCost: payload.standardCost, stock: payload.stock, weight: payload.weight, weightUnitMeasureCode: payload.weightUnitMeasureCode } 4. Add a `Transform component` that sets `originalPayload` and `newPayload` using the previously created DataWeave transformations. ```xml ``` 5. For configuring the details of the transaction, replace the Mule 3.x `transactional` scope with the new `try` scope and set the `transactionalAction` attribute to `ALWAYS_BEGIN`. ```xml ``` 6. Add a `db:insert` element into the `Try scope`, referencing the MySQL Global Configuration. Parameters must be supplied as key-value pairs into the `db:input-parameters` element. Notice also the inclusion of `db:auto-generated-keys-column-name` tag for setting the payload with the `ID` that was auto-generated by the Database engine. ```xml insert into product(name, description, product_number, manufactured, colors, categories, stock, safety_stock_level, standard_cost, list_price, size, size_unit_measure_code, weight, weight_unit_measure_code, days_to_manufacture, images, modified_date, created_date) values(:name, :description, :product_number, :manufactured, :colors, :categories, :stock, :safety_stock_level, :standard_cost, :list_price, :size, :size_unit_measure_code, :weight, :weight_unit_measure_code, :days_to_manufacture, :images, CURDATE(), CURDATE()); ``` 7. Create a `post-product-response.dwl` file under `src/main/resources/mappings` and migrate the response transformation from DataWeave 1.0 to 2.0. Notice the difference getting the generated `id` from the payload with the expression `payload.generatedKeys.GENERATED_KEY`. Transformation for post-product-response.dwl in DW 1.0. %dw 1.0 %output application/json --- flowVars.originalPayload ++ id: payload\[0\].GENERATED\_KEY Transformation for post-product-response.dwl in DW 2.0. %dw 2.0 output application/json --- vars.originalPayload ++ id: payload.generatedKeys.GENERATED\_KEY 8. Add a `Transform component` and set the payload with the DataWeave script. ```xml ``` Configuration XML for post-product-flow in Studio 7. ```xml insert into product(name, description, product_number, manufactured, colors, categories, stock, safety_stock_level, standard_cost, list_price, size, size_unit_measure_code, weight, weight_unit_measure_code, days_to_manufacture, images, modified_date, created_date) values(:name, :description, :product_number, :manufactured, :colors, :categories, :stock, :safety_stock_level, :standard_cost, :list_price, :size, :size_unit_measure_code, :weight, :weight_unit_measure_code, :days_to_manufacture, :images, CURDATE(), CURDATE()); ``` ![post-product-flow in Studio 7](/mulesoft/current/en-us/mule-runtime/4.3/_images/m4-apikit-based-example-post-product-flow.png) Figure 6. post-product-flow in Studio 7 ## [](#migrating-put-product-flow)Migrating _put-product-flow_ `put-product-flow` updates a product in the database based on the specified `id`. ![put-product-flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-put-product-flow.png) Figure 7. put-product-flow in Studio 6 Configuration XML for put-product-flow in Studio 6. ```xml ``` 1. There are no changes regarding `put-product-flow` definition. ```xml ``` 2. Create a `put-json-product-to-java.dwl` file under `src/main/resources/mappings` folder and migrate the original script from DW 1.0 to 2.0. Transformation for put-json-product-to-java.dwl in DW 1.0. %dw 1.0 %output application/java --- { categories: payload.categories joinBy ",", colors: payload.colors joinBy ",", daysToManufacture: payload.daysToManufacture, description: payload.description, images: payload.images joinBy ",", listPrice: payload.listPrice, manufactured: payload.manufactured, name: payload.name, productNumber: payload.productNumber, safetyStockLevel: payload.safetyStockLevel, size: payload.size, sizeUnitMeasureCode: payload.sizeUnitMeasureCode, standardCost: payload.standardCost, stock: payload.stock, weight: payload.weight, weightUnitMeasureCode: payload.weightUnitMeasureCode } Transformation for put-json-product-to-java.dwl in DW 2.0. %dw 2.0 output application/java --- { categories: payload.categories joinBy ",", colors: payload.colors joinBy ",", daysToManufacture: payload.daysToManufacture, description: payload.description, images: payload.images joinBy ",", listPrice: payload.listPrice, manufactured: payload.manufactured, name: payload.name, productNumber: payload.productNumber, safetyStockLevel: payload.safetyStockLevel, size: payload.size, sizeUnitMeasureCode: payload.sizeUnitMeasureCode, standardCost: payload.standardCost, stock: payload.stock, weight: payload.weight, weightUnitMeasureCode: payload.weightUnitMeasureCode } 3. Add a `Transform component` that sets `updatePayload` using the previously created DataWeave transformation and `id` with `variables/set-productId-variable.dwl` script. ```xml ``` 4. For configuring the details of the transaction, replace the Mule 3.x `transactional` scope with the new `try` scope and set the `transactionalAction` attribute to `ALWAYS_BEGIN`. ```xml ``` 5. Add a `db:update` element into the `Try scope`, referencing the MySQL Global Configuration. Parameters must be supplied as key-value pairs into the `db:input-parameters` element. ```xml update product set name = :name, description = :description, product_number = :product_number, manufactured = :manufactured, colors = :colors, categories= :categories, stock = :stock, safety_stock_level = :safety_stock_level, standard_cost = :standard_cost, list_price = :list_price, size = :size, size_unit_measure_code = :size_unit_measure_code, weight = :weight, weight_unit_measure_code = :weight_unit_measure_code, days_to_manufacture = :days_to_manufacture, images = :images, modified_date = CURDATE() where id = :id ``` 6. Add a `Transform component` and set the `httpStatus` variable with `204` using `set-httpStatus-with-204.dwl` file into `src/main/resources/variables`. ```xml ``` Configuration XML for put-product-flow in Studio 7. ```xml update product set name = :name, description = :description, product_number = :product_number, manufactured = :manufactured, colors = :colors, categories= :categories, stock = :stock, safety_stock_level = :safety_stock_level, standard_cost = :standard_cost, list_price = :list_price, size = :size, size_unit_measure_code = :size_unit_measure_code, weight = :weight, weight_unit_measure_code = :weight_unit_measure_code, days_to_manufacture = :days_to_manufacture, images = :images, modified_date = CURDATE() where id = :id ``` ![put-product-flow in Studio 7](/mulesoft/current/en-us/mule-runtime/4.3/_images/m4-apikit-based-example-put-product-flow.png) Figure 8. put-product-flow in Studio 7 ## [](#migrating-delete-product-flow)Migrating _delete-product-flow_ `delete-product-flow` deletes the product record from the MySQL database with the `id` specified as a `URI parameter` returning an HTTP 204 status code. ![delete-product-flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.3/_images/m3-apikit-based-example-delete-product-flow.png) Figure 9. delete-product-flow in Studio 6 Configuration XML for delete-product-flow in Studio 6. ```xml ``` 1. There are no changes regarding `delete-product-flow` definition. ```xml ``` 2. Add a `Transform component` that references the DW script that sets a variable with the `productId` value received as a `URI parameter`. ```xml ``` 3. For configuring the details of the transaction, replace the Mule 3.x `transactional` scope with the new `try` scope and set the `transactionalAction` attribute to `ALWAYS_BEGIN`. ```xml ``` 4. Add a `db:delete` element into the `Try scope`, referencing the MySQL Global Configuration. Parameters must be supplied as key-value pairs into the `db:input-parameters` element. Opposite to Mule 3.x, the previously defined `productId` flow variable must be accessed as `vars.productId` instead of `flowVars.productId`. ```xml delete from product where id=:productId ``` 5. Create a `set-httpStatus-with-204.dwl` file under `src/main/resources/variables` as follows. %dw 2.0 output application/java --- 204 6. Set `httpStatus` variable with the value `204` using a `Transform Component` for defining a `NO CONTENT` response code. ```xml ``` To return a specific HTTP Status code, instead of setting a `http.status` property, APIkit in Mule 4 requires setting a variable with the name `httpStatus`. Configuration XML for delete-product-flow in Studio 7. ```xml delete from product where id=:productId ``` ![delete-product-flow in Studio 7](/mulesoft/current/en-us/mule-runtime/4.3/_images/m4-apikit-based-example-delete-product-flow.png) Figure 10. delete-product-flow in Studio 7 ## [](#migrating-backend-flows)Migrating Backend Flows To migrate backend flows: For each Backend Flow generated by APIkit, add a `flow-ref` to its implementation. \+ .Configuration XML for Backend Flows in Studio 6. ```xml ``` + \+ .Configuration XML for Backend Flows in Studio 7. ```xml ``` ## [](#extending-default-apikit-global-exception-strategies)Extending default APIkit Global Exception Strategies 1. Add `APP:NOT_FOUND` exception type to the ApiKit-generated 404 mapping to handle the exception thrown by the `validation:is-true` element in `get-product-by-id-flow`. You can repeat this process for any other errors you want to map to a specific status code. Configuration XML for ApiKit Mapping 404 in Studio 6. ```xml ``` Configuration XML for ApiKit Mapping 404 in Studio 7. ```xml ``` 2. Add a Generic ApiKit Mapping 500 for all the non previously managed exceptions. Configuration XML for Generic ApiKit Mapping 500 in Studio 6. ```xml ``` Configuration XML for Generic ApiKit Mapping 500 in Studio 7. ```xml ``` # Migrating an APIkit-based Application This example covers the necessary steps for successfully migrate an APIkit-based application from Mule 3 to Mule 4. The following REST API performs CRUD (create, read, update and delete) operations over a MySQL database. ![api-main in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-main.png) ![api-console in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-console.png) ![get:/product:api-config flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-get-products.png) ![get:/product/{id}:api-config flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-get-product-id.png) ![post:/product:application/json:api-config flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-post-product.png) ![delete:/product/{id}:api-config flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-delete-product.png) ![put:/product/{id}:application/json:api-config flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-put-product.png) ![api-apiKitGlobalExceptionMapping flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-globalexceptionmapping.png) ## [](#migrating-property-placeholders)Migrating Property Placeholders Mule 4 supports property placeholders either as `.yaml` or `.properties` configuration files. 1. Create a folder with the name `config` under `/src/main/resources` project directory. 2. Create a configuration file with the name `configuration.yaml` inside the newly created config folder. 3. Migrate property placeholders from `.properties` to `.yaml` format. configuration.properties http.host=0.0.0.0 http.port=8081 mysql.password=pa$$w0rd mysql.port=3306 mysql.user=admin mysql.database=products mysql.host=corp.services.com autodiscovery.api.version=1.0.0:1762946 autodiscovery.api.name=groupId:com.mulesoft.retailer.manufacturingit.apis:assetId:product-api-database anypoint.platform.client\_id=1f702j71hu9z2x88v9vd19v7h248s589 anypoint.platform.client\_secret=87v8V47668701Dd574B0531255d6287d configuration.yaml http: host: "0.0.0.0" port: "8081" mysql: password: "pa$$w0rd" port: "3306" user: "admin" database: "products" host: "corp.services.com" autodiscovery: api: name: "groupId:com.mulesoft.retailer.manufacturingit.apis:assetId:product-api-database" version: "1.0.0:1762946" anypoint: platform: client\_id: "1f702j71hu9z2x88v9vd19v7h248s589" client\_secret: "87v8V47668701Dd574B0531255d6287d" 4. Replace the standard Spring element `` with the new Global Element `configuration-properties`. Configuration XML for Property Placeholders in Studio 6. ```xml ``` The `file` attribute points to the new configuration file in YAML format located under `/src/main/resources/config` folder. Configuration XML for Property Placeholders in Studio 7. ```xml ``` ## [](#migrating-global-http-listener-configuration)Migrating Global HTTP Listener Configuration Configuration XML for Global HTTP Listener Configuration in Studio 6. ```xml ``` The minimal configuration requires specifying `host` and `port` in the inner `http:listener-connection` element. We use the placeholders defined in the previous step. Configuration XML for Global HTTP Listener Configuration in Studio 7. ```xml ``` ## [](#migrating-mysql-global-configuration)Migrating MySQL Global Configuration The database connector facilitates setting up _Derby_, _MySQL_ and _Oracle_ databases for use in a Mule app. 1. In the Mule Palette, click `Add Module` and select `Database Connector` among the available modules. 2. Add a `Database Config` Global Configuration Element. 3. In Database Config > Connection, select MySQL Connection. 4. In MySQL JDBC Driver, click Add Dependency and configure the Maven information for the driver. mysql mysql-connector-java 5.1.6 5. Complete MySQL Global Configuration with `host`, `port`, `user`, `password` and `database` using previously defined placeholders. Configuration XML for MySQL Global Configuration in Studio 6. ```xml ``` Configuration XML for MySQL Global Configuration in Studio 7. ```xml ``` ## [](#migrating-api-autodiscovery-configuration)Migrating API Autodiscovery Configuration The `api-platform-gw` global element is required for registering an API in Anypoint Platform. Configuration XML for API Autodiscovery Configuration in Studio 6. ```xml ``` In Mule Runtime 4.x, the `apiName`, `version`, and `create` attributes were removed. Just the `apiId` and `flowRef` attributes are required. `apiId` is generated by API Manager and visible on the API instance dashboard. For API Autodiscovery Configuration in Mule Runtime 4.x: 1. Add the following Namespace, Schema `global.xml` Configuration file. xmlns:api-gateway="http://www.mulesoft.org/schema/mule/api-gateway" http://www.mulesoft.org/schema/mule/api-gateway http://www.mulesoft.org/schema/mule/api-gateway/current/mule-api-gateway.xsd 2. Add the required Autodiscovery Dependency Information to project `pom.xml` file. com.mulesoft.anypoint mule-module-autodiscovery 4.0.0 Configuration XML for API Autodiscovery Configuration in Studio 7. ```xml ``` ## [](#migrating-global-validation-configuration)Migrating Global Validation Configuration Configuration XML for Global Validation Configuration in Studio 6. ```xml ``` Opposite to Mule Runtime 3.x, adding the Validation Module to the Mule Palette is required to proceed with the configuration. 1. In the Mule Palette, click `Add Module` and select `Validation Module` among the available modules. 2. Add a `Validation Config` Global Configuration Element. Configuration XML for Global Validation Configuration in Studio 7. ```xml ``` ## [](#migrating-get-products-flow)Migrating _get-products-flow_ `get-products-flow` returns products from the database filtering by `Product Category` and/or `Product Name` also supporting paginated queries with `offset` and `maxResults` parameters. ![get-products-flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-get-products-flow.png) Figure 1. get-products-flow in Studio 6 Configuration XML for get-products-flow in Studio 6. ```xml ``` 1. There are no changes regarding `get-products-flow` definition. ```xml ``` 2. Create a package with the name `variables` under `src/main/resources` folder. 3. Create the file `set-queryCategory-variable.dwl` under `src/main/resources/variables` folder and write a DW script for setting `queryCategory` flow variable. %dw 2.0 output application/java var queryCategory = attributes.queryParams.category --- if (queryCategory != null) queryCategory else '%%' 4. Create the file `set-queryLimit-variable.dwl` under `src/main/resources/variables` folder and write a DW script for setting `queryLimit` flow variable. %dw 2.0 output application/java --- attributes.queryParams.maxResults as Number 5. Create the file `set-queryName-variable.dwl` under `src/main/resources/variables` folder and write a DW script for setting `queryName` flow variable. %dw 2.0 output application/java var queryName = attributes.queryParams.name --- if (queryName != null) queryName else '%%' 6. Create the file `set-queryOffset-variable.dwl` under `src/main/resources/variables` folder and write a DW script for setting `queryOffset` flow variable. %dw 2.0 output application/java --- attributes.queryParams.offset as Number 7. Add a `Transform component` to replace the logic inside `message-properties-transformer` and set the variables `queryOffset`, `queryLimit`, `queryName` and `queryCategory` referencing to its DW script. ```xml ``` 8. Add a `db:select` element, referencing the MySQL Global Configuration. Use the colon (:) syntax in parametrized queries. Parameters must be supplied as key-value pairs into the `db:input-parameters` element. ```xml SELECT p.id, p.name, p.description, p.product_number, p.manufactured, p.colors, p.categories, p.stock, p.safety_stock_level, p.standard_cost, p.list_price, p.size, p.size_unit_measure_code, p.weight, p.weight_unit_measure_code, p.days_to_manufacture, p.images, p.modified_date, p.created_date FROM product p WHERE LOWER(p.name) like :name AND LOWER(p.categories) like :category LIMIT :limit OFFSET :offset ``` 9. Create a package with the name `mappings` under `src/main/resources` folder. 10. Create the file `get-products-response.dwl` under `src/main/resources/mappings` folder. 11. Migrate `get-products-response.dwl` DW 1.0 script to DW 2.0. Transformation for get-products-response in DW 1.0. %dw 1.0 %output application/json --- payload map { id: $.id, categories: ($.categories default "") splitBy ",", colors: ($.colors default "") splitBy ",", images: ($.images default "") splitBy ",", createdDate: $.created\_date as :string {format: "yyyy-MM-dd"}, modifiedDate: $.modified\_date as :string {format: "yyyy-MM-dd"}, safetyStockLevel: $.safety\_stock\_level as :number, stock: $.stock as :number, daysToManufacture: $.days\_to\_manufacture, name: $.name, description: $.description, listPrice: $.list\_price, manufactured: $.manufactured, productNumber: $.product\_number, size: $.size, sizeUnitMeasureCode: $.size\_unit\_measure\_code, standardCost: $.standard\_cost, weightUnitMeasureCode: $.weight\_unit\_measure\_code, weight: $.weight } Transformation for get-products-response in DW 2.0. %dw 2.0 output application/json --- payload map { id: $.id, categories: ($.categories default "") splitBy ",", colors: ($.colors default "") splitBy ",", images: ($.images default "") splitBy ",", createdDate: $.created\_date as String {format: "yyyy-MM-dd"}, modifiedDate: $.modified\_date as String {format: "yyyy-MM-dd"}, safetyStockLevel: $.safety\_stock\_level as Number, stock: $.stock as Number, daysToManufacture: $.days\_to\_manufacture, name: $.name, description: $.description, listPrice: $.list\_price, manufactured: $.manufactured, productNumber: $.product\_number, size: $.size, sizeUnitMeasureCode: $.size\_unit\_measure\_code, standardCost: $.standard\_cost, weightUnitMeasureCode: $.weight\_unit\_measure\_code, weight: $.weight } 12. Finally, add a `Transform component` that sets the payload using the DW 2.0 transformation. ```xml ``` Configuration XML for get-products-flow in Studio 7. ```xml SELECT p.id, p.name, p.description, p.product_number, p.manufactured, p.colors, p.categories, p.stock, p.safety_stock_level, p.standard_cost, p.list_price, p.size, p.size_unit_measure_code, p.weight, p.weight_unit_measure_code, p.days_to_manufacture, p.images, p.modified_date, p.created_date FROM product p WHERE LOWER(p.name) like :name AND LOWER(p.categories) like :category LIMIT :limit OFFSET :offset ``` ![get-products-flow in Studio 7](/mulesoft/current/en-us/mule-runtime/4.4/_images/m4-apikit-based-example-get-products-flow.png) Figure 2. get-products-flow in Studio 7 ## [](#migrating-get-product-by-id-flow)Migrating _get-product-by-id-flow_ `get-product-by-id-flow` returns a product from the database filtering by `id`. If there isn’t a product with the required id, an `HTTP 404 Not Found` error is returned. ![get-product-by-id-flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-get-product-by-id-flow.png) Figure 3. get-product-by-id-flow in Studio 6 Configuration XML for get-product-by-id-flow in Studio 6. ```xml ``` 1. There are no changes regarding `get-product-by-id-flow` definition. ```xml ``` 2. Create `set-productId-variable.dwl` under `src/main/resources/variables` folder. Add the following logic for getting the `id` from `uriParams`. %dw 2.0 output application/java --- attributes.uriParams.id 3. Add a `Transform component` that references the DW script that sets a variable with the `productId` value received as a `URI parameter`. ```xml ``` 4. Add a `db:select` element, referencing the MySQL Global Configuration. Use the colon (:) syntax in parametrized queries. Parameters must be supplied as key-value pairs into the `db:input-parameters` element. ```xml SELECT p.id, p.name, p.description, p.product_number, p.manufactured, p.colors, p.categories, p.stock, p.safety_stock_level, p.standard_cost, p.list_price, p.size, p.size_unit_measure_code, p.weight, p.weight_unit_measure_code, p.days_to_manufacture, p.images, p.modified_date, p.created_date FROM product p where p.id = :id ``` 5. Add a `validation:is-true` element after the `db:select` that checks if the query has returned results. If not, throw an `APP:NOT_FOUND` error. Notice that as `MEL` has been replaced by `DataWeave` as the default expression language, `[payload.size() > 0]` is rewritten as `[sizeOf(payload) > 0]`. ```xml ``` 6. Create `get-product-by-id-response.dwl` file under `src/main/resources/mappings` folder and migrate DataWeave script for building JSON response from 1.0 to 2.0. Transformation for get-product-by-id-response in DW 1.0. %dw 1.0 %output application/json %var product = payload\[0\] --- { id: product.id, name: product.name, description: product.description, manufactured: product.manufactured, productNumber: product.product\_number, colors: (product.colors default "") splitBy "," , categories:(product.categories default "") splitBy "," , safetyStockLevel: product.safety\_socket\_level, standardCost: (product.standard\_cost default "0.0") as :string {format: "##.##"} as :number, listPrice: (product.list\_price default "0.0") as :string {format: "##.##"} as :number, stock: product.stock, safetyStockLevel: product.safety\_stock\_level, daysToManufacture: product.days\_to\_manufacture, size: product.size, sizeUnitMeasureCode: product.size\_unit\_measure\_code, weight: product.weight, weightUnitMeasureCode: product.weight\_unit\_measure\_code, daysToManufacture: product.days\_to\_manufacture, images: (product.images splitBy "," default null), modifiedDate: (product.modified\_date default "") as :date {format: "yyyy-MM-dd"}, createdDate: (product.created\_date default "") as :date {format: "yyyy-MM-dd"} } Transformation for get-product-by-id-response.dwl in DW 2.0. %dw 2.0 output application/json var product = payload\[0\] --- { id: product.id, name: product.name, description: product.description, manufactured: product.manufactured, productNumber: product.product\_number, colors: (product.colors default "") splitBy "," , categories:(product.categories default "") splitBy "," , safetyStockLevel: product.safety\_socket\_level, standardCost: (product.standard\_cost default "0.0") as String {format: "##.##"} as Number, listPrice: (product.list\_price default "0.0") as String {format: "##.##"} as Number, stock: product.stock, safetyStockLevel: product.safety\_stock\_level, daysToManufacture: product.days\_to\_manufacture, size: product.size, sizeUnitMeasureCode: product.size\_unit\_measure\_code, weight: product.weight, weightUnitMeasureCode: product.weight\_unit\_measure\_code, daysToManufacture: product.days\_to\_manufacture, images: (product.images splitBy "," default null), modifiedDate: (product.modified\_date default "") as Date {format: "yyyy-MM-dd"}, createdDate: (product.created\_date default "") as Date {format: "yyyy-MM-dd"} } 7. Finally, add a `Transform component` that sets the payload using the DW 2.0 transformation. ```xml ``` Configuration XML for get-product-by-id-flow in Studio 7. ```xml SELECT p.id, p.name, p.description, p.product_number, p.manufactured, p.colors, p.categories, p.stock, p.safety_stock_level, p.standard_cost, p.list_price, p.size, p.size_unit_measure_code, p.weight, p.weight_unit_measure_code, p.days_to_manufacture, p.images, p.modified_date, p.created_date FROM product p where p.id = :id ``` ![get-product-by-id-flow in Studio 7](/mulesoft/current/en-us/mule-runtime/4.4/_images/m4-apikit-based-example-get-product-by-id-flow.png) Figure 4. get-product-by-id-flow in Studio 7 ## [](#migrating-post-product-flow)Migrating _post-product-flow_ `post-product-flow` inserts a product in the database. ![post-product-flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-post-product-flow.png) Figure 5. post-product-flow in Studio 6 Configuration XML for post-product-flow in Studio 6. ```xml ``` 1. There are no changes regarding `post-product-flow` definition. ```xml ``` 2. Create a `json-to-java.dwl` file into `src/main/resources/mappings` folder to transform the JSON request into a JAVA map. %dw 2.0 output application/java --- payload 3. Create a `json-product-to-java.dwl` file into `src/main/resources/mappings` and migrate the original script from DW 1.0 to 2.0. Transformation for json-product-to-java.dwl in DW 1.0. %dw 1.0 %output application/java --- { categories: payload.categories joinBy ",", colors: payload.colors joinBy ",", daysToManufacture: payload.daysToManufacture, description: payload.description, images: payload.images joinBy ",", listPrice: payload.listPrice, (manufactured: 1) when payload.manufactured == true, (manufactured: 0) when payload.manufactured == false, name: payload.name, productNumber: payload.productNumber, safetyStockLevel: payload.safetyStockLevel, size: payload.size, sizeUnitMeasureCode: payload.sizeUnitMeasureCode, standardCost: payload.standardCost, stock: payload.stock, weight: payload.weight, weightUnitMeasureCode: payload.weightUnitMeasureCode } Transformation for json-product-to-java.dwl in DW 2.0. %dw 2.0 output application/java fun getManufacturedCode(value) = if (value == true) 1 else 0 --- { categories: payload.categories joinBy ",", colors: payload.colors joinBy ",", daysToManufacture: payload.daysToManufacture, description: payload.description, images: payload.images joinBy ",", listPrice: payload.listPrice, manufactured: getManufacturedCode(payload.manufactured), name: payload.name, productNumber: payload.productNumber, safetyStockLevel: payload.safetyStockLevel, size: payload.size, sizeUnitMeasureCode: payload.sizeUnitMeasureCode, standardCost: payload.standardCost, stock: payload.stock, weight: payload.weight, weightUnitMeasureCode: payload.weightUnitMeasureCode } 4. Add a `Transform component` that sets `originalPayload` and `newPayload` using the previously created DataWeave transformations. ```xml ``` 5. For configuring the details of the transaction, replace the Mule 3.x `transactional` scope with the new `try` scope and set the `transactionalAction` attribute to `ALWAYS_BEGIN`. ```xml ``` 6. Add a `db:insert` element into the `Try scope`, referencing the MySQL Global Configuration. Parameters must be supplied as key-value pairs into the `db:input-parameters` element. Notice also the inclusion of `db:auto-generated-keys-column-name` tag for setting the payload with the `ID` that was auto-generated by the Database engine. ```xml insert into product(name, description, product_number, manufactured, colors, categories, stock, safety_stock_level, standard_cost, list_price, size, size_unit_measure_code, weight, weight_unit_measure_code, days_to_manufacture, images, modified_date, created_date) values(:name, :description, :product_number, :manufactured, :colors, :categories, :stock, :safety_stock_level, :standard_cost, :list_price, :size, :size_unit_measure_code, :weight, :weight_unit_measure_code, :days_to_manufacture, :images, CURDATE(), CURDATE()); ``` 7. Create a `post-product-response.dwl` file under `src/main/resources/mappings` and migrate the response transformation from DataWeave 1.0 to 2.0. Notice the difference getting the generated `id` from the payload with the expression `payload.generatedKeys.GENERATED_KEY`. Transformation for post-product-response.dwl in DW 1.0. %dw 1.0 %output application/json --- flowVars.originalPayload ++ id: payload\[0\].GENERATED\_KEY Transformation for post-product-response.dwl in DW 2.0. %dw 2.0 output application/json --- vars.originalPayload ++ id: payload.generatedKeys.GENERATED\_KEY 8. Add a `Transform component` and set the payload with the DataWeave script. ```xml ``` Configuration XML for post-product-flow in Studio 7. ```xml insert into product(name, description, product_number, manufactured, colors, categories, stock, safety_stock_level, standard_cost, list_price, size, size_unit_measure_code, weight, weight_unit_measure_code, days_to_manufacture, images, modified_date, created_date) values(:name, :description, :product_number, :manufactured, :colors, :categories, :stock, :safety_stock_level, :standard_cost, :list_price, :size, :size_unit_measure_code, :weight, :weight_unit_measure_code, :days_to_manufacture, :images, CURDATE(), CURDATE()); ``` ![post-product-flow in Studio 7](/mulesoft/current/en-us/mule-runtime/4.4/_images/m4-apikit-based-example-post-product-flow.png) Figure 6. post-product-flow in Studio 7 ## [](#migrating-put-product-flow)Migrating _put-product-flow_ `put-product-flow` updates a product in the database based on the specified `id`. ![put-product-flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-put-product-flow.png) Figure 7. put-product-flow in Studio 6 Configuration XML for put-product-flow in Studio 6. ```xml ``` 1. There are no changes regarding `put-product-flow` definition. ```xml ``` 2. Create a `put-json-product-to-java.dwl` file under `src/main/resources/mappings` folder and migrate the original script from DW 1.0 to 2.0. Transformation for put-json-product-to-java.dwl in DW 1.0. %dw 1.0 %output application/java --- { categories: payload.categories joinBy ",", colors: payload.colors joinBy ",", daysToManufacture: payload.daysToManufacture, description: payload.description, images: payload.images joinBy ",", listPrice: payload.listPrice, manufactured: payload.manufactured, name: payload.name, productNumber: payload.productNumber, safetyStockLevel: payload.safetyStockLevel, size: payload.size, sizeUnitMeasureCode: payload.sizeUnitMeasureCode, standardCost: payload.standardCost, stock: payload.stock, weight: payload.weight, weightUnitMeasureCode: payload.weightUnitMeasureCode } Transformation for put-json-product-to-java.dwl in DW 2.0. %dw 2.0 output application/java --- { categories: payload.categories joinBy ",", colors: payload.colors joinBy ",", daysToManufacture: payload.daysToManufacture, description: payload.description, images: payload.images joinBy ",", listPrice: payload.listPrice, manufactured: payload.manufactured, name: payload.name, productNumber: payload.productNumber, safetyStockLevel: payload.safetyStockLevel, size: payload.size, sizeUnitMeasureCode: payload.sizeUnitMeasureCode, standardCost: payload.standardCost, stock: payload.stock, weight: payload.weight, weightUnitMeasureCode: payload.weightUnitMeasureCode } 3. Add a `Transform component` that sets `updatePayload` using the previously created DataWeave transformation and `id` with `variables/set-productId-variable.dwl` script. ```xml ``` 4. For configuring the details of the transaction, replace the Mule 3.x `transactional` scope with the new `try` scope and set the `transactionalAction` attribute to `ALWAYS_BEGIN`. ```xml ``` 5. Add a `db:update` element into the `Try scope`, referencing the MySQL Global Configuration. Parameters must be supplied as key-value pairs into the `db:input-parameters` element. ```xml update product set name = :name, description = :description, product_number = :product_number, manufactured = :manufactured, colors = :colors, categories= :categories, stock = :stock, safety_stock_level = :safety_stock_level, standard_cost = :standard_cost, list_price = :list_price, size = :size, size_unit_measure_code = :size_unit_measure_code, weight = :weight, weight_unit_measure_code = :weight_unit_measure_code, days_to_manufacture = :days_to_manufacture, images = :images, modified_date = CURDATE() where id = :id ``` 6. Add a `Transform component` and set the `httpStatus` variable with `204` using `set-httpStatus-with-204.dwl` file into `src/main/resources/variables`. ```xml ``` Configuration XML for put-product-flow in Studio 7. ```xml update product set name = :name, description = :description, product_number = :product_number, manufactured = :manufactured, colors = :colors, categories= :categories, stock = :stock, safety_stock_level = :safety_stock_level, standard_cost = :standard_cost, list_price = :list_price, size = :size, size_unit_measure_code = :size_unit_measure_code, weight = :weight, weight_unit_measure_code = :weight_unit_measure_code, days_to_manufacture = :days_to_manufacture, images = :images, modified_date = CURDATE() where id = :id ``` ![put-product-flow in Studio 7](/mulesoft/current/en-us/mule-runtime/4.4/_images/m4-apikit-based-example-put-product-flow.png) Figure 8. put-product-flow in Studio 7 ## [](#migrating-delete-product-flow)Migrating _delete-product-flow_ `delete-product-flow` deletes the product record from the MySQL database with the `id` specified as a `URI parameter` returning an HTTP 204 status code. ![delete-product-flow in Studio 6](/mulesoft/current/en-us/mule-runtime/4.4/_images/m3-apikit-based-example-delete-product-flow.png) Figure 9. delete-product-flow in Studio 6 Configuration XML for delete-product-flow in Studio 6. ```xml ``` 1. There are no changes regarding `delete-product-flow` definition. ```xml ``` 2. Add a `Transform component` that references the DW script that sets a variable with the `productId` value received as a `URI parameter`. ```xml ``` 3. For configuring the details of the transaction, replace the Mule 3.x `transactional` scope with the new `try` scope and set the `transactionalAction` attribute to `ALWAYS_BEGIN`. ```xml ``` 4. Add a `db:delete` element into the `Try scope`, referencing the MySQL Global Configuration. Parameters must be supplied as key-value pairs into the `db:input-parameters` element. Opposite to Mule 3.x, the previously defined `productId` flow variable must be accessed as `vars.productId` instead of `flowVars.productId`. ```xml delete from product where id=:productId ``` 5. Create a `set-httpStatus-with-204.dwl` file under `src/main/resources/variables` as follows. %dw 2.0 output application/java --- 204 6. Set `httpStatus` variable with the value `204` using a `Transform Component` for defining a `NO CONTENT` response code. ```xml ``` To return a specific HTTP Status code, instead of setting a `http.status` property, APIkit in Mule 4 requires setting a variable with the name `httpStatus`. Configuration XML for delete-product-flow in Studio 7. ```xml delete from product where id=:productId ``` ![delete-product-flow in Studio 7](/mulesoft/current/en-us/mule-runtime/4.4/_images/m4-apikit-based-example-delete-product-flow.png) Figure 10. delete-product-flow in Studio 7 ## [](#migrating-backend-flows)Migrating Backend Flows To migrate backend flows: For each Backend Flow generated by APIkit, add a `flow-ref` to its implementation. \+ .Configuration XML for Backend Flows in Studio 6. ```xml ``` + \+ .Configuration XML for Backend Flows in Studio 7. ```xml ``` ## [](#extending-default-apikit-global-exception-strategies)Extending default APIkit Global Exception Strategies 1. Add `APP:NOT_FOUND` exception type to the ApiKit-generated 404 mapping to handle the exception thrown by the `validation:is-true` element in `get-product-by-id-flow`. You can repeat this process for any other errors you want to map to a specific status code. Configuration XML for ApiKit Mapping 404 in Studio 6. ```xml ``` Configuration XML for ApiKit Mapping 404 in Studio 7. ```xml ``` 2. Add a Generic ApiKit Mapping 500 for all the non previously managed exceptions. Configuration XML for Generic ApiKit Mapping 500 in Studio 6. ```xml ``` Configuration XML for Generic ApiKit Mapping 500 in Studio 7. ```xml ``` --- product: Mule Runtime version: 4.3 --- # Migrating API Gateways > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This section covers the migration of API Gateway related features. Following topics will be explained: - [Migrating API Gateways: Autodiscovery](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways-autodiscovery) - [Migrating Mule 3 Applications Managed in API Manager](https://docs.mulesoft.com/mule-runtime/4.3/migrate-mule3-apimanager) - [Migrating API Gateways: Policies](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways-policies) - [Migrating API Gateways: Proxies](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways-proxies) - [Migrating API Gateways: Mule Runtime Configuration](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways-runtime-config) ## See Also [Core Components Migration](https://docs.mulesoft.com/mule-runtime/4.3/migration-core) --- product: Mule Runtime version: 4.4 --- # Migrating API Gateways > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This section covers the migration of API Gateway related features. Following topics will be explained: - [Migrating API Gateways: Autodiscovery](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways-autodiscovery) - [Migrating Mule 3 Applications Managed in API Manager](https://docs.mulesoft.com/mule-runtime/4.4/migrate-mule3-apimanager) - [Migrating API Gateways: Policies](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways-policies) - [Migrating API Gateways: Proxies](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways-proxies) - [Migrating API Gateways: Mule Runtime Configuration](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways-runtime-config) ## See Also [Core Components Migration](https://docs.mulesoft.com/mule-runtime/4.4/migration-core) --- product: Mule Runtime version: 4.3 --- # Migrating API Gateways: Autodiscovery > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Autodiscovery element was updated after Mule 4 release. - APIs are referenced by an ID instead of a name and version. - Creation of APIs from the runtime is no longer possible. Simple Mule app with an HTTP listener and an Autodiscovery element defined: Mule 3 Example: All Configurable Attributes ```xml This is a test API tag1 tag2 ``` Mule 4 Example: All Configurable Attributes ```xml ``` ## See Also [Migrating API Gateways](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways) [Migrating API Gateways: Policies](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways-policies) [Migrating API Gateways: Mule Runtime Configuration](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways-runtime-config) --- product: Mule Runtime version: 4.4 --- # Migrating API Gateways: Autodiscovery > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Autodiscovery element was updated after Mule 4 release. - APIs are referenced by an ID instead of a name and version. - Creation of APIs from the runtime is no longer possible. Simple Mule app with an HTTP listener and an Autodiscovery element defined: Mule 3 Example: All Configurable Attributes ```xml This is a test API tag1 tag2 ``` Mule 4 Example: All Configurable Attributes ```xml ``` ## See Also [Migrating API Gateways](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways) [Migrating API Gateways: Policies](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways-policies) [Migrating API Gateways: Mule Runtime Configuration](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways-runtime-config) --- product: Mule Runtime version: 4.3 --- # Migrating API Gateways: Mule Runtime Configuration > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Configuration properties for API Gateway Runtime changed in Mule 4. These properties have to be defined in the `wrapper.conf` for Mule 3 to work as API Gateway: ```text -M-Danypoint.platform.client_id=clientId -M-Danypoint.platform.client_secret=clientSecret -M-Danypoint.platform.platform_base_uri=https://anypoint.mulesoft.com/apiplatform -M-Danypoint.platform.coreservice_base_uri=https://anypoint.mulesoft.com/accounts -M-Danypoint.platform.contracts_base_uri=https://anypoint.mulesoft.com/apigateway/ccs -M-Danypoint.platform.analytics_base_uri=https://analytics-ingest.anypoint.mulesoft.com ``` Starting from Mule 4, these properties have to be defined in the `wrapper.conf` in order to work as an API Gateway: ```text -M-Danypoint.platform.client_id=clientId -M-Danypoint.platform.client_secret=clientSecret -M-Danypoint.platform.base_uri=https://anypoint.mulesoft.com -M-Danypoint.platform.analytics_base_uri=https://analytics-ingest.anypoint.mulesoft.com ``` ## See Also [Migrating API Gateways](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways) [Migrating API Gateways: Autodiscovery](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways-autodiscovery) [Migrating API Gateways: Policies](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways-policies) --- product: Mule Runtime version: 4.4 --- # Migrating API Gateways: Mule Runtime Configuration > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Configuration properties for API Gateway Runtime changed in Mule 4. These properties have to be defined in the `wrapper.conf` for Mule 3 to work as API Gateway: ```text -M-Danypoint.platform.client_id=clientId -M-Danypoint.platform.client_secret=clientSecret -M-Danypoint.platform.platform_base_uri=https://anypoint.mulesoft.com/apiplatform -M-Danypoint.platform.coreservice_base_uri=https://anypoint.mulesoft.com/accounts -M-Danypoint.platform.contracts_base_uri=https://anypoint.mulesoft.com/apigateway/ccs -M-Danypoint.platform.analytics_base_uri=https://analytics-ingest.anypoint.mulesoft.com ``` Starting from Mule 4, these properties have to be defined in the `wrapper.conf` in order to work as an API Gateway: ```text -M-Danypoint.platform.client_id=clientId -M-Danypoint.platform.client_secret=clientSecret -M-Danypoint.platform.base_uri=https://anypoint.mulesoft.com -M-Danypoint.platform.analytics_base_uri=https://analytics-ingest.anypoint.mulesoft.com ``` ## See Also [Migrating API Gateways](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways) [Migrating API Gateways: Autodiscovery](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways-autodiscovery) [Migrating API Gateways: Policies](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways-policies) --- product: Mule Runtime version: 4.3 --- # Migrating API Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, policies underwent major changes. ## Defining Policy Behavior In 3.x, the logic inside a particular policy is split in two blocks, one that is executed before the next policy or flow, the other executed after it. Mule 3 Example ```xml ``` In Mule 4, policies are no longer separated in a `before` and `after` block. They now work as a flow with an explicit jump to the next policy or flow that has to be defined in it. Same behavior can be achieved in Mule 4 with the following config: Mule 4 Example ```xml ``` A few things to notice: - Logic is placed in the same block. Injecting behavior before the flow can be achieved just by putting logic before the `execute-next` element. To injecting behavior after the flow, you put logic after that element. - `propagateMessageTransformations` attribute in the `http-policy:source` element: Starting in Mule 4, changes to the Mule message (payload or attributes) before executing the flow are not propagated to it by default. To enable this, `propagateMessageTransformations` has to be set to `true`. - `pointcut` elements are no longer defined in the policy config file. Now, they are resolved by the API Gateway when policies are fetched from API Manager. Endpoint and App `pointcut` elements are no longer available, and there is no replacement to them. ## Uploading Policy Template to Exchange In 3.x, once the policy is defined, the result is an XML file that has to be uploaded to API Manager. In Mule 4, once the policy behavior is defined, the policy has to be packaged into a policy template JAR and uploaded to Exchange to make it available in API Manager. 1. How to create a Maven project to generate the policy template JAR is explained in the [Packaging a Custom Policy](https://docs.mulesoft.com/mule-gateway/policies-custom-package) article. 2. How to upload the JAR to Exchange is explained in the [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange) article. Just like before, once the policy template JAR is in Exchange, it will appear in API Manager for APIs that belong to the same organization where the JAR was uploaded. ## Perform a Policy Migration To perform a policy migration, this example uses the Mule Migration Assistant (MMA), an open source project on GitHub. The procedure requires that you meet the [Prerequisites](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-tutorial.adoc#prerequisites) for the tool. For complete user documentation on MMA, see [Migration to Mule 4 (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/migration-intro.adoc). The MMA command for migrating policies differs from the typical [command-line options (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-tool-procedure.adoc#options) for migrating a Mule app in one important way: - MMA expects the `-projectBasePath` to have both the policy XML and YAML files in the same directory. The following example assumes that policy files are under `src/main/policy`. Command-line Invocation: ```console $ java -jar mule-migration-assistant-runner-0.5.1.jar \ -projectBasePath /Users/me/AnypointStudio/workspace-studio/my-mule3-policy/src/main/policy \ -muleVersion 4.1.5 \ -destinationProjectBasePath /Users/me/my-dir/my-migrated-policy ``` Note that the MMA creates the directory for the migrated project through the `-destinationProjectBasePath` option. The `my-migrated-policy` must _not_ exist before you invoke the command. If you point to a folder that exists already, the migration fails with an error like this: `Exception: Destination folder already exists.` When the migrator runs successfully, you see a message like this: Successful Migration ```console Executing migration... ... ======================================================== MIGRATION SUCCESS ======================================================== Total time: 11.335 s Migration report: /Users/me/my-dir/my-migrated-policy/report/summary.html ``` After migration completes successfully, the destination folder contains: - A policy POM file. - The policy YAML file, renamed to the `artifactId` value found in the POM file. - The `report` directory containing the [Mule Migration Report (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-report.adoc) (`summary.html`). Note that the same information provided in the report can be found as comments in the policy XML file. - The `mule-artifact.json` file, with a `minMuleVersion` value that matches the `-muleVersion` value set in the MMA command. - The `src` directory, which contains the migrated content. The `src` directory contains directories `main` and `test`. Inside `main`, the `mule` directory contains the policy XML file, renamed to `template.xml`. At the same level as the `mule` directory, MMA might create a `resources` directory that contains DataWeave files or other files that the migrated policy needs. The `test` directory contains test configuration files. After a successful migration, you need to modify the POM file as explained in [POM Migration](#pom_migration). Once the POM file has the correct organization ID, you can compile with `mvn clean install`. If the compilation is successful, you can upload the migrated policy to Exchange using `maven clean deploy`. You can find a more detailed explanation of uploading a custom policy in [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange). ### POM Migration The POM file migration modifies the file to include the elements necessary for uploading the custom policy to Exchange. After the migration: Replace the `{orgId}` value in the `` and `` elements with the organization ID found in Anypoint Platform. For more information on how to obtain the organization ID, see [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange). By default, the Exchange URL is set to the production environment. ```xml {orgId} https://maven.anypoint.mulesoft.com/api/v1/organizations/{orgId}/maven ``` Note that for the EU version of the URL, you need to set the URL manually after the migration: - URL template for EU: `https://maven.eu1.anypoint.mulesoft.com/api/v1/organizations/{orgId}/maven` If the MMA does not find a POM file for the policy, MMA will create a new POM file. In this file, the `artifactId` for the policy will be the name of the parent directory for the policy XML file. For example, for a policy in `src/main/mytestpolicy/policy.xml`, the `artifactId` is `mytestpolicy`. ### Dependency and Plugin Versions Dependency and plugin versions are set by default by the MMA, and you can change manually, as needed. ### Un-Migrated Elements Several elements are not migrated from Mule 3 to Mule 4:
ElementReason

policy:before-exception

Unable to recreate the behavior in Mule 4.

policy:pointcut

Resource and API pointcuts are resolved by the Mule runtime engine automatically. App and Endpoint pointcuts do not have an equivalent in Mule 4.

policy:data

The behavior is resolved by the Mule runtime engine automatically.

For each of these elements, the child elements are removed, as well. ### Elements Migrated to Other Structures The throttling element `fixed-time-frame-algorithm` is migrated to the Rate Limit format if multiple `rate-limit` elements are found as child elements of the `delay-response` element. In addition, because Throttling SLA policy is no longer supported, if a `delay-response` element is found as a child of a `sla-based-algorithm` element, the policy is migrated to Rate Limit SLA format. ### Common Migration Issues If policy files are not found during the migration, the MMA prints a message like this one: Unsuccessful Migration ```console Executing migration... ... =============================================================================== MIGRATION FAILED =============================================================================== Total time: 3.008 s Exception: Cannot read mule project. Is it a Mule Studio project? com.mulesoft.tools.migration.engine.exception.MigrationJobException: Cannot read mule project. Is it a Mule Studio project? at com.mulesoft.tools.migration.engine.project.MuleProjectFactory.getMuleProject(MuleProjectFactory.java:50) at com.mulesoft.tools.migration.engine.MigrationJob.generateSourceApplicationModel(MigrationJob.java:116) at com.mulesoft.tools.migration.engine.MigrationJob.execute(MigrationJob.java:80) at com.mulesoft.tools.migration.MigrationRunner.main(MigrationRunner.java:83) =============================================================================== ``` ### POM Migration Issues If the MMA does not find the POM model for the policy, the MMA will either generate the model from an existing POM in Mule 3, or if there is no Mule 3 POM, the MMA will create the model. If MMA uses an existing POM, any incorrect POM definition that the MMA encounters will cause POM model creation process to fail. For information about a POM model failure, you need to check for any preceding error messages regarding MMA steps on modifying the POM model. ### YAML Migration Issues The following issues can occur:
CaseReason

Error editing YAML

Use stack trace in the MMA for more information.

Multiple YAMLs found

MMA expects only one YAML file in the project base path, which is interpreted as the policy YAML. If you need more than one YAML in the project, the extra YAML files must be stored in another directory.

No YAML found

MMA expects a YAML file in the project base path when migration starts. If none is found, it is possible that a separate error occurred earlier in the migration process.

### Threat Protection Migration Issues The following issues can occur:
CaseReason

Could not determine if policy is XML or JSON threat protection type

In threat protection policies, the elements xml-policy and json-policy determine which type of threat protection to migrate. Only one of them must be present. If none are present, the error message will appear in the migration report.

Element structure could not be found

In threat protection policies, the xml-policy element needs to have child element, structure.

Element values could not be found

In threat protection policies, the xml-policy element needs to have child element, values.

### Client Id Enforcement Migration Issue The following issue is possible:
CaseReason

Client Id Enforcement invalid migration element

If the basicAuthEnabled attribute in the validate-client element is absent or equal to false, MMA expects clientSecret or clientId attributes to be present in the validate-client element.

### Spring Limitations You must perform a manual migration of your Spring Beans even though MMA migrates `spring:bean` elements in Mule 3 policies to a `template-beans.xml` file in the `resources` directory and even though it adds to the custom policy a `spring-module:config` element that references `template-beans.xml`. Declaring the beans in a policy is unsupported in Mule 4 and causes the policy to fail to deploy. ### Known Issues Known issues for MMA are: - Policies that have policy YAML files with the `.yml` extension are not detected. - Policy YAML files are not autocompleted with mandatory fields. - `mule:processor` element is not migrated. - `byte-array-to-string-transformer` element is not migrated. - `expression-component` element is not migrated. - `mulexml:object-to-xml-transformer` element is not migrated. - The migrated element `ee:transform` does not add a schema location URI. - DataWeave expressions that start with an underscore are not quoted, which causes the policy to fail. ## See Also [Migrating API Gateways](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways) [Migrating API Gateways: Autodiscovery](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways-autodiscovery) [Migrating API Gateways: Mule Runtime Configuration](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways-runtime-config) [Core Components Migration](https://docs.mulesoft.com/mule-runtime/4.3/migration-core) [Rate Limit and Throttling Policy](https://docs.mulesoft.com/gateway/latest/policies-included-rate-limiting) [Rate Limit SLA Based Policies](https://docs.mulesoft.com/gateway/latest/policies-included-rate-limiting-sla-based-policies) [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange) --- product: Mule Runtime version: 4.4 --- # Migrating API Policies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, policies underwent major changes. ## Defining Policy Behavior In 3.x, the logic inside a particular policy is split in two blocks, one that is executed before the next policy or flow, the other executed after it. Mule 3 Example ```xml ``` In Mule 4, policies are no longer separated in a `before` and `after` block. They now work as a flow with an explicit jump to the next policy or flow that has to be defined in it. Same behavior can be achieved in Mule 4 with the following config: Mule 4 Example ```xml ``` A few things to notice: - Logic is placed in the same block. Injecting behavior before the flow can be achieved just by putting logic before the `execute-next` element. To injecting behavior after the flow, you put logic after that element. - `propagateMessageTransformations` attribute in the `http-policy:source` element: Starting in Mule 4, changes to the Mule message (payload or attributes) before executing the flow are not propagated to it by default. To enable this, `propagateMessageTransformations` has to be set to `true`. - `pointcut` elements are no longer defined in the policy config file. Now, they are resolved by the API Gateway when policies are fetched from API Manager. Endpoint and App `pointcut` elements are no longer available, and there is no replacement to them. ## Uploading Policy Template to Exchange In 3.x, once the policy is defined, the result is an XML file that has to be uploaded to API Manager. In Mule 4, once the policy behavior is defined, the policy has to be packaged into a policy template JAR and uploaded to Exchange to make it available in API Manager. 1. How to create a Maven project to generate the policy template JAR is explained in the [Packaging a Custom Policy](https://docs.mulesoft.com/mule-gateway/policies-custom-package) article. 2. How to upload the JAR to Exchange is explained in the [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange) article. Just like before, once the policy template JAR is in Exchange, it will appear in API Manager for APIs that belong to the same organization where the JAR was uploaded. ## Perform a Policy Migration To perform a policy migration, this example uses the Mule Migration Assistant (MMA), an open source project on GitHub. The procedure requires that you meet the [Prerequisites](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-tutorial.adoc#prerequisites) for the tool. For complete user documentation on MMA, see [Migration to Mule 4 (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/migration-intro.adoc). The MMA command for migrating policies differs from the typical [command-line options (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-tool-procedure.adoc#options) for migrating a Mule app in one important way: - MMA expects the `-projectBasePath` to have both the policy XML and YAML files in the same directory. The following example assumes that policy files are under `src/main/policy`. Command-line Invocation: ```console $ java -jar mule-migration-assistant-runner-0.5.1.jar \ -projectBasePath /Users/me/AnypointStudio/workspace-studio/my-mule3-policy/src/main/policy \ -muleVersion 4.1.5 \ -destinationProjectBasePath /Users/me/my-dir/my-migrated-policy ``` Note that the MMA creates the directory for the migrated project through the `-destinationProjectBasePath` option. The `my-migrated-policy` must _not_ exist before you invoke the command. If you point to a folder that exists already, the migration fails with an error like this: `Exception: Destination folder already exists.` When the migrator runs successfully, you see a message like this: Successful Migration ```console Executing migration... ... ======================================================== MIGRATION SUCCESS ======================================================== Total time: 11.335 s Migration report: /Users/me/my-dir/my-migrated-policy/report/summary.html ``` After migration completes successfully, the destination folder contains: - A policy POM file. - The policy YAML file, renamed to the `artifactId` value found in the POM file. - The `report` directory containing the [Mule Migration Report (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-report.adoc) (`summary.html`). Note that the same information provided in the report can be found as comments in the policy XML file. - The `mule-artifact.json` file, with a `minMuleVersion` value that matches the `-muleVersion` value set in the MMA command. - The `src` directory, which contains the migrated content. The `src` directory contains directories `main` and `test`. Inside `main`, the `mule` directory contains the policy XML file, renamed to `template.xml`. At the same level as the `mule` directory, MMA might create a `resources` directory that contains DataWeave files or other files that the migrated policy needs. The `test` directory contains test configuration files. After a successful migration, you need to modify the POM file as explained in [POM Migration](#pom_migration). Once the POM file has the correct organization ID, you can compile with `mvn clean install`. If the compilation is successful, you can upload the migrated policy to Exchange using `maven clean deploy`. You can find a more detailed explanation of uploading a custom policy in [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange). ### POM Migration The POM file migration modifies the file to include the elements necessary for uploading the custom policy to Exchange. After the migration: Replace the `{orgId}` value in the `` and `` elements with the organization ID found in Anypoint Platform. For more information on how to obtain the organization ID, see [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange). By default, the Exchange URL is set to the production environment. ```xml {orgId} https://maven.anypoint.mulesoft.com/api/v1/organizations/{orgId}/maven ``` Note that for the EU version of the URL, you need to set the URL manually after the migration: - URL template for EU: `https://maven.eu1.anypoint.mulesoft.com/api/v1/organizations/{orgId}/maven` If the MMA does not find a POM file for the policy, MMA will create a new POM file. In this file, the `artifactId` for the policy will be the name of the parent directory for the policy XML file. For example, for a policy in `src/main/mytestpolicy/policy.xml`, the `artifactId` is `mytestpolicy`. ### Dependency and Plugin Versions Dependency and plugin versions are set by default by the MMA, and you can change manually, as needed. ### Un-Migrated Elements Several elements are not migrated from Mule 3 to Mule 4:
ElementReason

policy:before-exception

Unable to recreate the behavior in Mule 4.

policy:pointcut

Resource and API pointcuts are resolved by the Mule runtime engine automatically. App and Endpoint pointcuts do not have an equivalent in Mule 4.

policy:data

The behavior is resolved by the Mule runtime engine automatically.

For each of these elements, the child elements are removed, as well. ### Elements Migrated to Other Structures The throttling element `fixed-time-frame-algorithm` is migrated to the Rate Limit format if multiple `rate-limit` elements are found as child elements of the `delay-response` element. In addition, because Throttling SLA policy is no longer supported, if a `delay-response` element is found as a child of a `sla-based-algorithm` element, the policy is migrated to Rate Limit SLA format. ### Common Migration Issues If policy files are not found during the migration, the MMA prints a message like this one: Unsuccessful Migration ```console Executing migration... ... =============================================================================== MIGRATION FAILED =============================================================================== Total time: 3.008 s Exception: Cannot read mule project. Is it a Mule Studio project? com.mulesoft.tools.migration.engine.exception.MigrationJobException: Cannot read mule project. Is it a Mule Studio project? at com.mulesoft.tools.migration.engine.project.MuleProjectFactory.getMuleProject(MuleProjectFactory.java:50) at com.mulesoft.tools.migration.engine.MigrationJob.generateSourceApplicationModel(MigrationJob.java:116) at com.mulesoft.tools.migration.engine.MigrationJob.execute(MigrationJob.java:80) at com.mulesoft.tools.migration.MigrationRunner.main(MigrationRunner.java:83) =============================================================================== ``` ### POM Migration Issues If the MMA does not find the POM model for the policy, the MMA will either generate the model from an existing POM in Mule 3, or if there is no Mule 3 POM, the MMA will create the model. If MMA uses an existing POM, any incorrect POM definition that the MMA encounters will cause POM model creation process to fail. For information about a POM model failure, you need to check for any preceding error messages regarding MMA steps on modifying the POM model. ### YAML Migration Issues The following issues can occur:
CaseReason

Error editing YAML

Use stack trace in the MMA for more information.

Multiple YAMLs found

MMA expects only one YAML file in the project base path, which is interpreted as the policy YAML. If you need more than one YAML in the project, the extra YAML files must be stored in another directory.

No YAML found

MMA expects a YAML file in the project base path when migration starts. If none is found, it is possible that a separate error occurred earlier in the migration process.

### Threat Protection Migration Issues The following issues can occur:
CaseReason

Could not determine if policy is XML or JSON threat protection type

In threat protection policies, the elements xml-policy and json-policy determine which type of threat protection to migrate. Only one of them must be present. If none are present, the error message will appear in the migration report.

Element structure could not be found

In threat protection policies, the xml-policy element needs to have child element, structure.

Element values could not be found

In threat protection policies, the xml-policy element needs to have child element, values.

### Client Id Enforcement Migration Issue The following issue is possible:
CaseReason

Client Id Enforcement invalid migration element

If the basicAuthEnabled attribute in the validate-client element is absent or equal to false, MMA expects clientSecret or clientId attributes to be present in the validate-client element.

### Spring Limitations You must perform a manual migration of your Spring Beans even though MMA migrates `spring:bean` elements in Mule 3 policies to a `template-beans.xml` file in the `resources` directory and even though it adds to the custom policy a `spring-module:config` element that references `template-beans.xml`. Declaring the beans in a policy is unsupported in Mule 4 and causes the policy to fail to deploy. ### Known Issues Known issues for MMA are: - Policies that have policy YAML files with the `.yml` extension are not detected. - Policy YAML files are not autocompleted with mandatory fields. - `mule:processor` element is not migrated. - `byte-array-to-string-transformer` element is not migrated. - `expression-component` element is not migrated. - `mulexml:object-to-xml-transformer` element is not migrated. - The migrated element `ee:transform` does not add a schema location URI. - DataWeave expressions that start with an underscore are not quoted, which causes the policy to fail. ## See Also [Migrating API Gateways](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways) [Migrating API Gateways: Autodiscovery](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways-autodiscovery) [Migrating API Gateways: Mule Runtime Configuration](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways-runtime-config) [Core Components Migration](https://docs.mulesoft.com/mule-runtime/4.4/migration-core) [Rate Limit and Throttling Policy](https://docs.mulesoft.com/gateway/latest/policies-included-rate-limiting) [Rate Limit SLA Based Policies](https://docs.mulesoft.com/gateway/latest/policies-included-rate-limiting-sla-based-policies) [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange) --- product: Mule Runtime version: 4.3 --- # Migrating API Proxies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## Performing a Proxy Migration To perform a proxy migration, this example uses the Mule Migration Assistant (MMA). The procedure requires that you meet the [Prerequisites](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-tutorial.adoc#prerequisites) for the tool. For complete user documentation on MMA, see [Migration to Mule 4 (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/migration-intro.adoc). The MMA command for migrating proxies uses the standard [command-line options (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-tool-procedure.adoc#options) for migrating a Mule app: Command-line Invocation: ```console $ java -jar mule-migration-assistant-runner-0.5.1.jar \ -projectBasePath /Users/me/AnypointStudio/workspace-studio/my-mule3-proxy/ \ -muleVersion 4.1.5 \ -destinationProjectBasePath /Users/me/my-dir/my-migrated-proxy ``` Note that the MMA creates the directory for the migrated project through the `-destinationProjectBasePath` option. The `my-migrated-proxy` must _not_ exist before you invoke the command. If you point to a folder that exists already, the migration will fail an error like this: `Exception: Destination folder already exists.` When the migrator runs successfully, you see a message something like this: Successful Migration ```console Executing migration... ... ======================================================== MIGRATION SUCCESS ======================================================== Total time: 11.335 s Migration report: /Users/me/my-dir/my-migrated-proxy/report/summary.html ``` After migration completes successfully, the destination folder contains: - A proxy POM file. - The `report` directory containing the [Mule Migration Report (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-report.adoc) (`summary.html`). Note that the same information provided in the report can be found as comments in the proxy XML file. - The `mule-artifact.json` file, with a `minMuleVersion` value that matches the `-muleVersion` value set in the MMA command. - The `src` directory, which contains the migrated content. The `src` directory contains subdirectories `main` and `test`. Inside `main`, the `mule` directory is the proxy XML file. At the same level as the `mule` directory, MMA will create a `resources` directory for any DataWeave files or other files that the migrated proxy needs. Note that the configuration file defined in the proxy XML must be present in the `resources` directory for the artifact to be deployed correctly. The `test` directory contains test configuration files. After a successful migration, you need to modify the POM file as explained in [POM Migration](#pom_migration). Once the POM file has the correct organization ID, you can compile with `mvn clean install`. If the compilation is successful, you can upload the migrated proxy to Exchange using `maven clean deploy`. You can find a more detailed explanation of uploading a custom app in [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). ### POM Migration The POM file migration modifies the file to include the elements necessary for uploading the custom proxy to Exchange. _After_ the migration: - Replace the `{orgId}` value in the `` and `` elements with the organization ID found in Anypoint Platform. For more information on how to obtain the organization ID, see [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange). By default, the Exchange URL is set to the production environment. ```xml {orgId} https://maven.anypoint.mulesoft.com/api/v1/organizations/{orgId}/maven ``` Note that for the EU version of the URL, you need to set the URL manually after the migration: - URL template for EU: `https://maven.eu1.anypoint.mulesoft.com/api/v1/organizations/{orgId}/maven` If the MMA does not find a POM file for the proxy, MMA will create a new POM file. In this file, the `artifactId` for the proxy is the name of the base directory for the proxy app. For example, for a proxy in `mytestproxy/src/main/app/proxy.xml`, the `artifactId` is `mytestproxy`. ### Dependency and Plugin Versions Dependency and plugin versions are set by default by the MMA, and you can change them manually, as needed. ### Un-Migrated Elements Several elements are not migrated from Mule 3 to Mule 4:
ElementReason

api-platform-gw:tags

API auto-create is disabled in Mule 4.

api-platform-gw:description

API auto-create is disabled in Mule 4.

For each of these elements, the child elements are removed, as well. ### Common Migration Issues If proxy files are not found during the migration, the MMA prints a message like this one: Unsuccessful Migration ```console Executing migration... ... =============================================================================== MIGRATION FAILED =============================================================================== Total time: 3.008 s Exception: Cannot read mule project. Is it a Mule Studio project? com.mulesoft.tools.migration.engine.exception.MigrationJobException: Cannot read mule project. Is it a Mule Studio project? at com.mulesoft.tools.migration.engine.project.MuleProjectFactory.getMuleProject(MuleProjectFactory.java:50) at com.mulesoft.tools.migration.engine.MigrationJob.generateSourceApplicationModel(MigrationJob.java:116) at com.mulesoft.tools.migration.engine.MigrationJob.execute(MigrationJob.java:80) at com.mulesoft.tools.migration.MigrationRunner.main(MigrationRunner.java:83) =============================================================================== ``` ### POM Migration Issues If the MMA does not find the POM model for the proxy, the MMA will either generate the model from an existing POM in Mule 3, or if there is no Mule 3 POM, the MMA will create the model. If MMA uses an existing POM, any incorrect POM definition that the MMA encounters will cause POM model creation process to fail. For information about a POM model failure, you need to check for any preceding error messages regarding MMA steps on modifying the POM model. ### RAML Proxy Migration RAML proxy elements are migrated to REST proxy elements:
Mule 3Mule 4

proxy:raml-proxy-config.

rest-validator:config.

proxy:raml.

rest-validator:validate-request.

apikit:mapping-exception-strategy.

error-handler with on-error-continue elements in the flow containing the rest-validator:validate-request element.

The `error-handler` element contains the following types for `on-error-continue` elements:
TypeStatus Code

REST-VALIDATOR:BAD_REQUEST

400

REST-VALIDATOR:RESOURCE_NOT_FOUND

404

REST-VALIDATOR:METHOD_NOT_ALLOWED

405

HTTP:TIMEOUT

504

Exceptions that are not found in the Mule 3 element are autocompleted by the Mule Migration Assistant. ### WSDL Proxy Migration WSDL proxy migration consists of migrating the attribute values for WSDL properties. In Mule 3, most values are extracted using the function defined as attribute value. In Mule 4, there is no equivalent process, so most properties are migrated to a default value and require manual configuration with values from the WSDL file, which start with the `service` keyword. Some properties are renamed to extract the value in a more transparent way, for example:
Mule 3Mule 4

![wsdl(p['wsdl.uri']).services[0].preferredPort.name]

${service.port}

![wsdl(p['wsdl.uri']).targetNamespace]

${service.namespace}

![wsdl(p['wsdl.uri']).services[0].name]

${service.name}

Other properties, such as the following, are migrated to a DataWeave expression that uses the WSDL Functions Extension dependency, provided by MMA, to extract the expected values:
Mule 3Mule 4

![wsdl(p['wsdl.uri']).services[0].preferredPort.addresses[0].port]

#[Wsdl::getPort('${wsdl.uri}','${service.name}','${service.port}')]

![wsdl(p['wsdl.uri']).services[0].preferredPort.addresses[0].host]

#[Wsdl::getHost('${wsdl.uri}','${service.name}','${service.port}')]

![wsdl(p['wsdl.uri']).services[0].preferredPort.addresses[0].path]

#[Wsdl::getPath('${wsdl.uri}','${service.name}','${service.port}')]

## See Also [Migrating API Gateways](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways) [Migrating API Gateways: Autodiscovery](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways-autodiscovery) [Migrating API Gateways: Mule Runtime Configuration](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways-runtime-config) [Core Components Migration](https://docs.mulesoft.com/mule-runtime/4.3/migration-core) [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven) --- product: Mule Runtime version: 4.4 --- # Migrating API Proxies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt ## Performing a Proxy Migration To perform a proxy migration, this example uses the Mule Migration Assistant (MMA). The procedure requires that you meet the [Prerequisites](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-tutorial.adoc#prerequisites) for the tool. For complete user documentation on MMA, see [Migration to Mule 4 (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/migration-intro.adoc). The MMA command for migrating proxies uses the standard [command-line options (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-tool-procedure.adoc#options) for migrating a Mule app: Command-line Invocation: ```console $ java -jar mule-migration-assistant-runner-0.5.1.jar \ -projectBasePath /Users/me/AnypointStudio/workspace-studio/my-mule3-proxy/ \ -muleVersion 4.1.5 \ -destinationProjectBasePath /Users/me/my-dir/my-migrated-proxy ``` Note that the MMA creates the directory for the migrated project through the `-destinationProjectBasePath` option. The `my-migrated-proxy` must _not_ exist before you invoke the command. If you point to a folder that exists already, the migration will fail an error like this: `Exception: Destination folder already exists.` When the migrator runs successfully, you see a message something like this: Successful Migration ```console Executing migration... ... ======================================================== MIGRATION SUCCESS ======================================================== Total time: 11.335 s Migration report: /Users/me/my-dir/my-migrated-proxy/report/summary.html ``` After migration completes successfully, the destination folder contains: - A proxy POM file. - The `report` directory containing the [Mule Migration Report (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-report.adoc) (`summary.html`). Note that the same information provided in the report can be found as comments in the proxy XML file. - The `mule-artifact.json` file, with a `minMuleVersion` value that matches the `-muleVersion` value set in the MMA command. - The `src` directory, which contains the migrated content. The `src` directory contains subdirectories `main` and `test`. Inside `main`, the `mule` directory is the proxy XML file. At the same level as the `mule` directory, MMA will create a `resources` directory for any DataWeave files or other files that the migrated proxy needs. Note that the configuration file defined in the proxy XML must be present in the `resources` directory for the artifact to be deployed correctly. The `test` directory contains test configuration files. After a successful migration, you need to modify the POM file as explained in [POM Migration](#pom_migration). Once the POM file has the correct organization ID, you can compile with `mvn clean install`. If the compilation is successful, you can upload the migrated proxy to Exchange using `maven clean deploy`. You can find a more detailed explanation of uploading a custom app in [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven). ### POM Migration The POM file migration modifies the file to include the elements necessary for uploading the custom proxy to Exchange. _After_ the migration: - Replace the `{orgId}` value in the `` and `` elements with the organization ID found in Anypoint Platform. For more information on how to obtain the organization ID, see [Uploading a Custom Policy to Exchange](https://docs.mulesoft.com/mule-gateway/policies-custom-upload-to-exchange). By default, the Exchange URL is set to the production environment. ```xml {orgId} https://maven.anypoint.mulesoft.com/api/v1/organizations/{orgId}/maven ``` Note that for the EU version of the URL, you need to set the URL manually after the migration: - URL template for EU: `https://maven.eu1.anypoint.mulesoft.com/api/v1/organizations/{orgId}/maven` If the MMA does not find a POM file for the proxy, MMA will create a new POM file. In this file, the `artifactId` for the proxy is the name of the base directory for the proxy app. For example, for a proxy in `mytestproxy/src/main/app/proxy.xml`, the `artifactId` is `mytestproxy`. ### Dependency and Plugin Versions Dependency and plugin versions are set by default by the MMA, and you can change them manually, as needed. ### Un-Migrated Elements Several elements are not migrated from Mule 3 to Mule 4:
ElementReason

api-platform-gw:tags

API auto-create is disabled in Mule 4.

api-platform-gw:description

API auto-create is disabled in Mule 4.

For each of these elements, the child elements are removed, as well. ### Common Migration Issues If proxy files are not found during the migration, the MMA prints a message like this one: Unsuccessful Migration ```console Executing migration... ... =============================================================================== MIGRATION FAILED =============================================================================== Total time: 3.008 s Exception: Cannot read mule project. Is it a Mule Studio project? com.mulesoft.tools.migration.engine.exception.MigrationJobException: Cannot read mule project. Is it a Mule Studio project? at com.mulesoft.tools.migration.engine.project.MuleProjectFactory.getMuleProject(MuleProjectFactory.java:50) at com.mulesoft.tools.migration.engine.MigrationJob.generateSourceApplicationModel(MigrationJob.java:116) at com.mulesoft.tools.migration.engine.MigrationJob.execute(MigrationJob.java:80) at com.mulesoft.tools.migration.MigrationRunner.main(MigrationRunner.java:83) =============================================================================== ``` ### POM Migration Issues If the MMA does not find the POM model for the proxy, the MMA will either generate the model from an existing POM in Mule 3, or if there is no Mule 3 POM, the MMA will create the model. If MMA uses an existing POM, any incorrect POM definition that the MMA encounters will cause POM model creation process to fail. For information about a POM model failure, you need to check for any preceding error messages regarding MMA steps on modifying the POM model. ### RAML Proxy Migration RAML proxy elements are migrated to REST proxy elements:
Mule 3Mule 4

proxy:raml-proxy-config.

rest-validator:config.

proxy:raml.

rest-validator:validate-request.

apikit:mapping-exception-strategy.

error-handler with on-error-continue elements in the flow containing the rest-validator:validate-request element.

The `error-handler` element contains the following types for `on-error-continue` elements:
TypeStatus Code

REST-VALIDATOR:BAD_REQUEST

400

REST-VALIDATOR:RESOURCE_NOT_FOUND

404

REST-VALIDATOR:METHOD_NOT_ALLOWED

405

HTTP:TIMEOUT

504

Exceptions that are not found in the Mule 3 element are autocompleted by the Mule Migration Assistant. ### WSDL Proxy Migration WSDL proxy migration consists of migrating the attribute values for WSDL properties. In Mule 3, most values are extracted using the function defined as attribute value. In Mule 4, there is no equivalent process, so most properties are migrated to a default value and require manual configuration with values from the WSDL file, which start with the `service` keyword. Some properties are renamed to extract the value in a more transparent way, for example:
Mule 3Mule 4

![wsdl(p['wsdl.uri']).services[0].preferredPort.name]

${service.port}

![wsdl(p['wsdl.uri']).targetNamespace]

${service.namespace}

![wsdl(p['wsdl.uri']).services[0].name]

${service.name}

Other properties, such as the following, are migrated to a DataWeave expression that uses the WSDL Functions Extension dependency, provided by MMA, to extract the expected values:
Mule 3Mule 4

![wsdl(p['wsdl.uri']).services[0].preferredPort.addresses[0].port]

#[Wsdl::getPort('${wsdl.uri}','${service.name}','${service.port}')]

![wsdl(p['wsdl.uri']).services[0].preferredPort.addresses[0].host]

#[Wsdl::getHost('${wsdl.uri}','${service.name}','${service.port}')]

![wsdl(p['wsdl.uri']).services[0].preferredPort.addresses[0].path]

#[Wsdl::getPath('${wsdl.uri}','${service.name}','${service.port}')]

## See Also [Migrating API Gateways](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways) [Migrating API Gateways: Autodiscovery](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways-autodiscovery) [Migrating API Gateways: Mule Runtime Configuration](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways-runtime-config) [Core Components Migration](https://docs.mulesoft.com/mule-runtime/4.4/migration-core) [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven) --- product: Mule Runtime version: 4.3 --- # Migrating Connectors and Modules to Mule 4 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This section covers the migration of connector-specific features and lists connectors that are deprecated or removed from Mule 4. ## Deprecated or Removed Connectors The following table shows deprecated/removed Mule 3.x modules and how to replace them in Mule 4.0.
Mule 3.x ModuleMule 4.0 Replacement

Ajax

Use APIkit + standard REST.

Atom

Replaced with HTTP + DataWeave.

Axis

Use Web Service Consumer / APIkit for SOAP.

BPM

MuleSoft now provides connectivity to Pega or Appian for BPM.

CXF

Use Web Service Consumer.

Drools

Removed.

EJB

Removed.

Guice

Removed.

jBPM

MuleSoft now provides connectivity to Pega or Appian for BPM.

Jetty

Use new HTTP module.

OGNL

Replaced DataWeave expression language, or MEL in compatibility module.

Patterns

Removed. Use flows instead.

Quartz

Use new Scheduler component.

RSS

Use HTTP + DataWeave.

Servlet

New embedded mode in development.

Stdio

Removed.

SXC

Use DataWeave.

Tomcat

New embedded mode in development.

UDP

Use Sockets connector.

XMPP

Removed.

--- product: Mule Runtime version: 4.4 --- # Migrating Connectors and Modules to Mule 4 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt This section covers the migration of connector-specific features and lists connectors that are deprecated or removed from Mule 4. ## Deprecated or Removed Connectors The following table shows deprecated/removed Mule 3.x modules and how to replace them in Mule 4.0.
Mule 3.x ModuleMule 4.0 Replacement

Ajax

Use APIkit + standard REST.

Atom

Replaced with HTTP + DataWeave.

Axis

Use Web Service Consumer / APIkit for SOAP.

BPM

MuleSoft now provides connectivity to Pega or Appian for BPM.

CXF

Use Web Service Consumer.

Drools

Removed.

EJB

Removed.

Guice

Removed.

jBPM

MuleSoft now provides connectivity to Pega or Appian for BPM.

Jetty

Use new HTTP module.

OGNL

Replaced DataWeave expression language, or MEL in compatibility module.

Patterns

Removed. Use flows instead.

Quartz

Use new Scheduler component.

RSS

Use HTTP + DataWeave.

Servlet

New embedded mode in development.

Stdio

Removed.

SXC

Use DataWeave.

Tomcat

New embedded mode in development.

UDP

Use Sockets connector.

XMPP

Removed.

--- product: Mule Runtime version: 4.3 --- # Migrating Core Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The table below maps Mule 3.x components to their Mule 4 equivalents.
Mule 3.x ComponentMule 4.0 Replacement

All router

Use Scatter Gather instead or execute the operations one after the other with different target attributes and then use DW to merge results.

async[processingStrategy]

Async processing strategies are no longer needed with the non-blocking execution engine; remove all processing strategies from your scope when you migrate to Mule 4. Use an Async scope wrapping all the components that you want to execute asynchronously.

asynchronous-processing-strategy

Async processing strategies are no longer needed with the non-blocking execution engine; remove all processing strategies from your scope when you migrate to Mule 4. Use an Async scope wrapping all the components that you want to execute asynchronously.

bridge

Build an equivalent flow

catch-exception-strategy

Use error-handler with an on-error-continue strategy.

choice-exception-strategy

Use error-handler with different strategies inside using error type selection or when attribute.

combine-collections-transformer

No longer needed with the simplified message model. MuleMessageCollections are replaced with arrays of Mule Messages, which can be merged or iterated through using any Mule component, such as DataWeave or foreach.

component

Use the Java module.

composite-source

Create one flow per each source and invoke a private flow using flow-ref for the common functionality.

configuration[defaultExceptionStrategy-ref]

New name is defaultErrorHandler-ref

configuration[flowEndingWithOneWayEndpointReturnsNull]

No longer needed with new execution engine.

configuration[useExtendedTransformations]

Removed.

configuration[enricherPropagatesSessionVariableChanges]

Removed.

copy-attachments

Per the new Message Structure, attachments will now be part of the message Attributes. You can manipulate them at will using DataWeave

copy-properties

Per the new Message Structure, properties will now be part of the message Attributes. You can manipulate them at will using DataWeave

custom-agent

No longer supported.

custom-aggregator

Use the Mule SDK to build the custom aggregator.

custom-connector

Use the Mule SDK to build your own connector.

custom-exception-strategy

No longer needed. Use error-handler

custom-lifecycle-adapter-factory

No longer supported.

custom-object-store

Use Object Store connector to create custom stores.

custom-processor

Use the Mule SDK or the Scripting module instead

custom-queue-store

Use the new VM Connector.

custom-router-resolver

Use the Mule SDK to build a custom router.

custom-router

Use the Mule SDK to build a custom router.

custom-service

Use flows.

custom-source

Use the Mule SDK to write a new event source.

custom-splitter

Use DataWeave or the Mule SDK.

custom-transaction-manager

Use the <bti:transaction-manager/>.

custom-transaction

No longer supported.

default-exception-strategy

Use error-handler with an on-error-propagate strategy.

default-in-memory-queue-store

Use the new VM Connector.

default-persistent-queue-store

Use the new VM Connector.

default-service-exception-strategy

Use error-handler with an on-error-propagate strategy.

endpoint

Use connectors.

exception-strategy

Use error-handler.

expression-component

Depending on the nature of your expression, you can either use DataWeave (for data access expressions), Scripting module or the Mule SDK for algorithmic expressions, or the Java module for expressions which simply access Java.

file-queue-store

Use the new VM Connector.

flow[processingStrategy]

Removed. Non-blocking execution engine ensures that users do not need to tune this.

idempotent-message-filter

Replaced by idempotent-message-validator.

idempotent-redelivery-policy

New name is redelivery-policy.

idempotent-secure-hash-message-filter

Replaced by idempotent-message-validator.

in-memory-store

Use Object Store connector to create custom stores.

inbound-endpoint

Use the event sources or triggers defined on each connector or module.

include-entry-point

Use the Java module.

interceptor-stack

Removed. Use custom policies.

invoke

Use the Java module

jndi-transaction-manager

Use the <bti:transaction-manager/>.

jrun-transaction-manager

Use the <bti:transaction-manager/>.

legacy-abstract-exception-strategy

Use the new error-handler

managed-store

Use Object Store connector to create custom stores.

message-properties-transformer

Use Transform component and DataWeave.

model

Removed. Use flows instead.

mule[version]

outbound-endpoint

Element moved from the core namespace to the new transports namespace.

poll → watermark

This capability has been built inside event sources from many connectors, like Salesforce, Database, SFTP, File, etc. You can also use the object-store connector to manually set the watermark values.

poll

Replaced with scheduler component.

processor

Depending on the nature of your expression, you can either use DataWeave (for data access expressions), Scripting module or the Mule SDK for algorithmic expressions, or the Java module for expressions which simply access Java.

prototype-object

Use Java module or Spring module.

queue-profile

Use the VM Connector.

queue-store

VM Connector.

recipient-list

Removed.

reconnect-custom-notifier

Removed.

reconnect-custom-strategy

Removed.

reconnect-notifier

Removed.

remove-attachment

No longer needed per the new Message Structure, attachments

remove-property

PNo longer needed per the new Message Structure, attachments

response

No longer needed.

request-reply

Mule 4 will not longer support request-reply for all connectors. Connectors that had a “request-reply” behavior will provide a “request-reply” operation built in, such as the JMS publish-consume operation.

resin-transaction-manager

Removed.

rollback-exception-strategy

Use error-handler with an on-error-propagate strategy.

scatter-gather[threading-profile]

No longer needed now that Mule 4 is non blocking.

seda-model

No more SEDA queues in Mule 4. The execution engine in Mule 4 is non-blocking.

service

Use flows.

set-attachment

No longer needed. Attachments can be stored as variables.

set-property

Properties no longer exist in the new message model. You can store attributes from the Mule message in a variable.

set-session-variable

Session variables have been removed. Users must explicitly pass headers across transport boundaries.

simple-in-memory-queue-store

Use the new VM Connector.

simple-service

Use flows.

simple-text-file-store

Use object store module extension to create custom stores.

singleton-object

Use Java module or Spring module.

spring-object

Use Java module or Spring module.

synchronous-processing-strategy

The behavior related to flow components execution is the same as flows in 4.x but it doesn’t always execute in the same thread as in 3.x.

transactional scope

Replaced with “try” scope.

username-password-filter

Removed.

validator

Removed.

weblogic-transaction-manager

Use the <bti:transaction-manager/>.

websphere-transaction-manager

Use the <bti:transaction-manager/>.

all-strategy

Removed.

entry-point-resolver

Use the Java module.

filter

Filters are replaced by the Validation module.

interceptor

Interceptors are replaced with custom policies.

message-info-mapping

No longer needed

point-resolver-set

Use the Use the Java module.

router

Removed.

threading-profile

No longer needed. The Runtime now tunes itself.

transformer

Removed. Most explicit transformations are no longer needed. Use DataWeave for the corner cases.

--- product: Mule Runtime version: 4.4 --- # Migrating Core Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The table below maps Mule 3.x components to their Mule 4 equivalents.
Mule 3.x ComponentMule 4.0 Replacement

All router

Use Scatter Gather instead or execute the operations one after the other with different target attributes and then use DW to merge results.

async[processingStrategy]

Async processing strategies are no longer needed with the non-blocking execution engine; remove all processing strategies from your scope when you migrate to Mule 4. Use an Async scope wrapping all the components that you want to execute asynchronously.

asynchronous-processing-strategy

Async processing strategies are no longer needed with the non-blocking execution engine; remove all processing strategies from your scope when you migrate to Mule 4. Use an Async scope wrapping all the components that you want to execute asynchronously.

bridge

Build an equivalent flow

catch-exception-strategy

Use error-handler with an on-error-continue strategy.

choice-exception-strategy

Use error-handler with different strategies inside using error type selection or when attribute.

combine-collections-transformer

No longer needed with the simplified message model. MuleMessageCollections are replaced with arrays of Mule Messages, which can be merged or iterated through using any Mule component, such as DataWeave or foreach.

component

Use the Java module.

composite-source

Create one flow per each source and invoke a private flow using flow-ref for the common functionality.

configuration[defaultExceptionStrategy-ref]

New name is defaultErrorHandler-ref

configuration[flowEndingWithOneWayEndpointReturnsNull]

No longer needed with new execution engine.

configuration[useExtendedTransformations]

Removed.

configuration[enricherPropagatesSessionVariableChanges]

Removed.

copy-attachments

Per the new Message Structure, attachments will now be part of the message Attributes. You can manipulate them at will using DataWeave

copy-properties

Per the new Message Structure, properties will now be part of the message Attributes. You can manipulate them at will using DataWeave

custom-agent

No longer supported.

custom-aggregator

Use the Mule SDK to build the custom aggregator.

custom-connector

Use the Mule SDK to build your own connector.

custom-exception-strategy

No longer needed. Use error-handler

custom-lifecycle-adapter-factory

No longer supported.

custom-object-store

Use Object Store connector to create custom stores.

custom-processor

Use the Mule SDK or the Scripting module instead

custom-queue-store

Use the new VM Connector.

custom-router-resolver

Use the Mule SDK to build a custom router.

custom-router

Use the Mule SDK to build a custom router.

custom-service

Use flows.

custom-source

Use the Mule SDK to write a new event source.

custom-splitter

Use DataWeave or the Mule SDK.

custom-transaction-manager

Use the <bti:transaction-manager/>.

custom-transaction

No longer supported.

default-exception-strategy

Use error-handler with an on-error-propagate strategy.

default-in-memory-queue-store

Use the new VM Connector.

default-persistent-queue-store

Use the new VM Connector.

default-service-exception-strategy

Use error-handler with an on-error-propagate strategy.

endpoint

Use connectors.

exception-strategy

Use error-handler.

expression-component

Depending on the nature of your expression, you can either use DataWeave (for data access expressions), Scripting module or the Mule SDK for algorithmic expressions, or the Java module for expressions which simply access Java.

file-queue-store

Use the new VM Connector.

flow[processingStrategy]

Removed. Non-blocking execution engine ensures that users do not need to tune this.

idempotent-message-filter

Replaced by idempotent-message-validator.

idempotent-redelivery-policy

New name is redelivery-policy.

idempotent-secure-hash-message-filter

Replaced by idempotent-message-validator.

in-memory-store

Use Object Store connector to create custom stores.

inbound-endpoint

Use the event sources or triggers defined on each connector or module.

include-entry-point

Use the Java module.

interceptor-stack

Removed. Use custom policies.

invoke

Use the Java module

jndi-transaction-manager

Use the <bti:transaction-manager/>.

jrun-transaction-manager

Use the <bti:transaction-manager/>.

legacy-abstract-exception-strategy

Use the new error-handler

managed-store

Use Object Store connector to create custom stores.

message-properties-transformer

Use Transform component and DataWeave.

model

Removed. Use flows instead.

mule[version]

outbound-endpoint

Element moved from the core namespace to the new transports namespace.

poll → watermark

This capability has been built inside event sources from many connectors, like Salesforce, Database, SFTP, File, etc. You can also use the object-store connector to manually set the watermark values.

poll

Replaced with scheduler component.

processor

Depending on the nature of your expression, you can either use DataWeave (for data access expressions), Scripting module or the Mule SDK for algorithmic expressions, or the Java module for expressions which simply access Java.

prototype-object

Use Java module or Spring module.

queue-profile

Use the VM Connector.

queue-store

VM Connector.

recipient-list

Removed.

reconnect-custom-notifier

Removed.

reconnect-custom-strategy

Removed.

reconnect-notifier

Removed.

remove-attachment

No longer needed per the new Message Structure, attachments

remove-property

PNo longer needed per the new Message Structure, attachments

response

No longer needed.

request-reply

Mule 4 will not longer support request-reply for all connectors. Connectors that had a “request-reply” behavior will provide a “request-reply” operation built in, such as the JMS publish-consume operation.

resin-transaction-manager

Removed.

rollback-exception-strategy

Use error-handler with an on-error-propagate strategy.

scatter-gather[threading-profile]

No longer needed now that Mule 4 is non blocking.

seda-model

No more SEDA queues in Mule 4. The execution engine in Mule 4 is non-blocking.

service

Use flows.

set-attachment

No longer needed. Attachments can be stored as variables.

set-property

Properties no longer exist in the new message model. You can store attributes from the Mule message in a variable.

set-session-variable

Session variables have been removed. Users must explicitly pass headers across transport boundaries.

simple-in-memory-queue-store

Use the new VM Connector.

simple-service

Use flows.

simple-text-file-store

Use object store module extension to create custom stores.

singleton-object

Use Java module or Spring module.

spring-object

Use Java module or Spring module.

synchronous-processing-strategy

The behavior related to flow components execution is the same as flows in 4.x but it doesn’t always execute in the same thread as in 3.x.

transactional scope

Replaced with “try” scope.

username-password-filter

Removed.

validator

Removed.

weblogic-transaction-manager

Use the <bti:transaction-manager/>.

websphere-transaction-manager

Use the <bti:transaction-manager/>.

all-strategy

Removed.

entry-point-resolver

Use the Java module.

filter

Filters are replaced by the Validation module.

interceptor

Interceptors are replaced with custom policies.

message-info-mapping

No longer needed

point-resolver-set

Use the Use the Java module.

router

Removed.

threading-profile

No longer needed. The Runtime now tunes itself.

transformer

Removed. Most explicit transformations are no longer needed. Use DataWeave for the corner cases.

--- product: Mule Runtime version: 4.3 --- # Migrating Exception Strategies to Mule Error Handlers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The following examples will guide you through the migration of the different exception strategies of Mule 3 considering the new error handling components in Mule 4. > [!IMPORTANT] The examples do not cover the migration of expressions used within the `when` > attribute. See [Migrating MEL to DataWeave](https://docs.mulesoft.com/mule-runtime/4.3/migration-mel) for guidance with migrating > expressions, and see [Working With Throwables](https://docs.mulesoft.com/java-module/latest/java-throwable) to use the > Java module to analyze exceptions. ## Catch Exception Strategy A Catch Exception Strategy is equivalent to an Error Handler with a single `on-error-continue` component that accepts all errors, which is the default configuration: Mule 3 Example ```xml ``` Mule 4 Example ```xml ``` ## Rollback Exception Strategy A simple (no redelivery) rollback exception strategy is equivalent to an error handler with a single `on-error-propagate` component that accepts all errors, which is the default configuration: Mule 3 Example ```xml ``` Mule 4 Example ```xml ``` ## With Redelivery - `idempotent-redelivery-policy` gets renamed to `redelivery-policy` - `org.mule.runtime.core.api.exception.MessageRedeliveredException` has been replaced by the `REDELIVERY_EXHAUSTED` error type. - `dead-letter-queue` is removed. Any outbound operation performed to publish to a DLQ must be done as part of the handling of the `REDELIVERY_EXHAUSTED` error, for example: Mule 3 Example ```xml ``` Mule 4 Example ```xml ... ``` - `maxRedelivery` in `rollback-exception-strategy` is not supported anymore. A `` element with `maxRedelivery` must be created inside the `message-source`. ## Choice Exception Strategy A Choice exception strategy with inner catch/rollback exception strategies is equivalent to an error handler with on-error components continue/propagate according to the exception strategy kind, as explained above: Mule 3 Example ```xml ``` Mule 4 Example ```xml ``` ## Reference Exception Strategy Considering that the referenced exception strategy has already been migrated according to the above guidelines, migrating the actual reference is just adding a reference `error-handler`. Mule 3 Example ```xml ``` Mule 4 Example ```xml ``` ## See Also [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.3/error-handling) [Blog: A Look into Error Handling in Mule 4 Beta](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/how-to-error-handling-mule-4-beta/) --- product: Mule Runtime version: 4.4 --- # Migrating Exception Strategies to Mule Error Handlers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The following examples will guide you through the migration of the different exception strategies of Mule 3 considering the new error handling components in Mule 4. > [!IMPORTANT] The examples do not cover the migration of expressions used within the `when` > attribute. See [Migrating MEL to DataWeave](https://docs.mulesoft.com/mule-runtime/4.4/migration-mel) for guidance with migrating > expressions, and see [Working With Throwables](https://docs.mulesoft.com/java-module/latest/java-throwable) to use the > Java module to analyze exceptions. ## Catch Exception Strategy A Catch Exception Strategy is equivalent to an Error Handler with a single `on-error-continue` component that accepts all errors, which is the default configuration: Mule 3 Example ```xml ``` Mule 4 Example ```xml ``` ## Rollback Exception Strategy A simple (no redelivery) rollback exception strategy is equivalent to an error handler with a single `on-error-propagate` component that accepts all errors, which is the default configuration: Mule 3 Example ```xml ``` Mule 4 Example ```xml ``` ## With Redelivery - `idempotent-redelivery-policy` gets renamed to `redelivery-policy` - `org.mule.runtime.core.api.exception.MessageRedeliveredException` has been replaced by the `REDELIVERY_EXHAUSTED` error type. - `dead-letter-queue` is removed. Any outbound operation performed to publish to a DLQ must be done as part of the handling of the `REDELIVERY_EXHAUSTED` error, for example: Mule 3 Example ```xml ``` Mule 4 Example ```xml ... ``` - `maxRedelivery` in `rollback-exception-strategy` is not supported anymore. A `` element with `maxRedelivery` must be created inside the `message-source`. ## Choice Exception Strategy A Choice exception strategy with inner catch/rollback exception strategies is equivalent to an error handler with on-error components continue/propagate according to the exception strategy kind, as explained above: Mule 3 Example ```xml ``` Mule 4 Example ```xml ``` ## Reference Exception Strategy Considering that the referenced exception strategy has already been migrated according to the above guidelines, migrating the actual reference is just adding a reference `error-handler`. Mule 3 Example ```xml ``` Mule 4 Example ```xml ``` ## See Also [Error Handlers](https://docs.mulesoft.com/mule-runtime/4.4/error-handling) [Blog: A Look into Error Handling in Mule 4 Beta](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/how-to-error-handling-mule-4-beta/) --- product: Mule Runtime version: 4.3 --- # Migrating Filters > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 4 does not use `filters` anymore. The functionality provided by filters in Mule 3 can be achieved by using the [Validation Module](https://docs.mulesoft.com/validation-connector/latest/). ## Applying Filters In Mule 3, when a message was filtered, the flow ended silently at that point. The Validation module fails the flow when a condition is not met, which makes the migrated flow handle the `VALIDATION` error. The flow with the source for sending the response has to account for the `VALIDATION` error, which you can do by setting a variable in an error handler for validation errors, for example: Mule 4 example ```xml ... ... ``` You can then query the set variable in the source’s error response builder to send an appropriate response to the client. For instance, the `http:listener` source might be something like this: Mule 4 example ```xml #[error.description] ... ``` In this case, a 400 (Bad Request) code will be returned if the event is filtered. ## Migrating Custom or complex Filters Most likely, any custom or complex/nested filters you used can be migrated to use the expression language. The DataWeave script can be externalized to a file if the same filter needs to be in several places. For cases where you filter data in ways that DataWeave does not support, you should use the Java module or the Scripting module and use custom code to perform the filtering. ## See Also [Validation Module](https://docs.mulesoft.com/validation-connector/latest/) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) [Scripting Module](https://docs.mulesoft.com/scripting-module/latest/) [Java Module](https://docs.mulesoft.com/java-module/latest/) --- product: Mule Runtime version: 4.4 --- # Migrating Filters > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 4 does not use `filters` anymore. The functionality provided by filters in Mule 3 can be achieved by using the [Validation Module](https://docs.mulesoft.com/validation-connector/latest/). ## Applying Filters In Mule 3, when a message was filtered, the flow ended silently at that point. The Validation module fails the flow when a condition is not met, which makes the migrated flow handle the `VALIDATION` error. The flow with the source for sending the response has to account for the `VALIDATION` error, which you can do by setting a variable in an error handler for validation errors, for example: Mule 4 example ```xml ... ... ``` You can then query the set variable in the source’s error response builder to send an appropriate response to the client. For instance, the `http:listener` source might be something like this: Mule 4 example ```xml #[error.description] ... ``` In this case, a 400 (Bad Request) code will be returned if the event is filtered. ## Migrating Custom or complex Filters Most likely, any custom or complex/nested filters you used can be migrated to use the expression language. The DataWeave script can be externalized to a file if the same filter needs to be in several places. For cases where you filter data in ways that DataWeave does not support, you should use the Java module or the Scripting module and use custom code to perform the filtering. ## See Also [Validation Module](https://docs.mulesoft.com/validation-connector/latest/) [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) [Scripting Module](https://docs.mulesoft.com/scripting-module/latest/) [Java Module](https://docs.mulesoft.com/java-module/latest/) --- product: Mule Runtime version: 4.3 --- # Migrating from DataWeave version 1 to 2 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt - [DataWeave Header Content](#dw_header) - [Flow Controls](#dw_flow_control) - [Type References](#dw_type_references) - [Object Coercion](#dw_object_coercion) - [Conditional Key-Value Parenthesis](#dw_cond_key_value_parens) ## DataWeave Header Content Most of the header directives have been changed in DataWeave. The `%dw` directive is an exception. In most cases, MuleSoft removed the `%`, and in some cases the keyword is shortened.
DataWeave 1.0DataWeave 2.0Comments

%dw 1.0

%dw 2.0

%input

input

In a Mule app flow, DataWeave 2.0 recognizes the input MIME type and its reader properties based on the MIME type (outputMimeType) and parameters specified in the preceding component. The input MIME type is not defined using the input directive in the header anymore. However, the input directive is still used in specific cases like Validate a Script for Streamed Data.

%output

output

%var

var

%function

fun

%namespace

ns

## Flow Controls Flow control changed somewhat in DataWeave 2. ### When Otherwise The `when otherwise` statement is replaced by `if else`, for example: Mule 3 Example: DataWeave 1 ```dataweave { orderStatus: "complete" when flowVars.purchaseOrderStatus == "C" otherwise "incomplete" } ``` Mule 4 Example: DataWeave 2 ```dataweave { orderStatus: if(vars.purchaseOrderStatus == "C") "complete" else "incomplete" } ``` ### Pattern Matcher Pattern matching changed in DataWeave 2. It adds the keyword `case` and `else` (instead of `default`). You also no longer separate cases with commas (`,`) since they are now explicitly separated by the `case` keyword. Mule 3 Example: DataWeave 1 ```dataweave 'world' match { :string -> true, default -> false } ``` Mule 4 Example: DataWeave 2 ```dataweave 'world' match { case is String -> true else -> false } ``` For type pattern matchers, the `is` keyword needs to be set. ## Type References The `:` was removed from the type references and are now all camel case, so `:string` is now `String` ## Object Coercion In DataWeave 1.0, selecting a key-value pair from an object required you to do something like this: Mule 3 Example: DataWeave 1 ```dataweave %var payload = {a: 1, b:2} --- payload.a as :object ``` The DataWeave 1.0 expression above returns `{a:1}`. Because this is a coercion, it is also included in the auto-coercion mechanism and generates undesired or unexpected results. In DataWeave 2.0, the coercion is removed, and a new selector (`&`) is introduced to select key-value pair parenthesis. Mule 3 Example: DataWeave 2 ```dataweave var payload = {a: 1, b:2} --- payload.&a ``` This expression also returns `{a:1}`. ## Conditional Key-Value Parenthesis In DataWeave 1.0, conditional key-value pairs are declared with the `when` keyword. Mule 3 Example: DataWeave 1 ```dataweave { (a: 1) when payload.product == "Mule" } ``` In DataWeave 2.0, you use the `if` keyword. Mule 4 Example: DataWeave 2 ```dataweave { (a: 1) if payload.product == "Mule" } ``` ## See Also [Introduction to Mule 4: DataWeave 2.0](https://docs.mulesoft.com/mule-runtime/4.3/intro-dataweave2) --- product: Mule Runtime version: 4.4 --- # Migrating from DataWeave version 1 to 2 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt - [DataWeave Header Content](#dw_header) - [Flow Controls](#dw_flow_control) - [Type References](#dw_type_references) - [Object Coercion](#dw_object_coercion) - [Conditional Key-Value Parenthesis](#dw_cond_key_value_parens) ## DataWeave Header Content Most of the header directives have been changed in DataWeave. The `%dw` directive is an exception. In most cases, MuleSoft removed the `%`, and in some cases the keyword is shortened.
DataWeave 1.0DataWeave 2.0Comments

%dw 1.0

%dw 2.0

%input

input

In a Mule app flow, DataWeave 2.0 recognizes the input MIME type and its reader properties based on the MIME type (outputMimeType) and parameters specified in the preceding component. The input MIME type is not defined using the input directive in the header anymore. However, the input directive is still used in specific cases like Validate a Script for Streamed Data.

%output

output

%var

var

%function

fun

%namespace

ns

## Flow Controls Flow control changed somewhat in DataWeave 2. ### When Otherwise The `when otherwise` statement is replaced by `if else`, for example: Mule 3 Example: DataWeave 1 ```dataweave { orderStatus: "complete" when flowVars.purchaseOrderStatus == "C" otherwise "incomplete" } ``` Mule 4 Example: DataWeave 2 ```dataweave { orderStatus: if(vars.purchaseOrderStatus == "C") "complete" else "incomplete" } ``` ### Pattern Matcher Pattern matching changed in DataWeave 2. It adds the keyword `case` and `else` (instead of `default`). You also no longer separate cases with commas (`,`) since they are now explicitly separated by the `case` keyword. Mule 3 Example: DataWeave 1 ```dataweave 'world' match { :string -> true, default -> false } ``` Mule 4 Example: DataWeave 2 ```dataweave 'world' match { case is String -> true else -> false } ``` For type pattern matchers, the `is` keyword needs to be set. ## Type References The `:` was removed from the type references and are now all camel case, so `:string` is now `String` ## Object Coercion In DataWeave 1.0, selecting a key-value pair from an object required you to do something like this: Mule 3 Example: DataWeave 1 ```dataweave %var payload = {a: 1, b:2} --- payload.a as :object ``` The DataWeave 1.0 expression above returns `{a:1}`. Because this is a coercion, it is also included in the auto-coercion mechanism and generates undesired or unexpected results. In DataWeave 2.0, the coercion is removed, and a new selector (`&`) is introduced to select key-value pair parenthesis. Mule 3 Example: DataWeave 2 ```dataweave var payload = {a: 1, b:2} --- payload.&a ``` This expression also returns `{a:1}`. ## Conditional Key-Value Parenthesis In DataWeave 1.0, conditional key-value pairs are declared with the `when` keyword. Mule 3 Example: DataWeave 1 ```dataweave { (a: 1) when payload.product == "Mule" } ``` In DataWeave 2.0, you use the `if` keyword. Mule 4 Example: DataWeave 2 ```dataweave { (a: 1) if payload.product == "Mule" } ``` ## See Also [Introduction to Mule 4: DataWeave 2.0](https://docs.mulesoft.com/mule-runtime/4.4/intro-dataweave2) --- product: Mule Runtime version: 4.3 --- # Migrating HTTP Connector Uses > For the full documentation index, see: https://docs.mulesoft.com/llms.txt For the most part, the HTTP connector has just been adapted to the Mule 4 model: - Configuration properties have been moved to a connection component when applicable. - Message processors have been refactored into proper operations. - Outbound properties such as `http.status` have been removed in favor of explicit properties. - Inbound properties such as `http.queryParams` have been removed in favor of HTTP specific message attributes. - Threading configuration has been removed since it’s now all handled at the Mule Runtime level. - Special handling for `application/x-www-form-urlencoded` and `multipart/*` media types has been removed in favor of DataWeave. - RAML metadata support has been removed from the HTTP request operation in favor of REST Connect. ## What’s Covered Here? - [HTTP Listener](#http_listener) - [HTTP Request](#http-request) - [HTTP Static Resource Handler](#http-static-resource) - [HTTP Basic Security Filter](#http-basic-authentication) - [HTTP MIME Type Parsing](#http-mime-types) ## HTTP Listener The HTTP Listener has only seen major changes in the configuration of its response builders, as well as the encapsulation of its configuration properties into a specific connection component. ### Configuration The following properties and components must now be defined within an inner `http:listener-connection` component: - `host` - `port` - `protocol` - `usePersistentConnections` - `connectionIdleTimeout` - TLS Context Mule 3 example ```xml ``` Mule 4 example ```xml ``` ### Listener All HTTP Listener properties remain the same except for the `http:response-builder` and `http:error-response-builder`. These have been renamed to simply `http:response` and `http:error-response`, and now require the headers to be defined through a single expression while removing support for implicit outbound properties handling. Additionally, they support a new `http:body` component where an expression can be used to define the outgoing HTTP message body. Mule 3 example In the following example, a number of `User-Agent` headers are sent in a response set up through an implicit outbound property (`Mule 3.6.0`), a single header reference (`Mule 3.7.0`) and an expression reference (`Mule 3.8.0` and `Mule 3.9.0`). An error response, on the other hand, will feature a `Date` header as well as the outbound property for `User-Agent`. ```xml ... ``` Mule 4 example Notice that while `statusCode` and `reasonPhrase` properties remain the same, all headers should now be explicitly added using a DataWeave expression. It’s important to note that explicit `statusCode` and `reasonPhrase` must be provided as well to replace usages of outbound properties `http.status` and `http.reason`. ```xml #[{ 'User-Agent' : 'Mule 3.6.0', 'User-Agent' : 'Mule 3.7.0', 'User-Agent' : 'Mule 3.8.0', 'User-Agent' : 'Mule 3.9.0' }] #[{ 'User-Agent': 'Mule 3.6.0', 'Date': now() }] ... ``` #### Attributes Following the new Mule Message structure, the HTTP listener now provides all request metadata through specific HTTP Request Attributes. Below you can find the new ways of accessing that metadata compared to Mule 3.
MetadataMule 3Mule 4

Method

#[inboundProperties.'http.method']

#[attributes.method]

Path

#[inboundProperties.'http.listener.path']

#[attributes.listenerPath]

Relative Path

#[inboundProperties.'http.relative.path']

#[attributes.relativePath]

Request URI

#[inboundProperties.'http.request.uri']

#[attributes.requestUri]

Query String

#[inboundProperties.'http.query.string']

#[attributes.queryString]

Query Parameters

#[inboundProperties.'http.query.params']

#[attributes.queryParams]

URI Parameters

#[inboundProperties.'http.uri.params']

#[attributes.uriParams]

Version

#[inboundProperties.'http.version']

#[attributes.version]

Scheme

#[inboundProperties.'http.scheme']

#[attributes.scheme]

Headers

#[inboundProperties]

#[attributes.headers]

Remote Address

#[inboundProperties.'http.remote.address']

#[attributes.remoteAddress]

Client Certificate

#[inboundProperties.'http.client.cert']

#[attributes.clientCertificate]

Notice that while the HTTP headers were mapped directly into inbound properties, now they have an exclusive object. Below you can find an example of how to obtain a header: - Mule 3: `#[inboundProperties.'host']` - Mule 4: `#[attributes.headers.'host']` #### Encode Characters for HTTP Requests In Mule 4 to avoid a malformed URI when you make an HTTP request to the HTTP Listener, encode characters such as `{` and `}` that you set in the HTTP request as recommended in [RFC](https://datatracker.ietf.org/doc/html/rfc1738). Encode these characters both when you configure the request URL in the **Path** field of the HTTP Listener in Studio, and when you send the curl request command. In the following example, you encode the characters `{` to `%7B` and `}` to `%7D` of the URL `path=/profiles/{profileid}/credit`: 1. In Studio, select the HTTP **Listener** source from your flow. 2. In the **Path** field, set the relative path URL with the encoded characters, for example, `/profiles/%7Bprofileid%7D/credit` 3. Save all your application changes in Studio. 4. Run the curl command `http://localhost:8084/test?path=/profiles/%7Bprofileid%7D/credit` ## HTTP Request Like the HTTP listener, most changes in the HTTP request operation regard the encapsulation of configuration properties within a connection component and the request building process. ### Configuration The following properties and components must now be defined within an inner `http:request-connection` component: - `host` - `port` - `protocol` - `usePersistentConnections` - `maxConnections` - `connectionIdleTimeout` - `streamResponse` - `responseBufferSize` - HTTP Authentication - HTTP Proxy - TLS Context - TCP Client Socket Properties Mule 3 example ```xml ``` Mule 4 example ```xml ``` Note that RAML metadata support has been removed because REST Connect can now generate a specific connector for a given RAML, which can then be reused. #### HTTP Authentication In addition to now belonging in the `http:request-connection` component, the HTTP authentication configuration must be placed within an `http:authentication` component. This applies to all authentication types supported: basic, digest, NTLM and OAuth2. Mule 3 example ```xml ``` Mule 4 example ```xml ``` #### HTTP Proxy Just like the HTTP Authentication component, configuring an HTTP proxy now requires a wrapping `http:proxy-config` component, for all kinds of proxies. Mule 3 example ```xml ``` Mule 4 example ```xml ``` #### TCP Client Socket Properties In Mule 3, TCP client socket properties were defined based in the TCP transport which has been replaced in Mule 4 by the Sockets Connector, so now that is required to configure the properties. Additionally, the properties must be wrapped in an `http:client-socket-properties` component. Mule 3 example ```xml ``` Mule 4 example ```xml ``` ### Request All HTTP request properties remain the same except for the `source` which has between replaced by an `http:body` component supporting expressions and transformations and the `http:request-builder` which has been removed. Headers, query and URI parameters should now be defined explicitly through DataWeave expressions. Mule 3 example ```xml ... ... ``` Mule 4 example ```xml ... #[vars.customSource] #[{ 'Host': 'www.example.com' 'Transfer-Encoding' : 'chunked' }] #[{ 'id' : vars.songId }] #[vars.params] ... ``` #### Attributes Like the HTTP Listener , the HTTP request now provides all response metadata through specific HTTP Response Attributes. Below you can find the new ways of accessing that metadata compared to Mule 3.
MetadataMule 3Mule 4

Status Code

#[inboundProperties.'http.status']

#[attributes.statusCode]

Reason Phrase

#[inboundProperties.'http.reason']

#[attributes.reasonPhrase]

Headers

#[inboundProperties]

#[attributes.headers]

Notice that headers are treated just like in the HTTP Listener. ## HTTP Static Resource Handler The HTTP Static Resource Handler has been adapted to Mule 4’s operation model and renamed to `http:load-static-resource`. The `resourceBase` property has also been renamed to `resourceBasePath`. Mule 3 example ```xml ``` Mule 4 example ```xml ``` Though this operation is only meant to be used with an HTTP Listener source, we’ve also introduced an `attributes` property where you can reference the HTTP request attributes of the listener and thus use the operation in any point of the flow. ## HTTP Basic Security Filter The HTTP Basic Security Filter has not been changed except to support DataWeave as a source for the `securityProviders` property and the introduction of an `attributes` property where you can reference the HTTP request attributes of the listener and thus use the operation in any point of the flow, just like the HTTP load static resource operation. Mule 3 example ```xml ``` Mule 4 example ```xml ``` See [Configure LDAP Provider for Spring Security](https://docs.mulesoft.com/mule-runtime/4.3/setting-up-ldap-provider-for-spring-security) for a complete configuration example. ## HTTP MIME Type Parsing The HTTP connector in Mule 3 featured options to parse requests and responses when bodies of type `application/x-www-form-urlencoded` or `multipart/form-data` (and other subtypes) were received. When the parsed objects where encountered on outbound requests and responses, they were transformed back into those types of bodies for consistency. However, since DataWeave 2.0 now handles those MIME types, in Mule 4 HTTP parsing has been removed and HTTP components always provide and require binary data streams. Below you can find details on how to migrate uses of the formerly parsed types. ### application/x-www-form-urlencoded In Mule 3, a `Map` payload was used as a counterpart of `application/x-www-form-urlencoded` content. For outbound traffic, that meant that if a `Map` payload was present, then each key-value pair would be used to generate an `application/x-www-form-urlencoded` body. For inbound traffic, it meant that each key-value pair of that body would be put in a `Map`. Now, DataWeave can read and write `application/x-www-form-urlencoded` content, making it easier and more consistent to work with different MIME types in HTTP. Mule 3 example In this example, a payload of `song=Snow+Poems&artist=TQP` is sent and returned featuring an ID with which it was saved: `song=Snow+Poems&artist=TQP&id=49`. ```xml ``` Mule 4 example Notice that the syntax for reading the content remains the same except that now we must indicate an output type since we are actually transforming data. ```xml ... #[ %dw 2.0 output application/x-www-form-urlencoded --- { song: "Snow Poems", artist: "TQP" }] ... ``` Several values for a key can be added, just keep in mind accessing that data requires using the star selector to get the collection of all associated values: `#[payload.*artist]` would return a list with `David Bowie` and `Queen` for the song `Under Pressure`, for example. ### multipart/\* Mule Message attachments were used in Mule 3 as a counterpart of multipart content. For outbound traffic that meant that if attachments were present then those would be use as parts of a `multipart/form-data` body. For inbound traffic it meant that each part of that body would be mapped to a Mule Message attachment. In Mule 4, Mule Message attachments no longer exist. Instead, you can read and write multipart content through DataWeave as you would with JSON or XML content. Mule 3 example In this example, a `multipart/form-data` body is received featuring 2 JSON parts, an order and a partner who has generated it. After logging the partner name, the order ID is saved to generate a `multipart/form-data` response featuring a simple message acknowledging the order and a PDF receipt generated for it. ```xml ``` Mule 4 example All the complexity of handling the attachments is now gone, and we just access the parts by name using the `content` keyword. The multipart response is generated in the HTTP response body using DataWeave, where you can easily customize headers. ```xml ``` It’s important to notice that while we are taking advantage of the `http:body` feature, the same result could be achieved using a final transform component. Note that the boundary is autogenerated, which results in a correct content-type header. For details, see [Multipart Format (Form-Data)](https://docs.mulesoft.com/dataweave/2.3/dataweave-formats-multipart). == See Also [Core Components Migration](https://docs.mulesoft.com/mule-runtime/4.3/migration-core) [REST Connect](https://docs.mulesoft.com/exchange/to-deploy-using-rest-connect) --- product: Mule Runtime version: 4.4 --- # Migrating HTTP Connector Uses > For the full documentation index, see: https://docs.mulesoft.com/llms.txt For the most part, the HTTP connector has just been adapted to the Mule 4 model: - Configuration properties have been moved to a connection component when applicable. - Message processors have been refactored into proper operations. - Outbound properties such as `http.status` have been removed in favor of explicit properties. - Inbound properties such as `http.queryParams` have been removed in favor of HTTP specific message attributes. - Threading configuration has been removed since it’s now all handled at the Mule Runtime level. - Special handling for `application/x-www-form-urlencoded` and `multipart/*` media types has been removed in favor of DataWeave. - RAML metadata support has been removed from the HTTP request operation in favor of REST Connect. ## What’s Covered Here? - [HTTP Listener](#http_listener) - [HTTP Request](#http-request) - [HTTP Static Resource Handler](#http-static-resource) - [HTTP Basic Security Filter](#http-basic-authentication) - [HTTP MIME Type Parsing](#http-mime-types) ## HTTP Listener The HTTP Listener has only seen major changes in the configuration of its response builders, as well as the encapsulation of its configuration properties into a specific connection component. ### Configuration The following properties and components must now be defined within an inner `http:listener-connection` component: - `host` - `port` - `protocol` - `usePersistentConnections` - `connectionIdleTimeout` - TLS Context Mule 3 example ```xml ``` Mule 4 example ```xml ``` ### Listener All HTTP Listener properties remain the same except for the `http:response-builder` and `http:error-response-builder`. These have been renamed to simply `http:response` and `http:error-response`, and now require the headers to be defined through a single expression while removing support for implicit outbound properties handling. Additionally, they support a new `http:body` component where an expression can be used to define the outgoing HTTP message body. Mule 3 example In the following example, a number of `User-Agent` headers are sent in a response set up through an implicit outbound property (`Mule 3.6.0`), a single header reference (`Mule 3.7.0`) and an expression reference (`Mule 3.8.0` and `Mule 3.9.0`). An error response, on the other hand, will feature a `Date` header as well as the outbound property for `User-Agent`. ```xml ... ``` Mule 4 example Notice that while `statusCode` and `reasonPhrase` properties remain the same, all headers should now be explicitly added using a DataWeave expression. It’s important to note that explicit `statusCode` and `reasonPhrase` must be provided as well to replace usages of outbound properties `http.status` and `http.reason`. ```xml #[{ 'User-Agent' : 'Mule 3.6.0', 'User-Agent' : 'Mule 3.7.0', 'User-Agent' : 'Mule 3.8.0', 'User-Agent' : 'Mule 3.9.0' }] #[{ 'User-Agent': 'Mule 3.6.0', 'Date': now() }] ... ``` #### Attributes Following the new Mule Message structure, the HTTP listener now provides all request metadata through specific HTTP Request Attributes. Below you can find the new ways of accessing that metadata compared to Mule 3.
MetadataMule 3Mule 4

Method

#[inboundProperties.'http.method']

#[attributes.method]

Path

#[inboundProperties.'http.listener.path']

#[attributes.listenerPath]

Relative Path

#[inboundProperties.'http.relative.path']

#[attributes.relativePath]

Request URI

#[inboundProperties.'http.request.uri']

#[attributes.requestUri]

Query String

#[inboundProperties.'http.query.string']

#[attributes.queryString]

Query Parameters

#[inboundProperties.'http.query.params']

#[attributes.queryParams]

URI Parameters

#[inboundProperties.'http.uri.params']

#[attributes.uriParams]

Version

#[inboundProperties.'http.version']

#[attributes.version]

Scheme

#[inboundProperties.'http.scheme']

#[attributes.scheme]

Headers

#[inboundProperties]

#[attributes.headers]

Remote Address

#[inboundProperties.'http.remote.address']

#[attributes.remoteAddress]

Client Certificate

#[inboundProperties.'http.client.cert']

#[attributes.clientCertificate]

Notice that while the HTTP headers were mapped directly into inbound properties, now they have an exclusive object. Below you can find an example of how to obtain a header: - Mule 3: `#[inboundProperties.'host']` - Mule 4: `#[attributes.headers.'host']` #### Encode Characters for HTTP Requests In Mule 4 to avoid a malformed URI when you make an HTTP request to the HTTP Listener, encode characters such as `{` and `}` that you set in the HTTP request as recommended in [RFC](https://datatracker.ietf.org/doc/html/rfc1738). Encode these characters both when you configure the request URL in the **Path** field of the HTTP Listener in Studio, and when you send the curl request command. In the following example, you encode the characters `{` to `%7B` and `}` to `%7D` of the URL `path=/profiles/{profileid}/credit`: 1. In Studio, select the HTTP **Listener** source from your flow. 2. In the **Path** field, set the relative path URL with the encoded characters, for example, `/profiles/%7Bprofileid%7D/credit` 3. Save all your application changes in Studio. 4. Run the curl command `http://localhost:8084/test?path=/profiles/%7Bprofileid%7D/credit` ## HTTP Request Like the HTTP listener, most changes in the HTTP request operation regard the encapsulation of configuration properties within a connection component and the request building process. ### Configuration The following properties and components must now be defined within an inner `http:request-connection` component: - `host` - `port` - `protocol` - `usePersistentConnections` - `maxConnections` - `connectionIdleTimeout` - `streamResponse` - `responseBufferSize` - HTTP Authentication - HTTP Proxy - TLS Context - TCP Client Socket Properties Mule 3 example ```xml ``` Mule 4 example ```xml ``` Note that RAML metadata support has been removed because REST Connect can now generate a specific connector for a given RAML, which can then be reused. #### HTTP Authentication In addition to now belonging in the `http:request-connection` component, the HTTP authentication configuration must be placed within an `http:authentication` component. This applies to all authentication types supported: basic, digest, NTLM and OAuth2. Mule 3 example ```xml ``` Mule 4 example ```xml ``` #### HTTP Proxy Just like the HTTP Authentication component, configuring an HTTP proxy now requires a wrapping `http:proxy-config` component, for all kinds of proxies. Mule 3 example ```xml ``` Mule 4 example ```xml ``` #### TCP Client Socket Properties In Mule 3, TCP client socket properties were defined based in the TCP transport which has been replaced in Mule 4 by the Sockets Connector, so now that is required to configure the properties. Additionally, the properties must be wrapped in an `http:client-socket-properties` component. Mule 3 example ```xml ``` Mule 4 example ```xml ``` ### Request All HTTP request properties remain the same except for the `source` which has between replaced by an `http:body` component supporting expressions and transformations and the `http:request-builder` which has been removed. Headers, query and URI parameters should now be defined explicitly through DataWeave expressions. Mule 3 example ```xml ... ... ``` Mule 4 example ```xml ... #[vars.customSource] #[{ 'Host': 'www.example.com' 'Transfer-Encoding' : 'chunked' }] #[{ 'id' : vars.songId }] #[vars.params] ... ``` #### Attributes Like the HTTP Listener , the HTTP request now provides all response metadata through specific HTTP Response Attributes. Below you can find the new ways of accessing that metadata compared to Mule 3.
MetadataMule 3Mule 4

Status Code

#[inboundProperties.'http.status']

#[attributes.statusCode]

Reason Phrase

#[inboundProperties.'http.reason']

#[attributes.reasonPhrase]

Headers

#[inboundProperties]

#[attributes.headers]

Notice that headers are treated just like in the HTTP Listener. ## HTTP Static Resource Handler The HTTP Static Resource Handler has been adapted to Mule 4’s operation model and renamed to `http:load-static-resource`. The `resourceBase` property has also been renamed to `resourceBasePath`. Mule 3 example ```xml ``` Mule 4 example ```xml ``` Though this operation is only meant to be used with an HTTP Listener source, we’ve also introduced an `attributes` property where you can reference the HTTP request attributes of the listener and thus use the operation in any point of the flow. ## HTTP Basic Security Filter The HTTP Basic Security Filter has not been changed except to support DataWeave as a source for the `securityProviders` property and the introduction of an `attributes` property where you can reference the HTTP request attributes of the listener and thus use the operation in any point of the flow, just like the HTTP load static resource operation. Mule 3 example ```xml ``` Mule 4 example ```xml ``` See [Configure LDAP Provider for Spring Security](https://docs.mulesoft.com/mule-runtime/4.4/setting-up-ldap-provider-for-spring-security) for a complete configuration example. ## HTTP MIME Type Parsing The HTTP connector in Mule 3 featured options to parse requests and responses when bodies of type `application/x-www-form-urlencoded` or `multipart/form-data` (and other subtypes) were received. When the parsed objects where encountered on outbound requests and responses, they were transformed back into those types of bodies for consistency. However, since DataWeave 2.0 now handles those MIME types, in Mule 4 HTTP parsing has been removed and HTTP components always provide and require binary data streams. Below you can find details on how to migrate uses of the formerly parsed types. ### application/x-www-form-urlencoded In Mule 3, a `Map` payload was used as a counterpart of `application/x-www-form-urlencoded` content. For outbound traffic, that meant that if a `Map` payload was present, then each key-value pair would be used to generate an `application/x-www-form-urlencoded` body. For inbound traffic, it meant that each key-value pair of that body would be put in a `Map`. Now, DataWeave can read and write `application/x-www-form-urlencoded` content, making it easier and more consistent to work with different MIME types in HTTP. Mule 3 example In this example, a payload of `song=Snow+Poems&artist=TQP` is sent and returned featuring an ID with which it was saved: `song=Snow+Poems&artist=TQP&id=49`. ```xml ``` Mule 4 example Notice that the syntax for reading the content remains the same except that now we must indicate an output type since we are actually transforming data. ```xml ... #[ %dw 2.0 output application/x-www-form-urlencoded --- { song: "Snow Poems", artist: "TQP" }] ... ``` Several values for a key can be added, just keep in mind accessing that data requires using the star selector to get the collection of all associated values: `#[payload.*artist]` would return a list with `David Bowie` and `Queen` for the song `Under Pressure`, for example. ### multipart/\* Mule Message attachments were used in Mule 3 as a counterpart of multipart content. For outbound traffic that meant that if attachments were present then those would be use as parts of a `multipart/form-data` body. For inbound traffic it meant that each part of that body would be mapped to a Mule Message attachment. In Mule 4, Mule Message attachments no longer exist. Instead, you can read and write multipart content through DataWeave as you would with JSON or XML content. Mule 3 example In this example, a `multipart/form-data` body is received featuring 2 JSON parts, an order and a partner who has generated it. After logging the partner name, the order ID is saved to generate a `multipart/form-data` response featuring a simple message acknowledging the order and a PDF receipt generated for it. ```xml ``` Mule 4 example All the complexity of handling the attachments is now gone, and we just access the parts by name using the `content` keyword. The multipart response is generated in the HTTP response body using DataWeave, where you can easily customize headers. ```xml ``` It’s important to notice that while we are taking advantage of the `http:body` feature, the same result could be achieved using a final transform component. Note that the boundary is autogenerated, which results in a correct content-type header. For details, see [Multipart Format (Form-Data)](https://docs.mulesoft.com/dataweave/latest/dataweave-formats-multipart). == See Also [Core Components Migration](https://docs.mulesoft.com/mule-runtime/4.4/migration-core) [REST Connect](https://docs.mulesoft.com/exchange/to-deploy-using-rest-connect) --- product: Mule Runtime version: 4.3 --- # Migrating MEL to DataWeave > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, the DataWeave expression language replaces Mule Expression Language (MEL). This section provides guidance on migrating MEL expressions in your Mule apps to DataWeave (2.0 and later). ## DataWeave at a Glance DataWeave is a Mule-specific language that can be used lightly as an expression language to simply reference values and evaluate conditions, or as a scripting language to construct complex data transformations that include functions and recursion. Unlike MEL, it supports different data types out of the box, like JSON, XML, or CSV, which means data no longer needs to be transformed before expressions can be evaluated. It also supports advanced use cases like mapping functions or filtering data. It’s important to notice that the main data selector in DataWeave is the `.` operator. Since it shares most keywords with MEL, the syntax for most scenarios is identical. For example, `#[message.payload.name]` is the same in both languages. The main difference between MEL and DataWeave is that DataWeave expressions have no side effects. You can use DataWeave to extract or generate data but not to modify it. The [Java Integration](https://docs.mulesoft.com/mule-runtime/4.3/intro-java-integration) examples explain how to deal with those use cases. ## MEL Usages The next sections show how to adapt some uses of MEL to Mule 4. ### Accessing Context Variables Except for the following changes, context variables (also called Mule Runtime variables) remain the same in DataWeave:
MELDataWeave

Flow variables

flowVars

  • Example: #[flowVars.myVar]

Mule Event Variables

vars

  • Example: #[vars.myVar]

Exception

exception

Inbound Attachments

message.inboundAttachments

Inbound Properties

message.inboundProperties

  • Examples:

    #[inboundProperties.'http.query.params']
    #[inboundProperties]

Mule Message Attributes (metadata)

attributes

  • Examples:

    #[attributes.queryParams]
    #[attributes.headers]

Outbound Attachments

message.outboundAttachments

Multipart data formats

See:

Outbound Properties

message.outboundProperties

Removed:

message.dataType

dataType

message.id, message.rootId, message.replyTo

Removed

Record Variables

recordVars

  • Example: #[recordVars.myVar]

Mule Event Variables

vars

  • Example: #[vars.myVar]

Session Variables

sessionVars

  • Example: #[sessionVars.myVar]

Removed:

Transport barriers do not exist in Mule 4. See:

server.dateTime

Removed:

Use the DataWeave now function.

### Extracting Data You can use [DataWeave Selectors](https://docs.mulesoft.com/dataweave/2.3/dataweave-selectors) to query data as you did with MEL. Only now, you won’t need extra transformations when dealing with types like JSON. The next examples log the ID from this JSON payload: JSON Payload ```json { "name": "Rachel Duncan", "id": "779H41" } ``` Mule 3 Example ```xml ``` Mule 4 Example ```xml ``` ### Assigning Values As mentioned earlier, DataWeave does not support modifying data in the way the `expression-component` allowed with MEL. To achieve those use cases, you must use the Scripting module. Consider payload described [above](#extract_data) as a Java Map. The examples modify the `name` attribute. Mule 3 Example ```xml ``` Mule 4 Example ```xml payload.put('name', 'R. Duncan') return payload ``` To use the Scripting module, simply add it to your app using the Studio palette, or add the following dependency in your `pom.xml` file: ```xml org.mule.modules mule-scripting-module 1.1.0 mule-plugin ``` ### Invoking Java Methods DataWeave can be used to invoke static methods. For regular methods, you can use the Java module, which exposes both an operation and a function to invoke Java methods. #### Static Methods The following examples use Java’s Locale `getDefault` static method in Mule 3 and 4. Mule 3 example ```xml ``` Mule 4 example ```xml ``` Note that DataWeave requires the `java!` prefix to indicate that a Java static method is to be searched, and it requires the fully qualified Class name (separated by `::` instead of `.`). #### Instance Methods The following examples show the usage of Java’s String `equalsIgnoreCase` method in Mule 3 and 4. Mule 3 example ```xml ``` Mule 4 example ```xml ``` To use the Java module, simply add it to your app using the Studio palette, or add the following dependency to your `pom.xml` file: ```xml org.mule.modules mule-java-module 1.0.0 mule-plugin ``` ### Target Definitions The `enricher` has been removed and replaced by target variables, which are now supported by every operation. The example below shows how to send the result of an operation to a variable in Mule 3 and 4. Mule 3 example ```xml ``` Mule 4 example ```xml ``` - See [Enriching Data with Target Variables](https://docs.mulesoft.com/mule-runtime/4.3/target-variables) for more details. ### XPath Function DataWeave can be used to query XML content using its [selectors](https://docs.mulesoft.com/dataweave/2.3/dataweave-selectors), but you can also use the XML module, which exposes both an operation and a function to execute XPath queries. The following examples show how to take lines containing a specific word taken from a variable in Mule 3 and 4. Mule 3 example ```xml xpath3('//LINE[contains(.,$word)]',payload,'NODESET') ``` Mule 4 example ```xml ``` To use the XML module, simply add it to your app using the Studio palette, or add the following dependency to your `pom.xml` file: ```xml org.mule.modules mule-xml-module 1.1.0 mule-plugin ``` ### Wildcard and Regex functions DataWeave matching functions `match` and `matches` (see Core DataWeave Functions) can be used instead. The next example shows how a regex is used in DataWeave to replace the use of the `wildcard` MEL function. Mule 3 example ```xml ``` Mule 4 example ```xml ``` ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) [Why DataWeave is the Main Expression Language in Mule 4 Beta](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/why-dataweave-main-expression-language-mule-4/) --- product: Mule Runtime version: 4.4 --- # Migrating MEL to DataWeave > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, the DataWeave expression language replaces Mule Expression Language (MEL). This section provides guidance on migrating MEL expressions in your Mule apps to DataWeave (2.0 and later). ## DataWeave at a Glance DataWeave is a Mule-specific language that can be used lightly as an expression language to simply reference values and evaluate conditions, or as a scripting language to construct complex data transformations that include functions and recursion. Unlike MEL, it supports different data types out of the box, like JSON, XML, or CSV, which means data no longer needs to be transformed before expressions can be evaluated. It also supports advanced use cases like mapping functions or filtering data. It’s important to notice that the main data selector in DataWeave is the `.` operator. Since it shares most keywords with MEL, the syntax for most scenarios is identical. For example, `#[message.payload.name]` is the same in both languages. The main difference between MEL and DataWeave is that DataWeave expressions have no side effects. You can use DataWeave to extract or generate data but not to modify it. The [Java Integration](https://docs.mulesoft.com/mule-runtime/4.4/intro-java-integration) examples explain how to deal with those use cases. ## MEL Usages The next sections show how to adapt some uses of MEL to Mule 4. ### Accessing Context Variables Except for the following changes, context variables (also called Mule Runtime variables) remain the same in DataWeave:
MELDataWeave

Flow variables

flowVars

  • Example: #[flowVars.myVar]

Mule Event Variables

vars

  • Example: #[vars.myVar]

Exception

exception

Inbound Attachments

message.inboundAttachments

Inbound Properties

message.inboundProperties

  • Examples:

#[inboundProperties.'http.query.params']
#[inboundProperties]

Mule Message Attributes (metadata)

attributes

  • Examples:

#[attributes.queryParams]
#[attributes.headers]

Outbound Attachments

message.outboundAttachments

Multipart data formats

See:

Outbound Properties

message.outboundProperties

Removed:

See:

message.dataType

dataType

message.id, message.rootId, message.replyTo

Removed

Record Variables

recordVars

  • Example: #[recordVars.myVar]

Mule Event Variables

vars

  • Example: #[vars.myVar]

Session Variables

sessionVars

  • Example: #[sessionVars.myVar]

Removed:

Transport barriers do not exist in Mule 4. See:

server.dateTime

Removed:

Use the DataWeave now function.

### Extracting Data You can use [DataWeave Selectors](https://docs.mulesoft.com/dataweave/latest/dataweave-selectors) to query data as you did with MEL. Only now, you won’t need extra transformations when dealing with types like JSON. The next examples log the ID from this JSON payload: JSON Payload ```json { "name": "Rachel Duncan", "id": "779H41" } ``` Mule 3 Example ```xml ``` Mule 4 Example ```xml ``` ### Assigning Values As mentioned earlier, DataWeave does not support modifying data in the way the `expression-component` allowed with MEL. To achieve those use cases, you must use the Scripting module. Consider payload described [above](#extract_data) as a Java Map. The examples modify the `name` attribute. Mule 3 Example ```xml ``` Mule 4 Example ```xml payload.put('name', 'R. Duncan') return payload ``` To use the Scripting module, simply add it to your app using the Studio palette, or add the following dependency in your `pom.xml` file: ```xml org.mule.modules mule-scripting-module 1.1.0 mule-plugin ``` ### Invoking Java Methods DataWeave can be used to invoke static methods. For regular methods, you can use the Java module, which exposes both an operation and a function to invoke Java methods. #### Static Methods The following examples use Java’s Locale `getDefault` static method in Mule 3 and 4. Mule 3 example ```xml ``` Mule 4 example ```xml ``` Note that DataWeave requires the `java!` prefix to indicate that a Java static method is to be searched, and it requires the fully qualified Class name (separated by `::` instead of `.`). #### Instance Methods The following examples show the usage of Java’s String `equalsIgnoreCase` method in Mule 3 and 4. Mule 3 example ```xml ``` Mule 4 example ```xml ``` To use the Java module, simply add it to your app using the Studio palette, or add the following dependency to your `pom.xml` file: ```xml org.mule.modules mule-java-module 1.0.0 mule-plugin ``` ### Target Definitions The `enricher` has been removed and replaced by target variables, which are now supported by every operation. The example below shows how to send the result of an operation to a variable in Mule 3 and 4. Mule 3 example ```xml ``` Mule 4 example ```xml ``` - See:[Enriching Data with Target Variables](https://docs.mulesoft.com/mule-runtime/4.4/target-variables) for more details. ### XPath Function DataWeave can be used to query XML content using its [selectors](https://docs.mulesoft.com/dataweave/latest/dataweave-selectors), but you can also use the XML module, which exposes both an operation and a function to execute XPath queries. The following examples show how to take lines containing a specific word taken from a variable in Mule 3 and 4. Mule 3 example ```xml xpath3('//LINE[contains(.,$word)]',payload,'NODESET') ``` Mule 4 example ```xml ``` To use the XML module, simply add it to your app using the Studio palette, or add the following dependency to your `pom.xml` file: ```xml org.mule.modules mule-xml-module 1.1.0 mule-plugin ``` ### Wildcard and Regex functions DataWeave matching functions `match` and `matches` (see Core DataWeave Functions) can be used instead. The next example shows how a regex is used in DataWeave to replace the use of the `wildcard` MEL function. Mule 3 example ```xml ``` Mule 4 example ```xml ``` ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) [Why DataWeave is the Main Expression Language in Mule 4 Beta](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/why-dataweave-main-expression-language-mule-4/) --- product: Mule Runtime version: 4.3 --- # Migrating Message Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 3, there are several property scopes that you can use for different purposes. In Mule 4, most of these scopes have been removed. ## Invocation Properties Invocation properties are now called `variables` in Mule 4. Their behavior is exactly the same as in Mule 3. ## Inbound Properties, Outbound Properties, Inbound and Outbound Attachments These scopes do not exist in Mule 4. See [Intro Mule Message](https://docs.mulesoft.com/mule-runtime/4.3/intro-mule-message) for more information about migration. ## See Also [Introduction to Mule 4: The Mule Message](https://docs.mulesoft.com/mule-runtime/4.3/intro-mule-message) [Mule Events](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-event) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-message) [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-variables) --- product: Mule Runtime version: 4.4 --- # Migrating Message Properties > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 3, there are several property scopes that you can use for different purposes. In Mule 4, most of these scopes have been removed. ## Invocation Properties Invocation properties are now called `variables` in Mule 4. Their behavior is exactly the same as in Mule 3. ## Inbound Properties, Outbound Properties, Inbound and Outbound Attachments These scopes do not exist in Mule 4. See [Intro Mule Message](https://docs.mulesoft.com/mule-runtime/4.4/intro-mule-message) for more information about migration. ## See Also [Introduction to Mule 4: The Mule Message](https://docs.mulesoft.com/mule-runtime/4.4/intro-mule-message) [Mule Events](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-event) [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-message) [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-variables) --- product: Mule Runtime version: 4.3 --- # Migrating Reconnection Strategies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt From a syntax point of view, reconnection hasn’t changed much between Mule 3 and Mule 4. However, there are significant behavior differences. In Mule 3, reconnection strategies were specified on each connector’s config element. These strategies had two purposes: - To reconnect when a running application loses connection to an endpoint - To validate all connections when the application is being deployed. So, suppose an application which connects to a mysql Database. If that connection cannot be established at deployment time, the deployment will fail. This was to guarantee that all deployed apps are in a functioning state. Mule 3 Examples: Reconnection Settings (for a MySQL database) ```xml ` ` ``` However, there are use cases in which you don’t necessarily want the deployment to fail if connectivity fails. For example, your application might have a flow that reaches an external SFTP server only once a day at 3:00 AM. If the app is being deployed at 8:00 AM, there’s no reason for the deployment to fail if the SFTP server is down. You still have all day to make sure the server is up when it’s actually needed. To achieve this with Mule 3, you had to use the `blocking="false"` option, so that reconnection happens asynchronously and deployment is not aborted. Mule 3 Examples: Asynchronous reconnection Settings (for a MySQL database) ```xml ` ``` In Mule 4 you can simply specify if deployment should fail or not if connectivity testing fails: Mule 4 Examples: Reconnection Settings (for a SQL database) ```xml ``` By default, a failure to establish connection will only generate a warning in the logs. ## Operation level reconnection strategy In Mule 3, the same reconnection strategy at the config element was used both at deployment time and at runtime. For example, if connectivity to the Database is lost which executing a flow, the same reconnection strategy will be used. In Mule 4 this behavior is kept by default, but you also get the chance to specify a different strategy at the operation or Message Source level: Mule 4 Examples: Reconnection Settings (for an HTTP request) ```xml #[{'my': 'map'}] #[{{'content-type' : 'text/plain'}}] ``` ## See Also - [Migrating Connectors](https://docs.mulesoft.com/mule-runtime/4.3/migration-connectors) --- product: Mule Runtime version: 4.4 --- # Migrating Reconnection Strategies > For the full documentation index, see: https://docs.mulesoft.com/llms.txt From a syntax point of view, reconnection hasn’t changed much between Mule 3 and Mule 4. However, there are significant behavior differences. In Mule 3, reconnection strategies were specified on each connector’s config element. These strategies had two purposes: - To reconnect when a running application loses connection to an endpoint - To validate all connections when the application is being deployed. So, suppose an application which connects to a mysql Database. If that connection cannot be established at deployment time, the deployment will fail. This was to guarantee that all deployed apps are in a functioning state. Mule 3 Examples: Reconnection Settings (for a MySQL database) ```xml ` ` ``` However, there are use cases in which you don’t necessarily want the deployment to fail if connectivity fails. For example, your application might have a flow that reaches an external SFTP server only once a day at 3:00 AM. If the app is being deployed at 8:00 AM, there’s no reason for the deployment to fail if the SFTP server is down. You still have all day to make sure the server is up when it’s actually needed. To achieve this with Mule 3, you had to use the `blocking="false"` option, so that reconnection happens asynchronously and deployment is not aborted. Mule 3 Examples: Asynchronous reconnection Settings (for a MySQL database) ```xml ` ``` In Mule 4 you can simply specify if deployment should fail or not if connectivity testing fails: Mule 4 Examples: Reconnection Settings (for a SQL database) ```xml ``` By default, a failure to establish connection will only generate a warning in the logs. ## Operation level reconnection strategy In Mule 3, the same reconnection strategy at the config element was used both at deployment time and at runtime. For example, if connectivity to the Database is lost which executing a flow, the same reconnection strategy will be used. In Mule 4 this behavior is kept by default, but you also get the chance to specify a different strategy at the operation or event source level: Mule 4 Examples: Reconnection Settings (for an HTTP request) ```xml #[{'my': 'map'}] #[{{'content-type' : 'text/plain'}}] ``` ## See Also - [Migrating Connectors](https://docs.mulesoft.com/mule-runtime/4.4/migration-connectors) --- product: Mule Runtime version: 4.3 --- # Migrating Splitter/Aggregator > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Splitters are not longer available in Mule 4. To process a collection of elements sequentially, use the [For Each component](https://docs.mulesoft.com/mule-runtime/4.3/for-each-scope-concept). [Aggregators](https://docs.mulesoft.com/aggregators-module/latest/) remain in Mule 4 but as a separate module with very different behavior. ## Splitters The main difference between Mule 3 splitters and the Mule 4 For Each component is that the `foreach` element is a scope, meaning that the components used to process the iterated elements must be defined within `foreach`. Mule 3 Example ```xml ... ... ``` Mule 4 Example ```xml ... ... ``` Also, the `foreach` element does not return a collection with the results of all the processed values. Instead, it returns the same collection received as input. So, the behavior of previous examples is not the same. It does not matter if a Mule 3 aggregator is present. To store the results of the processed values, you need to use a Mule 4 aggregator. ### Simple Migration The default format of the migration should be: Mule 3 Example ```xml ... ... ``` Mule 4 Example ```xml ... ... ``` In the example: - A variable `collection-splitter0-group-size` should be created to store the size of the collection. This is needed because inside the `foreach` scope, the payload will correspond to the element from the collection being processed. - Every component between the `collection-splitter` and `collection-aggregator` is wrapped inside a `foreach` scope. - A `group-based-aggregator` is added at the end of the `foreach` scope to store all the results. The size of the aggregation expected will correspond to the value stored in the `collection-splitter0-group-size` variable. `set-variable` is added inside the `aggregation-complete` to store the result of the aggregation once it is complete. - Since the payload after the `foreach` element will be the same as the input received, `set-payload` should be used to set it as the stored value in the variable defined insider the `aggregation-complete` route. ### Complex Migration In some cases, the Mule 3 configuration with splitters and aggregators might set more parameters, so the migration will be a bit more complicated to achieve the Mule 3 behavior in Mule 4. Mule 3 aggregators allowed for 2 attributes to be configured: `timeout` and `failOnTimeout`. If the `timeout` attribute is present (with a value greater than 0), the migration should be as follows in the examples. > [!IMPORTANT] Even when there is a way of adding extra logic when there is a timed-out aggregation > and `failOnTimeout` is set to `true`, the behavior will not be the same as in Mule 3. Aggregators > in Mule 4 do not raise any errors or dispatch any notifications where there is a timed-out > aggregation. Mule 3 Example ```xml ... ... ``` Mule 4 example ```xml ... ... ... ``` In the example: - A variable `collection-splitter0-group-size` should be created to store the size of the collection. This is needed because inside the `foreach` scope, the payload will correspond to the element from the collection being processed. - Another variable `collection-splitter0-aggregator-complete-aggregation` should be created if there is a need for storing an indication of whether or not the aggregation terminated due to a timeout or a complete processing. - Every component between the `collection-splitter` and `collection-aggregator` is wrapped inside a `foreach` scope. - A `group-based-aggregator` is added at the end of the `foreach` scope to store all the results. The expected size of the aggregation will correspond to the value stored in the `collection-splitter0-group-size` variable. The timeout for the aggregation should be set to the timeout that the Mule 3 aggregator contained. `set-variable` is added inside the `aggregation-complete` to set that the aggregation was complete. (That route is only executed with a complete aggregation). Another flow should be created and an `aggregator:aggregator-listener` should be added as source. All aggregations (complete or not) will trigger that listener. Then, they will be sent to the main flow via a `vm:publish` operation. - A `vm:consume` operation is added after the `foreach` element to wait for the aggregation. Once a value is read, the flow will continue with its execution. - Because the `collection-splitter0-aggregator-complete-aggregation` will only be set to true if the aggregation completes, additional logic can be added to check the value of that variable (with `choice` and `when`). This can simulate logic that was previously added in a Mule 3 error handler for when a timeout error was received. ### Additional Attributes All splitters allowed for the configuration of the `enableCorrelation` attribute. There is no way to migrate an `enableCorrelation="NEVER"` configuration. A correlation ID will always be set to the events processed from the collection by the `foreach` element. Expression splitters (``) allowed for the configuration of two attributes: `evaluator` and `custom-evaluator`. Expression evaluators can’t be configured anymore; only DataWeave can be used. ### Available Splitters Migration Mule 3 had the following splitters, some of which require some extra logic to be migrated or cannot be migrated at all. - `collection-splitter`: As defined in the main example. - `custom-splitter`: The use of custom classes is not allowed in Mule 4 anymore so this splitter can’t be migrated. - `splitter` (expression splitter) : The expression used should be set as the `collection` attribute for the `foreach` element. - Mule 3: `` - Mule 4: `` - `map-splitter` : The DataWeave expression `#[dw::core::Objects::entrySet(payload)]` should be used as the `collection` attribute in the `foreach` element. - Mule 3: `` - Mule 4: `` - `message-chunk-splitter`: There is no similar behavior in Mule 4. It cannot be migrated. ### Aggregators Most parameters allowed by Mule 3 aggregators are not allowed in Mule 4: - `timeout`: Though the timeout parameter can be set in any new aggregator, there are some differences. First, `timeoutUnit` should also be set to specify the unit of time. Also, the behavior of aggregation timeouts is very different in a Mule 4 aggregator. This is explained in [Aggregators Module Reference](https://docs.mulesoft.com/aggregators-module/latest/aggregators-module-reference). - `failOnTimeout`: No longer available. However similar behavior can be achieved, as explained in the [Complex Migration](#complex_migration). - `processed-groups-object-store-ref`: Processed groups are no longer stored in a separate object store. This paremeter is not allowed anymore. - `event-groups-object-store-ref`: You can set this object store using the `objectStore` attribute in Mule 4 aggregators. - `persistentStores`: Not allowed anymore. If a persistent object store is needed, the `objectStore` attribute should be the name of a persistent object store. - `storePrefix`: Not allowed anymore. ### Available Aggregators Migration - `collection-aggregator`: Should be migrated as defined in the main example. - `custom-aggregator`: Cannot be migrated. There is no way in Mule 4 to add custom implementations for an interface. - `message-chunk-aggregator`: There is no similar behavior in Mule 4. It cannot be migrated. ## See Also [Aggregators Module](https://docs.mulesoft.com/aggregators-module/latest/) [For Each Scope](https://docs.mulesoft.com/mule-runtime/4.3/for-each-scope-concept) [For Each Scope Reference](https://docs.mulesoft.com/mule-runtime/4.3/for-each-scope-concept) --- product: Mule Runtime version: 4.4 --- # Migrating Splitter/Aggregator > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Splitters are not longer available in Mule 4. To process a collection of elements sequentially, use the [For Each component](https://docs.mulesoft.com/mule-runtime/4.4/for-each-scope-concept). [Aggregators](https://docs.mulesoft.com/aggregators-module/latest/) remain in Mule 4 but as a separate module with very different behavior. ## Splitters The main difference between Mule 3 splitters and the Mule 4 For Each component is that the `foreach` element is a scope, meaning that the components used to process the iterated elements must be defined within `foreach`. Mule 3 Example ```xml ... ... ``` Mule 4 Example ```xml ... ... ``` Also, the `foreach` element does not return a collection with the results of all the processed values. Instead, it returns the same collection received as input. So, the behavior of previous examples is not the same. It does not matter if a Mule 3 aggregator is present. To store the results of the processed values, you need to use a Mule 4 aggregator. ### Simple Migration The default format of the migration should be: Mule 3 Example ```xml ... ... ``` Mule 4 Example ```xml ... ... ``` In the example: - A variable `collection-splitter0-group-size` should be created to store the size of the collection. This is needed because inside the `foreach` scope, the payload will correspond to the element from the collection being processed. - Every component between the `collection-splitter` and `collection-aggregator` is wrapped inside a `foreach` scope. - A `group-based-aggregator` is added at the end of the `foreach` scope to store all the results. The size of the aggregation expected will correspond to the value stored in the `collection-splitter0-group-size` variable. `set-variable` is added inside the `aggregation-complete` to store the result of the aggregation once it is complete. - Since the payload after the `foreach` element will be the same as the input received, `set-payload` should be used to set it as the stored value in the variable defined insider the `aggregation-complete` route. ### Complex Migration In some cases, the Mule 3 configuration with splitters and aggregators might set more parameters, so the migration will be a bit more complicated to achieve the Mule 3 behavior in Mule 4. Mule 3 aggregators allowed for 2 attributes to be configured: `timeout` and `failOnTimeout`. If the `timeout` attribute is present (with a value greater than 0), the migration should be as follows in the examples. > [!IMPORTANT] Even when there is a way of adding extra logic when there is a timed-out aggregation > and `failOnTimeout` is set to `true`, the behavior will not be the same as in Mule 3. Aggregators > in Mule 4 do not raise any errors or dispatch any notifications where there is a timed-out > aggregation. Mule 3 Example ```xml ... ... ``` Mule 4 example ```xml ... ... ... ``` In the example: - A variable `collection-splitter0-group-size` should be created to store the size of the collection. This is needed because inside the `foreach` scope, the payload will correspond to the element from the collection being processed. - Another variable `collection-splitter0-aggregator-complete-aggregation` should be created if there is a need for storing an indication of whether or not the aggregation terminated due to a timeout or a complete processing. - Every component between the `collection-splitter` and `collection-aggregator` is wrapped inside a `foreach` scope. - A `group-based-aggregator` is added at the end of the `foreach` scope to store all the results. The expected size of the aggregation will correspond to the value stored in the `collection-splitter0-group-size` variable. The timeout for the aggregation should be set to the timeout that the Mule 3 aggregator contained. `set-variable` is added inside the `aggregation-complete` to set that the aggregation was complete. (That route is only executed with a complete aggregation). Another flow should be created and an `aggregator:aggregator-listener` should be added as source. All aggregations (complete or not) will trigger that listener. Then, they will be sent to the main flow via a `vm:publish` operation. - A `vm:consume` operation is added after the `foreach` element to wait for the aggregation. Once a value is read, the flow will continue with its execution. - Because the `collection-splitter0-aggregator-complete-aggregation` will only be set to true if the aggregation completes, additional logic can be added to check the value of that variable (with `choice` and `when`). This can simulate logic that was previously added in a Mule 3 error handler for when a timeout error was received. ### Additional Attributes All splitters allowed for the configuration of the `enableCorrelation` attribute. There is no way to migrate an `enableCorrelation="NEVER"` configuration. A correlation ID will always be set to the events processed from the collection by the `foreach` element. Expression splitters (``) allowed for the configuration of two attributes: `evaluator` and `custom-evaluator`. Expression evaluators can’t be configured anymore; only DataWeave can be used. ### Available Splitters Migration Mule 3 had the following splitters, some of which require some extra logic to be migrated or cannot be migrated at all. - `collection-splitter`: As defined in the main example. - `custom-splitter`: The use of custom classes is not allowed in Mule 4 anymore so this splitter can’t be migrated. - `splitter` (expression splitter) : The expression used should be set as the `collection` attribute for the `foreach` element. - Mule 3: `` - Mule 4: `` - `map-splitter` : The DataWeave expression `#[dw::core::Objects::entrySet(payload)]` should be used as the `collection` attribute in the `foreach` element. - Mule 3: `` - Mule 4: `` - `message-chunk-splitter`: There is no similar behavior in Mule 4. It cannot be migrated. ### Aggregators Most parameters allowed by Mule 3 aggregators are not allowed in Mule 4: - `timeout`: Though the timeout parameter can be set in any new aggregator, there are some differences. First, `timeoutUnit` should also be set to specify the unit of time. Also, the behavior of aggregation timeouts is very different in a Mule 4 aggregator. This is explained in [Aggregators Module Reference](https://docs.mulesoft.com/aggregators-module/latest/aggregators-module-reference). - `failOnTimeout`: No longer available. However similar behavior can be achieved, as explained in the [Complex Migration](#complex_migration). - `processed-groups-object-store-ref`: Processed groups are no longer stored in a separate object store. This paremeter is not allowed anymore. - `event-groups-object-store-ref`: You can set this object store using the `objectStore` attribute in Mule 4 aggregators. - `persistentStores`: Not allowed anymore. If a persistent object store is needed, the `objectStore` attribute should be the name of a persistent object store. - `storePrefix`: Not allowed anymore. ### Available Aggregators Migration - `collection-aggregator`: Should be migrated as defined in the main example. - `custom-aggregator`: Cannot be migrated. There is no way in Mule 4 to add custom implementations for an interface. - `message-chunk-aggregator`: There is no similar behavior in Mule 4. It cannot be migrated. ## See Also [Aggregators Module](https://docs.mulesoft.com/aggregators-module/latest/) [For Each Scope](https://docs.mulesoft.com/mule-runtime/4.4/for-each-scope-concept) [For Each Scope Reference](https://docs.mulesoft.com/mule-runtime/4.4/for-each-scope-concept) --- product: Mule Runtime version: 4.3 --- # Migrating Test Structure (MUnit) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The MUnit test is divided into three scopes. All of them are optional:
ScopeDescription

Behavior

The behavior scope (<munit:behavior/>) is intended for setting the preconditions before executing the test logic.
Mocks and Spies go in this section.

Execution

The execution scope (<munit:execution/>) is meant to have the testing logic which will wait for all processes to finish before executing the next scope.

Validation

The validation scope (<munit:validation/>) is meant to have all the validations regarding the result of the execution scope.
Assertions and Verifications go in the validation scope.

The following examples compare MUnit tests in 1.x to 2.x. Test in MUnit 1.x ```xml ``` Test in MUnit 2.x ```xml ``` ## See Also - [MUnit 2 Test structure](https://docs.mulesoft.com/munit/latest/munit-test-concept) --- product: Mule Runtime version: 4.4 --- # Migrating Test Structure (MUnit) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The MUnit test is divided into three scopes. All of them are optional:
ScopeDescription

Behavior

The behavior scope (<munit:behavior/>) is intended for setting the preconditions before executing the test logic.
Mocks and Spies go in this section.

Execution

The execution scope (<munit:execution/>) is meant to have the testing logic which will wait for all processes to finish before executing the next scope.

Validation

The validation scope (<munit:validation/>) is meant to have all the validations regarding the result of the execution scope.
Assertions and Verifications go in the validation scope.

The following examples compare MUnit tests in 1.x to 2.x. Test in MUnit 1.x ```xml ``` Test in MUnit 2.x ```xml ``` ## See Also - [MUnit 2 Test structure](https://docs.mulesoft.com/munit/latest/munit-test-concept) --- product: Mule Runtime version: 4.3 --- # Migrating the Anypoint Enterprise Security (AES) features > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, the Anypoint Enterprise Security module was split into different modules: - [Cryptography Module](https://docs.mulesoft.com/mule-runtime/4.3/securing#cryptography-module) replaces the Mule 3 Encryption and Signature modules - [Secure Configuration Properties Module](https://docs.mulesoft.com/mule-runtime/4.3/secure-configuration-properties) replaces the Mule 3 Secure Property Placeholder - [Validation Module](https://docs.mulesoft.com/validation-connector/latest/) incorporated functionality from the Mule 3 Filters Module - [OAuth2 Provider](https://docs.mulesoft.com/oauth2-provider-module/latest/oauth2-provider-module-reference) replaces the Mule 3 OAuth2 Provider Please refer to the above modules documentation for information on how to migrate to Mule 4. --- product: Mule Runtime version: 4.4 --- # Migrating the Anypoint Enterprise Security (AES) features > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 4, the Anypoint Enterprise Security module was split into different modules: - [Cryptography Module](https://docs.mulesoft.com/mule-runtime/4.4/securing#cryptography-module) replaces the Mule 3 Encryption and Signature modules - [Secure Configuration Properties Module](https://docs.mulesoft.com/mule-runtime/4.4/secure-configuration-properties) replaces the Mule 3 Secure Property Placeholder - [Validation Module](https://docs.mulesoft.com/validation-connector/latest/) incorporated functionality from the Mule 3 Filters Module - [OAuth2 Provider](https://docs.mulesoft.com/oauth2-provider-module/latest/oauth2-provider-module-reference) replaces the Mule 3 OAuth2 Provider Please refer to the above modules documentation for information on how to migrate to Mule 4. --- product: Mule Runtime version: 4.3 --- # Migrating the Batch Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Batch module was introduced to handle Extract Transform Load (ETL) functionality. What’s covered in this section: - [Migrating the Batch Element](#batch_scope) - [Migrating Record Vars to Vars](#record_var) - [Support for Non-Java DataSets](#non_java_datasets) - [XML Changes to Batch Elements and Attributes for Mule 4](#xml_changes) ## Migrating the Batch Element In Mule 3, Batch was a top-level element, at the same level as a flow. In Mule 4, the `` element is a scope that lives inside a flow so that it is easier to understand, invoke dynamically, and interact with other Mule components. This also means that there is no `` anymore. The role of the `` is now accomplished by whatever set of processors are in the flow before the `` is triggered. - ``: Even though Batch is a scope, it has a name. No Mule app can have two `` definitions with the same name. This allows better tracking and management when one single flow defines more than one job - ``: This operation does not exist anymore. Instead, just invoke whatever flow contains the bach job. Mule 3 example ```xml <> > ``` Mule 4 example ```xml ``` ## Migrating Record Vars to Vars Unlike a regular flow, Batch processes at the record level instead of message level. In Mule 3, you use record-level variables (`recordVars`) to attach variables to a particular record, just like you use Flow variables (`flowVars`) for the Mule message. In Mule 4, variables (`vars`) replace `recordVars`. Variables are part of the Mule event in Mule 4. From within the ``, you can modify a variable that existed before the `` began executing, and you can do it for one particular record, without side effects on the other ones. The Mule 3 example here uses `recordVars` within an expression in a For Each component: Mule 3 Example ```xml record.payload = 'foo'; record.recordVars['marco'] = 'polo'; ``` The Mule 4 example here uses `vars` within an expression in a For Each component: Mule 4 Example ```xml vars['marco'] = 'polo' vars['record'].payload = 'foo' ``` ## Support for Non-Java DataSets In Mule 3, the batch input phase required a Java structure. So, for input data in formats such as XML or JSON, you first needed to transform to Java, then make DataWeave use streaming in that transformation to avoid running out of memory for large datasets. For example, suppose you have this source data pushed to your app through an HTTP call: Example: JSON Input Data \[ { "name": "Luke Skywalker", "darkSide": true }, { "name": "Ben Solo", "darkSide": true }, { "name": "Obi-Wan Kenobi", "darkSide": false } \] In Mule 3, you need to transform that JSON to Java before passing it over, something like this: Mule 3 Example ```xml <> <> ..... ``` In Mule 4, Batch can automatically determine that the payload is a JSON array and perform the splitting on its own, for example: Mule 4 Example ```xml .... ``` You no longer have to set streaming in Mule 4 because of the automatic streaming framework it uses. So, when you migrate to Mule 4, you can avoid a transformation step. ## XML Changes to Batch Elements and Attributes for Mule 4 - Camel Case attributes: Following the Mule 4 DSL guidelines, and in order to improve consistency, all DSL attributes have been changed to camel case. For example, `max-failed-records` is now `maxFailedRecords`, `accept-policy` is `acceptPolicy`, and so on. - MuleSoft removed the `filter-expression` parameter from the `` ` `` element. This attribute was deprecated in Mule 3.6 and should be replaced with `accept-expression` parameter. - The `` is now called ``. ## See Also - [Batch Processors](https://docs.mulesoft.com/mule-runtime/4.3/batch-processing-concept) --- product: Mule Runtime version: 4.4 --- # Migrating the Batch Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Batch module was introduced to handle Extract Transform Load (ETL) functionality. What’s covered in this section: - [Migrating the Batch Element](#batch_scope) - [Migrating Record Vars to Vars](#record_var) - [Support for Non-Java DataSets](#non_java_datasets) - [XML Changes to Batch Elements and Attributes for Mule 4](#xml_changes) ## Migrating the Batch Element In Mule 3, Batch was a top-level element, at the same level as a flow. In Mule 4, the `` element is a scope that lives inside a flow so that it is easier to understand, invoke dynamically, and interact with other Mule components. This also means that there is no `` anymore. The role of the `` is now accomplished by whatever set of processors are in the flow before the `` is triggered. - ``: Even though Batch is a scope, it has a name. No Mule app can have two `` definitions with the same name. This allows better tracking and management when one single flow defines more than one job - ``: This operation does not exist anymore. Instead, just invoke whatever flow contains the bach job. Mule 3 example ```xml <> > ``` Mule 4 example ```xml ``` ## Migrating Record Vars to Vars Unlike a regular flow, Batch processes at the record level instead of message level. In Mule 3, you use record-level variables (`recordVars`) to attach variables to a particular record, just like you use Flow variables (`flowVars`) for the Mule message. In Mule 4, variables (`vars`) replace `recordVars`. Variables are part of the Mule event in Mule 4. From within the ``, you can modify a variable that existed before the `` began executing, and you can do it for one particular record, without side effects on the other ones. The Mule 3 example here uses `recordVars` within an expression in a For Each component: Mule 3 Example ```xml record.payload = 'foo'; record.recordVars['marco'] = 'polo'; ``` The Mule 4 example here uses `vars` within an expression in a For Each component: Mule 4 Example ```xml vars['marco'] = 'polo' vars['record'].payload = 'foo' ``` ## Support for Non-Java DataSets In Mule 3, the batch input phase required a Java structure. So, for input data in formats such as XML or JSON, you first needed to transform to Java, then make DataWeave use streaming in that transformation to avoid running out of memory for large datasets. For example, suppose you have this source data pushed to your app through an HTTP call: Example: JSON Input Data \[ { "name": "Luke Skywalker", "darkSide": true }, { "name": "Ben Solo", "darkSide": true }, { "name": "Obi-Wan Kenobi", "darkSide": false } \] In Mule 3, you need to transform that JSON to Java before passing it over, something like this: Mule 3 Example ```xml <> <> ..... ``` In Mule 4, Batch can automatically determine that the payload is a JSON array and perform the splitting on its own, for example: Mule 4 Example ```xml .... ``` You no longer have to set streaming in Mule 4 because of the automatic streaming framework it uses. So, when you migrate to Mule 4, you can avoid a transformation step. ## XML Changes to Batch Elements and Attributes for Mule 4 - Camel Case attributes: Following the Mule 4 DSL guidelines, and in order to improve consistency, all DSL attributes have been changed to camel case. For example, `max-failed-records` is now `maxFailedRecords`, `accept-policy` is `acceptPolicy`, and so on. - MuleSoft removed the `filter-expression` parameter from the `` ` `` element. This attribute was deprecated in Mule 3.6 and should be replaced with `accept-expression` parameter. - The `` is now called ``. ## See Also - [Batch Processors](https://docs.mulesoft.com/mule-runtime/4.4/batch-processing-concept) --- product: Mule Runtime version: 4.3 --- # Migrating the Choice Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Little changed between Choice router for Mule 3 and Mule 4 except for: - DataWeave is now the expression language so the when statements are actually going to use it instead of MEL - The `` block is now optional ## Expression Language for the When Block The when expressions need to be changed from MEL to DataWeave. This also mean that you can leverage DataWeave’s ability to interpret any format to avoid unnecessary convertions. For example, suppose a flow in which a JSON document representing a user is posted through HTTP and you want to check if the person is underage: Mule 3 Example: MEL ```xml ``` With Mule 4, you don’t need to worry about JSON or Java formats and just do: Mule 4 Example: DataWeave 2 ```xml ``` ## Optional Otherwise In Mule 3, the `` block was required. Many times in which fallback logic was not necessary, you ended up with an `` block which just had an insignificant logger. In Mule 4, the `` block is optional and you don’t need to specify it if not necessary. ## See Also [Introduction to Mule 4: Error Handlers](https://docs.mulesoft.com/mule-runtime/4.3/intro-error-handlers) [Migrating from MEL to DataWeave](https://docs.mulesoft.com/mule-runtime/4.3/migration-mel) [Migrating from DataWeave 1.0 to 2.x](https://docs.mulesoft.com/mule-runtime/4.3/migration-dataweave) --- product: Mule Runtime version: 4.4 --- # Migrating the Choice Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Little changed between Choice router for Mule 3 and Mule 4 except for: - DataWeave is now the expression language so the when statements are actually going to use it instead of MEL - The `` block is now optional ## Expression Language for the When Block The when expressions need to be changed from MEL to DataWeave. This also mean that you can leverage DataWeave’s ability to interpret any format to avoid unnecessary convertions. For example, suppose a flow in which a JSON document representing a user is posted through HTTP and you want to check if the person is underage: Mule 3 Example: MEL ```xml ``` With Mule 4, you don’t need to worry about JSON or Java formats and just do: Mule 4 Example: DataWeave 2 ```xml ``` ## Optional Otherwise In Mule 3, the `` block was required. Many times in which fallback logic was not necessary, you ended up with an `` block which just had an insignificant logger. In Mule 4, the `` block is optional and you don’t need to specify it if not necessary. ## See Also [Introduction to Mule 4: Error Handlers](https://docs.mulesoft.com/mule-runtime/4.4/intro-error-handlers) [Migrating from MEL to DataWeave](https://docs.mulesoft.com/mule-runtime/4.4/migration-mel) [Migrating from DataWeave 1.0 to 2.x](https://docs.mulesoft.com/mule-runtime/4.4/migration-dataweave) --- product: Mule Runtime version: 4.3 --- # Migrating the Database Connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The main changes to the Database connector from Mule 3 to Mule 4 include: - All database operations (such as Select, Insert, Update, Delete, and others) have been refactored into separate operations. There are also new, dedicated bulk operations for Mule 4. - Use of DataWeave: Database operations, such as Insert and Update, support DataWeave version 2 transformations. You can construct the data sets that insert or update the database without message side effects, and you no longer use message enrichers. - You can perform dynamic and static queries in similar ways. - The Mule streaming framework is automatically configured for your operations. You can execute a select statement and process the results asynchronously without worrying about leaking connections. ## What’s Covered Here? - [Database Connection Configurations](#database_configuration) - [Data Source Reference](#data_source_ref) - [Examples: Detailed Connector Configurations](#connector_config_detail) - [Migrating Dynamic Queries](#database_dynamic_queries) - [Streaming Large Results](#database_streaming) - [Migrating Bulk Operations](#database_operation_bulk) - [Migrating the Bulk Execute Operation](#database_bulk_execute) - [Transactional Actions](#tx_actions) - [Output Target](#output_target) ## Database Connection Configurations The Database connectors for Mule 3 and Mule 4 support Derby, MySQL, Oracle, and generic database configurations. For Mule 4, Microsoft SQL Server and Data Source Reference connections are also supported. The XML for these connection configurations has changed in Mule 4: - Mule 3: Database elements such as `` are the top-level elements. - Mule 4: `` is the top-level element for all database connection configurations in Mule 4, and specific database configurations are nested under separate `` elements: - Derby: `` - Microsoft SQL Server: `` - MySQL: `` - Oracle: `` - Generic: `` - Data Source Reference Connection: `` Mule 3 Example: Derby Connection Configuration ```xml ``` Notice that `` in the Mule 3 example above changes to `` in the Mule 4 example below, and the attribute for the URL to the database changes from `url` to `database` in Mule 4. The `` child element is new in Mule 4. Mule 4 Examples: Derby Connection Configuration ```xml ``` Also note that in Mule 4, additional `` settings (XML attributes) are available: - `create="true|false"`: Whether to create the database if it does not exist. - `subsubProtocol="directory"`: Type of SubsubProtocol to be used by Derby. The available options are `directory`, `memory`, `classpath` and `jar`. The next section describes connection configurations for other databases. ### Data Source Reference These topics provide Mule 4 XML examples for other database connections and include connector-specific settings: - [Mule 4 Example: Data Source Reference](#example_data_source_db) - [Mule 4 Example: Generic](#example_generic_db) - [Mule 4 Example: Microsoft SQL Server](#example_mssql_db) - [Mule 4 Example: MySQL](#example_mysql_db) - [Mule 4 Example: Oracle JDBC Database](#example_oracle_db) - [Mule 4 Example: Microsoft SQL Server](#example_mssql_db) - [Example: Maven dependency setting for a Microsoft SQL Server driver](#example_driver) Note that the Mule 3 example for Derby in the previous section shows most of the main differences between Mule 3 and Mule 4 for database connection configurations, including My SQL, Oracle, and so on. It also shows the main migration pattern from Mule 3 to Mule 4 database connections: - Derby: [Database Connection Configurations](#database_configuration) #### Mule 4 Example: Data Source Reference To use a Data Source Reference you need to: 1 - Create a XML Spring Beans file creating the Spring Bean representing the `DataSource` datasource-spring-beans.xml ```xml ``` > [!WARNING] Is required to configure the Maven dependency which contains the DataSource > implementation. For this example, `org.enhydra.jdbc.standard.StandardDataSource`, the required > dependency is: > > `` > `com.experlog` > `xapool` > `1.5.0` > `` 2 - Create Data Source Connection
1Import the datasource-spring-beans.xml file using the Mule Spring Module [link to Spring Module]
2Create the DB Config with the DataSource Connection, and add as dataSourceRef the Spring Bean ID of the DataSource Bean created in datasource-spring-beans.xml.
```xml (1) (2) ``` This setting is unique to Data Source Reference: - `dataSourceRef="my_ref_here"`: Reference to a JDBC DataSource object. This object is typically created using Spring. When using XA transactions, an XADataSource object must be provided. #### Mule 4 Example: Generic ```xml ``` These setting are unique to a Generic database: - `url="url_here"` for the JDBC URL to be used to connect to the database. - `driverClassName="driver_class_name_here"` for the fully-qualified name of the database driver class. > [!WARNING] The Maven dependency which contains the Class referenced in the `driverClassName` > parameter should be configured in the Mule Application. > Also, due to new Mule 4 ClassLoading mechanism, this dependency must be declared as a Shared > Library to be exported to the DB Connector. See also, [Database Transactions](#db_transactions). #### Mule 4 Example: Microsoft SQL Server ```xml ``` See also, [Database Transactions](#db_transactions). #### Mule 4 Example: MySQL ```xml ``` See also, [Database Transactions](#db_transactions). #### Mule 4 Example: Oracle JDBC Database ```xml ``` See also, [Database Transactions](#db_transactions). #### Example: Maven dependency setting for a Microsoft SQL Server driver Microsoft SQL Server, MySQL, Derby, Oracle configurations require a driver. ```xml com.microsoft.sqlserver mssql-jdbc 6.2.2.jre8 ``` > [!WARNING] Because of the new Mule 4 ClassLoading mechanism, this dependency must be declared as a > Shared Library to be exported to the DB Connector. Using Studio, this will be automatically > configured. ### Examples: Detailed Connector Configurations In Mule 4, you can add child elements for these settings under the database connection configurations (such as ``): - [Database Transactions](#db_transactions) - [Transactional Actions](#tx_actions) - [Transaction Isolation](#tx_isolation) - [XA Transactions](#xa_tx) - [Connection Properties](#connection_properties) - [Column Types](#column_types) - [Pooling Profile](#pooling_profile) - [Reconnection Strategies](#reconnection_strategies) #### Database Transactions ##### Transaction Isolation Transactions are for the transaction isolation level to set on the driver when connecting the database. - **NOT\_CONFIGURED** (Default) - **READ\_COMMITTED** (`transactionIsolation="READ_COMMITTED"`) - **READ\_UNCOMMITTED** (`transactionIsolation="READ_UNCOMMITTED"`) - **REPEATABLE\_READ** (`transactionIsolation="REPEATABLE_READ"`) - **SERIALIZABLE** (`transactionIsolation="SERIALIZABLE"`) Mule 3 Example: Transaction Isolation ```xml ``` Mule 4 Example: Transaction Isolation ```xml ``` ##### XA Transactions Connections can be configured to work in XA Transactions, in both **Mule 3** and **Mule 4** this can be configured in the connection configuration setting `useXaTransactions="true"` Mule 3 Example: XA Transactions ```xml ``` Mule 4 Example: XA Transactions ```xml ``` #### Connection Properties **MySQL** and **Microsoft SQL Server** database configurations provide connection property settings, these properties are injected to the JDBC Connection as additional properties. Mule 3 Example: Connection Properties ```xml ``` Mule 4 Example: Connection Properties ```xml ``` #### Column Types - Column types (``) for non-standard column types. #### Pooling Profile - Pooling profile (``) for JDBC Data Sources capable of connection pooling connections. It is is almost identical to Connection Pooling in Mule 3. #### Reconnection Strategies Reconnection strategy settings are similar in Mule 3 and Mule 4. However, custom reconnection strategies are not available in Mule 4. The examples below show changes to the XML for these settings: - **None**: Default. Same as Do Not Use A Reconnection Strategy in Mule 3. - **Standard**: Same as Standard Reconnection in Mule 3. Both have the same options: Frequency (ms), Reconnection Attempts - **Forever**: Same as Reconnect Forever in Mule 3. Mule 3 Examples: Reconnection Settings ```xml ` ` ``` Mule 4 Examples: Reconnection Settings ```xml ``` ## Database Connector Operations - Query for SQL query text and input parameters - Streaming strategy settings (as shown here in [Streaming Large Results](#database_streaming)) - [Transactional Actions](#tx_actions) - Query settings - Error mapping for errors, including DB:BAD\_SQL\_SYNTAX, DB:QUERY\_EXECUTION - Mule 4 input and output metadata for attributes, payload, and variables ### Migrating Parameterized Queries In Both **Mule 3** and **Mule 4** input parameters are supplied as key-value pairs. Those keys are used with the semicolon character (:) to reference a parameter value by name, this means that written SQL parameterized queries in **Mule 3** doesn’t need changes to be used in **Mule 4**. This approach is recommended to avoid SQL injection attacks, and it allows the connector to perform optimizations that improve the overall performance of the Mule app. #### Input Parameters - In **Mule 3** each Input Parameter was defined as a `` element inside the `` operation which had an `name` attribute for the parameter name, and a `value` attribute which holds the parameter value. - In **Mule 4**, the input parameters are defined as Map ``, where the key is the name of the parameter, and the value as the parameter value. This map can only be created using DataWeave. Mule 3 Example: Parameterized SELECT Query ```xml SELECT * FROM employees WHERE last_name = :last_name ``` Mule 4 Example: Parameterized SELECT Query ```xml SELECT * FROM employees WHERE last_name = :last_name #[ { last_name : vars.lastName } ] ``` ### Migrating Dynamic Queries Sometimes, you not only need to parameterize the WHERE clause, but also parameterize parts of the query itself. Example use cases for this would be queries which need to hit online/historic tables depending on a condition, or complex queries where the project columns need to vary. In Mule 3, the concept of select was split in parameterized and dynamic queries, and you couldn’t use both at the same time. You had to choose between having a dynamic query or having the advantages of using parameters (SQL Injection protection, PreparedStatement optimization, etc.). Furthermore, the syntax to do one or the other was different, so you had to learn two different ways of doing the same thing. But with the new Database Connector in Mule 4, you can now use both methods at the same time by using expressions in the query: Mule 3 Example: Dynamic SELECT Query ```xml SELECT * FROM #[flowVars.table] WHERE name = #[flowVars.name] ``` Mule 4 Example: Dynamic SELECT Query ```xml #['SELECT * FROM $(vars.table) WHERE name = $(vars.name)'] ``` GOTCHA: The Mule 3 example is less performant and vulnerable to SQL Injection attacks since the entire query is being treated as a string instead of using PreparedStatements ## Streaming Large Results Streaming can handle results queries to big database tables, which might return tens of thousands of records, especially for integration use cases. Streaming is a great solution for this. ### Enabling Streaming In **Mule 3**, streaming is disabled by default, so you have to enable it to use it. In **Mule 4**, streaming is always on but you can configure the strategy through which the runtime will achieve repeatable streaming. For more information on this, please refer to the [streaming documentation page](https://docs.mulesoft.com/mule-runtime/4.3/streaming-about). TIP: Note that disabling repeatable streaming will prevent DataWeave and other components to process the a stream many times, even in parallel. ### Migrating Bulk Operations #### Enabling Bulk Mode In **Mule 3**, you set bulk functionality through a `bulkMode="true"` setting on **Insert, Update, and Delete** operations. In **Mule 4**, you use dedicated Bulk Insert (``), Bulk Update (``), and Bulk Delete (``) database, instead. This means that operations no longer change their behavior depending on the received payload. #### Consuming bulk data In **Mule 3**, in a bulk query, the connector worked similar to the `` component, it took the current payload value, expecting to be a collection of items, and executes the `` expressions with each value of the collection. In **Mule 4**, is slightly different, instead of consuming the payload and executing expressions for each element in a collection, is required to inject a collection of entries. ##### Examples: Mule 3 Example: Select with a Parameterized Query ```xml INSERT INTO customers (id, name, lastName) VALUES (:id, :name, :lastName) ``` Mule 4 Example: Using the Bulk Operation to Get Different Values ```xml INSERT INTO customers (id, name, lastName) VALUES (:id, :name, :lastName) #[[{ id: 2, name: 'George', lastName: 'Costanza' }, { id: 3, name: 'Cosmo', lastName: 'Kramer' }]] ``` ### Migrating the Bulk Execute Operation The `` operation from the Mule 3 connector is replaced by the `` operation. It’s important to note that even though the Mule 3 version uses the word `bulk`, it is not an actual bulk operation as in the examples above. Instead, it executes many individual statements using the same connection, but it does not create bulk prepared statements. So, in Mule 4, the operation is named `execute-script` to better describe what it is doing. Mule 4 Example: Using the `execute-script` operation ```xml update PLANET set NAME='Mercury' where POSITION=0; update PLANET set NAME='Mercury' where POSITION=4 ``` You can also extract the statements to an external file: Mule 4 Example: Using the `execute-script` operation with an external file ```xml ``` ### Transactional Actions When database operations are executed inside a transaction, they can determine how to interact with the transaction. Available Transactional Actions: - **ALWAYS\_JOIN** - **JOIN\_IF\_POSSIBLE** - **NOT\_SUPPORTED** Mule 3 Example: Transactional Action ```xml SELECT * FROM people ``` Mule 4 Example: Transactional Action ```xml SELECT * FROM people ``` ### Output Target In **Mule 3** the DB Connector had the capability of save the execution output in a desired target variable. In **Mule 4**, this can still be done, but with a few differences. In **Mule 3** what was considered as output was just the execution result, so when configuring, for example: `target="#[flowVars.targetVar]"` this meant that the query execution will be saved in the flow variable `targetVar`. In **Mule 4** is very similar, you have a `target` parameter which is the name of the target Flow Variable, this can’t be an expression, and the new parameter in **Mule 4** is `targetValue`, this is an expression that is evaluated against the operation result. For example this can be: `#[payload]`, to save the entire payload, or `#[payload[0]]` to just save the first row of a Select Query. Mule 3 Example: Output Target ```xml SELECT * FROM People ``` Mule 4 Example: Output Target ```xml SELECT * from People ``` To use the Database connector, simply add it to your application using the Studio palette or add the following dependency in your `pom.xml` file: ```xml org.mule.connectors mule-db-connector 1.2.0 mule-plugin ``` ## See Also - [Database Connector Overview](https://docs.mulesoft.com/db-connector/latest/) - [Streaming in Mule 4.0](https://docs.mulesoft.com/mule-runtime/4.3/streaming-about). --- product: Mule Runtime version: 4.4 --- # Migrating the Database Connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The main changes to the Database connector from Mule 3 to Mule 4 include: - All database operations (such as Select, Insert, Update, Delete, and others) have been refactored into separate operations. There are also new, dedicated bulk operations for Mule 4. - Use of DataWeave: Database operations, such as Insert and Update, support DataWeave version 2 transformations. You can construct the data sets that insert or update the database without message side effects, and you no longer use message enrichers. - You can perform dynamic and static queries in similar ways. - The Mule streaming framework is automatically configured for your operations. You can execute a select statement and process the results asynchronously without worrying about leaking connections. ## What’s Covered Here? - [Database Connection Configurations](#database_configuration) - [Data Source Reference](#data_source_ref) - [Examples: Detailed Connector Configurations](#connector_config_detail) - [Migrating Dynamic Queries](#database_dynamic_queries) - [Streaming Large Results](#database_streaming) - [Migrating Bulk Operations](#database_operation_bulk) - [Migrating the Bulk Execute Operation](#database_bulk_execute) - [Transactional Actions](#tx_actions) - [Output Target](#output_target) ## Database Connection Configurations The Database connectors for Mule 3 and Mule 4 support Derby, MySQL, Oracle, and generic database configurations. For Mule 4, Microsoft SQL Server and Data Source Reference connections are also supported. The XML for these connection configurations has changed in Mule 4: - Mule 3: Database elements such as `` are the top-level elements. - Mule 4: `` is the top-level element for all database connection configurations in Mule 4, and specific database configurations are nested under separate `` elements: - Derby: `` - Microsoft SQL Server: `` - MySQL: `` - Oracle: `` - Generic: `` - Data Source Reference Connection: `` Mule 3 Example: Derby Connection Configuration ```xml ``` Notice that `` in the Mule 3 example above changes to `` in the Mule 4 example below, and the attribute for the URL to the database changes from `url` to `database` in Mule 4. The `` child element is new in Mule 4. Mule 4 Examples: Derby Connection Configuration ```xml ``` Also note that in Mule 4, additional `` settings (XML attributes) are available: - `create="true|false"`: Whether to create the database if it does not exist. - `subsubProtocol="directory"`: Type of SubsubProtocol to be used by Derby. The available options are `directory`, `memory`, `classpath` and `jar`. The next section describes connection configurations for other databases. ### Data Source Reference These topics provide Mule 4 XML examples for other database connections and include connector-specific settings: - [Mule 4 Example: Data Source Reference](#example_data_source_db) - [Mule 4 Example: Generic](#example_generic_db) - [Mule 4 Example: Microsoft SQL Server](#example_mssql_db) - [Mule 4 Example: MySQL](#example_mysql_db) - [Mule 4 Example: Oracle JDBC Database](#example_oracle_db) - [Mule 4 Example: Microsoft SQL Server](#example_mssql_db) - [Example: Maven dependency setting for a Microsoft SQL Server driver](#example_driver) Note that the Mule 3 example for Derby in the previous section shows most of the main differences between Mule 3 and Mule 4 for database connection configurations, including My SQL, Oracle, and so on. It also shows the main migration pattern from Mule 3 to Mule 4 database connections: - Derby: [Database Connection Configurations](#database_configuration) #### Mule 4 Example: Data Source Reference To use a Data Source Reference you need to: 1 - Create a XML Spring Beans file creating the Spring Bean representing the `DataSource` datasource-spring-beans.xml ```xml ``` > [!WARNING] Is required to configure the Maven dependency which contains the DataSource > implementation. For this example, `org.enhydra.jdbc.standard.StandardDataSource`, the required > dependency is: > > `` > `com.experlog` > `xapool` > `1.5.0` > `` 2 - Create Data Source Connection
1Import the datasource-spring-beans.xml file using the Mule Spring Module [link to Spring Module]
2Create the DB Config with the DataSource Connection, and add as dataSourceRef the Spring Bean ID of the DataSource Bean created in datasource-spring-beans.xml.
```xml (1) (2) ``` This setting is unique to Data Source Reference: - `dataSourceRef="my_ref_here"`: Reference to a JDBC DataSource object. This object is typically created using Spring. When using XA transactions, an XADataSource object must be provided. #### Mule 4 Example: Generic ```xml ``` These setting are unique to a Generic database: - `url="url_here"` for the JDBC URL to be used to connect to the database. - `driverClassName="driver_class_name_here"` for the fully-qualified name of the database driver class. > [!WARNING] The Maven dependency which contains the Class referenced in the `driverClassName` > parameter should be configured in the Mule Application. > Also, due to new Mule 4 ClassLoading mechanism, this dependency must be declared as a Shared > Library to be exported to the DB Connector. See also, [Database Transactions](#db_transactions). #### Mule 4 Example: Microsoft SQL Server ```xml ``` See also, [Database Transactions](#db_transactions). #### Mule 4 Example: MySQL ```xml ``` See also, [Database Transactions](#db_transactions). #### Mule 4 Example: Oracle JDBC Database ```xml ``` See also, [Database Transactions](#db_transactions). #### Example: Maven dependency setting for a Microsoft SQL Server driver Microsoft SQL Server, MySQL, Derby, Oracle configurations require a driver. ```xml com.microsoft.sqlserver mssql-jdbc 6.2.2.jre8 ``` > [!WARNING] Because of the new Mule 4 ClassLoading mechanism, this dependency must be declared as a > Shared Library to be exported to the DB Connector. Using Studio, this will be automatically > configured. ### Examples: Detailed Connector Configurations In Mule 4, you can add child elements for these settings under the database connection configurations (such as ``): - [Database Transactions](#db_transactions) - [Transactional Actions](#tx_actions) - [Transaction Isolation](#tx_isolation) - [XA Transactions](#xa_tx) - [Connection Properties](#connection_properties) - [Column Types](#column_types) - [Pooling Profile](#pooling_profile) - [Reconnection Strategies](#reconnection_strategies) #### Database Transactions ##### Transaction Isolation Transactions are for the transaction isolation level to set on the driver when connecting the database. - **NOT\_CONFIGURED** (Default) - **READ\_COMMITTED** (`transactionIsolation="READ_COMMITTED"`) - **READ\_UNCOMMITTED** (`transactionIsolation="READ_UNCOMMITTED"`) - **REPEATABLE\_READ** (`transactionIsolation="REPEATABLE_READ"`) - **SERIALIZABLE** (`transactionIsolation="SERIALIZABLE"`) Mule 3 Example: Transaction Isolation ```xml ``` Mule 4 Example: Transaction Isolation ```xml ``` ##### XA Transactions Connections can be configured to work in XA Transactions, in both **Mule 3** and **Mule 4** this can be configured in the connection configuration setting `useXaTransactions="true"` Mule 3 Example: XA Transactions ```xml ``` Mule 4 Example: XA Transactions ```xml ``` #### Connection Properties **MySQL** and **Microsoft SQL Server** database configurations provide connection property settings, these properties are injected to the JDBC Connection as additional properties. Mule 3 Example: Connection Properties ```xml ``` Mule 4 Example: Connection Properties ```xml ``` #### Column Types - Column types (``) for non-standard column types. #### Pooling Profile - Pooling profile (``) for JDBC Data Sources capable of connection pooling connections. It is is almost identical to Connection Pooling in Mule 3. #### Reconnection Strategies Reconnection strategy settings are similar in Mule 3 and Mule 4. However, custom reconnection strategies are not available in Mule 4. The examples below show changes to the XML for these settings: - **None**: Default. Same as Do Not Use A Reconnection Strategy in Mule 3. - **Standard**: Same as Standard Reconnection in Mule 3. Both have the same options: Frequency (ms), Reconnection Attempts - **Forever**: Same as Reconnect Forever in Mule 3. Mule 3 Examples: Reconnection Settings ```xml ` ` ``` Mule 4 Examples: Reconnection Settings ```xml ``` ## Database Connector Operations - Query for SQL query text and input parameters - Streaming strategy settings (as shown here in [Streaming Large Results](#database_streaming)) - [Transactional Actions](#tx_actions) - Query settings - Error mapping for errors, including DB:BAD\_SQL\_SYNTAX, DB:QUERY\_EXECUTION - Mule 4 input and output metadata for attributes, payload, and variables ### Migrating Parameterized Queries In Both **Mule 3** and **Mule 4** input parameters are supplied as key-value pairs. Those keys are used with the semicolon character (:) to reference a parameter value by name, this means that written SQL parameterized queries in **Mule 3** doesn’t need changes to be used in **Mule 4**. This approach is recommended to avoid SQL injection attacks, and it allows the connector to perform optimizations that improve the overall performance of the Mule app. #### Input Parameters - In **Mule 3** each Input Parameter was defined as a `` element inside the `` operation which had an `name` attribute for the parameter name, and a `value` attribute which holds the parameter value. - In **Mule 4**, the input parameters are defined as Map ``, where the key is the name of the parameter, and the value as the parameter value. This map can only be created using DataWeave. Mule 3 Example: Parameterized SELECT Query ```xml SELECT * FROM employees WHERE last_name = :last_name ``` Mule 4 Example: Parameterized SELECT Query ```xml SELECT * FROM employees WHERE last_name = :last_name #[ { last_name : vars.lastName } ] ``` ### Migrating Dynamic Queries Sometimes, you not only need to parameterize the WHERE clause, but also parameterize parts of the query itself. Example use cases for this would be queries which need to hit online/historic tables depending on a condition, or complex queries where the project columns need to vary. In Mule 3, the concept of select was split in parameterized and dynamic queries, and you couldn’t use both at the same time. You had to choose between having a dynamic query or having the advantages of using parameters (SQL Injection protection, PreparedStatement optimization, etc.). Furthermore, the syntax to do one or the other was different, so you had to learn two different ways of doing the same thing. But with the new Database Connector in Mule 4, you can now use both methods at the same time by using expressions in the query: Mule 3 Example: Dynamic SELECT Query ```xml SELECT * FROM #[flowVars.table] WHERE name = #[flowVars.name] ``` Mule 4 Example: Dynamic SELECT Query ```xml #['SELECT * FROM $(vars.table) WHERE name = $(vars.name)'] ``` GOTCHA: The Mule 3 example is less performant and vulnerable to SQL Injection attacks since the entire query is being treated as a string instead of using PreparedStatements ## Streaming Large Results Streaming can handle results queries to big database tables, which might return tens of thousands of records, especially for integration use cases. Streaming is a great solution for this. ### Enabling Streaming In **Mule 3**, streaming is disabled by default, so you have to enable it to use it. In **Mule 4**, streaming is always on but you can configure the strategy through which the runtime will achieve repeatable streaming. For more information on this, please refer to the [streaming documentation page](https://docs.mulesoft.com/mule-runtime/4.4/streaming-about). TIP: Note that disabling repeatable streaming will prevent DataWeave and other components to process the a stream many times, even in parallel. ### Migrating Bulk Operations #### Enabling Bulk Mode In **Mule 3**, you set bulk functionality through a `bulkMode="true"` setting on **Insert, Update, and Delete** operations. In **Mule 4**, you use dedicated Bulk Insert (``), Bulk Update (``), and Bulk Delete (``) database, instead. This means that operations no longer change their behavior depending on the received payload. #### Consuming bulk data In **Mule 3**, in a bulk query, the connector worked similar to the `` component, it took the current payload value, expecting to be a collection of items, and executes the `` expressions with each value of the collection. In **Mule 4**, is slightly different, instead of consuming the payload and executing expressions for each element in a collection, is required to inject a collection of entries. ##### Examples: Mule 3 Example: Select with a Parameterized Query ```xml INSERT INTO customers (id, name, lastName) VALUES (:id, :name, :lastName) ``` Mule 4 Example: Using the Bulk Operation to Get Different Values ```xml INSERT INTO customers (id, name, lastName) VALUES (:id, :name, :lastName) #[[{ id: 2, name: 'George', lastName: 'Costanza' }, { id: 3, name: 'Cosmo', lastName: 'Kramer' }]] ``` ### Migrating the Bulk Execute Operation The `` operation from the Mule 3 connector is replaced by the `` operation. It’s important to note that even though the Mule 3 version uses the word `bulk`, it is not an actual bulk operation as in the examples above. Instead, it executes many individual statements using the same connection, but it does not create bulk prepared statements. So, in Mule 4, the operation is named `execute-script` to better describe what it is doing. Mule 4 Example: Using the `execute-script` operation ```xml update PLANET set NAME='Mercury' where POSITION=0; update PLANET set NAME='Mercury' where POSITION=4 ``` You can also extract the statements to an external file: Mule 4 Example: Using the `execute-script` operation with an external file ```xml ``` ### Transactional Actions When database operations are executed inside a transaction, they can determine how to interact with the transaction. Available Transactional Actions: - **ALWAYS\_JOIN** - **JOIN\_IF\_POSSIBLE** - **NOT\_SUPPORTED** Mule 3 Example: Transactional Action ```xml SELECT * FROM people ``` Mule 4 Example: Transactional Action ```xml SELECT * FROM people ``` ### Output Target In **Mule 3** the DB Connector had the capability of save the execution output in a desired target variable. In **Mule 4**, this can still be done, but with a few differences. In **Mule 3** what was considered as output was just the execution result, so when configuring, for example: `target="#[flowVars.targetVar]"` this meant that the query execution will be saved in the flow variable `targetVar`. In **Mule 4** is very similar, you have a `target` parameter which is the name of the target Flow Variable, this can’t be an expression, and the new parameter in **Mule 4** is `targetValue`, this is an expression that is evaluated against the operation result. For example this can be: `#[payload]`, to save the entire payload, or `#[payload[0]]` to just save the first row of a Select Query. Mule 3 Example: Output Target ```xml SELECT * FROM People ``` Mule 4 Example: Output Target ```xml SELECT * from People ``` To use the Database connector, simply add it to your application using the Studio palette or add the following dependency in your `pom.xml` file: ```xml org.mule.connectors mule-db-connector 1.2.0 mule-plugin ``` ## See Also - [Database Connector Overview](https://docs.mulesoft.com/db-connector/latest/) - [Streaming in Mule 4.0](https://docs.mulesoft.com/mule-runtime/4.4/streaming-about). --- product: Mule Runtime version: 4.3 --- # Migrating the Enricher to a Target Variable > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Message Enricher and its functionality in Mule 3 is replaced by the `target` parameter in Mule 4. The Enricher provided a way to execute a group of message processors and redirect their output to a variable without side effects to the current message. In Mule 4, all non-void operations (for example, ``, ``, ``, and so on) include `target` and `targetValue` parameters, which allow redirecting each operation’s output into a variable (such as `myVar`). Other components in a Mule flow can then access that data through a DataWeave selector (for example, `vars.myVar`). ## Example Consider a message coming from an HTTP request, which we want to redirect to a third system, only that adding a `state` query param which is to be extracted using a secondary flow called `stateLookup`. Because you don’t want to lose the original payload or headers, you need to extract this value without affecting the original message. The Enricher calls out to the enrichment resource with the current message (containing the zip code), then enriches the current message with the result. Mule 3 example In Mule 4, you can simply use the `target` parameter in the `` operation: Mule 4 example #\[{'state' : vars.state}\] ## Migrate Multiple Enrichers In Mule 4, you can set only one `target` variable per operation. If you have more than one enricher configured in your Mule 3 application, you can achieve the same behavior in Mule 4 by using the `Set Variable` component: Mule 3 example ... ... Mule 4 example ... ... ## See Also - [Target Variables](https://docs.mulesoft.com/mule-runtime/4.3/target-variables) --- product: Mule Runtime version: 4.4 --- # Migrating the Enricher to a Target Variable > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Message Enricher and its functionality in Mule 3 is replaced by the `target` parameter in Mule 4. The Enricher provided a way to execute a group of message processors and redirect their output to a variable without side effects to the current message. In Mule 4, all non-void operations (for example, ``, ``, ``, and so on) include `target` and `targetValue` parameters, which allow redirecting each operation’s output into a variable (such as `myVar`). Other components in a Mule flow can then access that data through a DataWeave selector (for example, `vars.myVar`). ## Example Consider a message coming from an HTTP request, which we want to redirect to a third system, only that adding a `state` query param which is to be extracted using a secondary flow called `stateLookup`. Because you don’t want to lose the original payload or headers, you need to extract this value without affecting the original message. The Enricher calls out to the enrichment resource with the current message (containing the zip code), then enriches the current message with the result. Mule 3 example In Mule 4, you can simply use the `target` parameter in the `` operation: Mule 4 example #\[{'state' : vars.state}\] ## Migrate Multiple Enrichers In Mule 4, you can set only one `target` variable per operation. If you have more than one enricher configured in your Mule 3 application, you can achieve the same behavior in Mule 4 by using the `Set Variable` component: Mule 3 example ... ... Mule 4 example ... ... ## See Also - [Target Variables](https://docs.mulesoft.com/mule-runtime/4.4/target-variables) --- product: Mule Runtime version: 4.3 --- # Migrating the File Connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The File transport was completely rewritten. It evolved away from the Mule 3 transport model into an operation based connector. This enables many new capabilities: - The ability to read files or fully list directory contents on demand, unlike the old transport, which only provided a polling inbound endpoint. - Top-level support for common file system operations such as copying, moving, renaming, deleting, creating directories, and more. - Support for locking files at the file system level. - Advanced file matching functionality. ## What’s Covered Here? - [Migrating File Connector Configurations](#file_configs) - [Referencing File Connection Configurations](#file_config_refs) - [Migrating an inbound endpoint](#file_listener) - [Migrating an outbound endpoint](#file_write) ## Migrating File Connector Configurations In Mule 3, all transport configurations are set under a top-level element called ``, and by default, the File connector sets auto-deletion, streaming, and validation of the connections to `true`. Mule 3 Example: Default File Configuration ```xml ``` The connector configuration also provides settings for reading, writing, and moving files, among many others. The next example shows most of the Mule 3 setting available to the File connector. Mule 3 Example: Available File Connection Settings ```xml ``` In Mule 4, `` is the the top-level element for the file connection configuration, and `` is a child element for connection-related settings. Mule 4 Examples ```xml ``` - `workingDir` allows to specify a path to which all other paths are relative to. If not specified, the user’s home directory will be used. Note that in Mule 3, `workDirectory` is a similarly named attribute, but `workDirectory` is used when moving input files before processing them.) - `defaultWriteEncoding` identifies the character encoding to use for writing. You can overwrite this global configuration with a File operation, such as Write. All other Mule 3 config parameters are no longer needed since they were either replaced by parameters in the new connector’s operations or they were render needless by the new connector model. ## Referencing File Connection Configurations In Mule 3, all operations are set as inbound or outbound endpoints that use `connector-ref` to point to a name File connector configuration. Mule 3 Example: File Connection as Inbound Endpoint ```xml ``` Mule 3 Example: File Connection as Outbound Endpoint ```xml ``` ## Migrating an inbound endpoint In Mule 3, a `` message source was used to poll a directory for files. For each file found, a new message was triggered. The message would hold the file’s content in the payload and a number of file attributes as system properties. To avoid picking the same files over and over, `autoDelete` and `moveTo` parameters were provided so that the files would leave the polled directory after being picked. Mule 4 offers an improved way of doing that. The `` component (called `On New File` in the Studio palette) polls a directory and triggers a new message just like its predecessor did. However, it has the following added capabilities: - You can use a `` to only accept files that match certain criteria. - The listening `directory` has to be created before the app starts, or a reconnection strategy must be configured. In Mule 3.x, the directory was created if it did not exist when the app started. - You are no longer forced to either delete or move the file, although the option to do that is still available. - In 3.x, deleting or moving the input file did not take place if an error occurred and a transaction was rolled back, but it was done if there was no transaction. In Mule 4, an error prevents the deletion or move operation from occurring regardless of whether there is a transaction or not. - You can use any of the connector’s operations to change processed files in such a way that they no longer meet the matching criteria. - Watermark is automatically supported, allowing you to optionally filter automatically by creation or modification timestamp. - Mule 3 used the canonical path of the read file to add its metadata into the message inbound properties. Mule 4 uses the absolute path. Mule 3 Example: Inbound endpoint ```xml ``` Mule 4 Example: On New File ```xml ``` ## Migrating an outbound endpoint The Mule 3 transport uses the `` component to write the current payload to a file. The Mule 4 connector uses the `` operation instead. The most important differences are: - The `` component was asynchronous, which means that the actual writing happened in the background, while the next message processor in the flow was concurrently executed. The `` operation in the other hand, is synchronous, which means that the next message processor will not be executed until this one finishes. If you want the asynchronous behavior, just wrap the `` operation in an `` block - The `` required the content to be written to be in the message payload at the moment of executing. The `` operation allows embedding a DataWeave transformation which generates the content to be written. - The Mule 3 transport has the `outputAppend` parameter set at the config level, while the `` operation has a mode parameter Mule 3 Example: Outbound endpoint ```xml ``` Mule 4 Example: Write Operation ```xml #['Hello $(payload.name)'] ``` To use the File connector, simply add it to your application using the Studio palette or add the following dependency in your `pom.xml` file: ```xml org.mule.connectors mule-file-connector 1.1.0 mule-plugin ``` ## See also - [File Connector Documentation](https://docs.mulesoft.com/file-connector/latest/) --- product: Mule Runtime version: 4.4 --- # Migrating the File Connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The File transport was completely rewritten. It evolved away from the Mule 3 transport model into an operation based connector. This enables many new capabilities: - The ability to read files or fully list directory contents on demand, unlike the old transport, which only provided a polling inbound endpoint. - Top-level support for common file system operations such as copying, moving, renaming, deleting, creating directories, and more. - Support for locking files at the file system level. - Advanced file matching functionality. ## What’s Covered Here? - [Migrating File Connector Configurations](#file_configs) - [Referencing File Connection Configurations](#file_config_refs) - [Migrating an inbound endpoint](#file_listener) - [Migrating an outbound endpoint](#file_write) ## Migrating File Connector Configurations In Mule 3, all transport configurations are set under a top-level element called ``, and by default, the File connector sets auto-deletion, streaming, and validation of the connections to `true`. Mule 3 Example: Default File Configuration ```xml ``` The connector configuration also provides settings for reading, writing, and moving files, among many others. The next example shows most of the Mule 3 setting available to the File connector. Mule 3 Example: Available File Connection Settings ```xml ``` In Mule 4, `` is the the top-level element for the file connection configuration, and `` is a child element for connection-related settings. Mule 4 Examples ```xml ``` - `workingDir` allows to specify a path to which all other paths are relative to. If not specified, the user’s home directory will be used. Note that in Mule 3, `workDirectory` is a similarly named attribute, but `workDirectory` is used when moving input files before processing them.) - `defaultWriteEncoding` identifies the character encoding to use for writing. You can overwrite this global configuration with a File operation, such as Write. All other Mule 3 config parameters are no longer needed since they were either replaced by parameters in the new connector’s operations or they were render needless by the new connector model. ## Referencing File Connection Configurations In Mule 3, all operations are set as inbound or outbound endpoints that use `connector-ref` to point to a name File connector configuration. Mule 3 Example: File Connection as Inbound Endpoint ```xml ``` Mule 3 Example: File Connection as Outbound Endpoint ```xml ``` ## Migrating an inbound endpoint In Mule 3, a `` message source was used to poll a directory for files. For each file found, a new message was triggered. The message would hold the file’s content in the payload and a number of file attributes as system properties. To avoid picking the same files over and over, `autoDelete` and `moveTo` parameters were provided so that the files would leave the polled directory after being picked. Mule 4 offers an improved way of doing that. The `` component (called `On New File` in the Studio palette) polls a directory and triggers a new message just like its predecessor did. However, it has the following added capabilities: - You can use a `` to only accept files that match certain criteria. - The listening `directory` has to be created before the app starts, or a reconnection strategy must be configured. In Mule 3.x, the directory was created if it did not exist when the app started. - You are no longer forced to either delete or move the file, although the option to do that is still available. - In 3.x, deleting or moving the input file did not take place if an error occurred and a transaction was rolled back, but it was done if there was no transaction. In Mule 4, an error prevents the deletion or move operation from occurring regardless of whether there is a transaction or not. - You can use any of the connector’s operations to change processed files in such a way that they no longer meet the matching criteria. - Watermark is automatically supported, allowing you to optionally filter automatically by creation or modification timestamp. - Mule 3 used the canonical path of the read file to add its metadata into the message inbound properties. Mule 4 uses the absolute path. Mule 3 Example: Inbound endpoint ```xml ``` Mule 4 Example: On New File ```xml ``` ## Migrating an outbound endpoint The Mule 3 transport uses the `` component to write the current payload to a file. The Mule 4 connector uses the `` operation instead. The most important differences are: - The `` component was asynchronous, which means that the actual writing happened in the background, while the next message processor in the flow was concurrently executed. The `` operation in the other hand, is synchronous, which means that the next message processor will not be executed until this one finishes. If you want the asynchronous behavior, just wrap the `` operation in an `` block - The `` required the content to be written to be in the message payload at the moment of executing. The `` operation allows embedding a DataWeave transformation which generates the content to be written. - The Mule 3 transport has the `outputAppend` parameter set at the config level, while the `` operation has a mode parameter Mule 3 Example: Outbound endpoint ```xml ``` Mule 4 Example: Write Operation ```xml #['Hello $(payload.name)'] ``` To use the File connector, simply add it to your application using the Studio palette or add the following dependency in your `pom.xml` file: ```xml org.mule.connectors mule-file-connector 1.1.0 mule-plugin ``` ## See also - [File Connector Documentation](https://docs.mulesoft.com/file-connector/latest/) --- product: Mule Runtime version: 4.3 --- # Migrating the For Each Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Little changed between For Each scope for Mule 3 and Mule 4 except for the use of DataWeave 2 as the expression language. This little change however has a huge impact in terms of usability of the component. In Mule 3, foreach required the input collection to be a Java Iterable, Java Iterator or Java array. You were always forced to make sure that the input was in Java format (and therefore, you were forced to know java). In Mule 4, we support iterating over any array-like structure, regardless of the format. For example, suppose the following JSON is posted through an HTTP request: ```json { "persons": [ { "name": "John Doe", "age": 34 }, { "name": "Jane Doe", "age": 32 } ] } ``` Mule 3 requires the json being transformed to Java first: Mule 3 example ```xml ``` In Mule 4, you can just access the persons array in Json format directly: Mule 4 example ```xml ``` ## See Also - [Migrating Exception Strategies](https://docs.mulesoft.com/mule-runtime/4.3/migration-core-exception-strategies) - [Migrating from DataWeave 1.0 to 2.x](https://docs.mulesoft.com/mule-runtime/4.3/migration-dataweave) --- product: Mule Runtime version: 4.4 --- # Migrating the For Each Scope > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Little changed between For Each scope for Mule 3 and Mule 4 except for the use of DataWeave 2 as the expression language. This little change however has a huge impact in terms of usability of the component. In Mule 3, foreach required the input collection to be a Java Iterable, Java Iterator or Java array. You were always forced to make sure that the input was in Java format (and therefore, you were forced to know java). In Mule 4, we support iterating over any array-like structure, regardless of the format. For example, suppose the following JSON is posted through an HTTP request: ```json { "persons": [ { "name": "John Doe", "age": 34 }, { "name": "Jane Doe", "age": 32 } ] } ``` Mule 3 requires the json being transformed to Java first: Mule 3 example ```xml ``` In Mule 4, you can just access the persons array in Json format directly: Mule 4 example ```xml ``` ## See Also - [Migrating Exception Strategies](https://docs.mulesoft.com/mule-runtime/4.4/migration-core-exception-strategies) - [Migrating from DataWeave 1.0 to 2.x](https://docs.mulesoft.com/mule-runtime/4.4/migration-dataweave) --- product: Mule Runtime version: 4.3 --- # Migrating the JSON Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A new JSON module in Mule 4 replaces the one that was bundled in with Mule 3 for schema validation. To migrate transformations involving JSON, MuleSoft recommends that you use DataWeave. ## Migrating Transformers In Mule 3, many components required the payload to be a POJO so that its fields could be accessed. In Mule 4, DataWeave can be used as a query language directly on the JSON payload, which completely avoids the need to convert the payload to a POJO as an intermediate step. ### JSON to Object Transformer For mapping rules that are configured for the `json:json-to-object-transformer`, you can express the rules in DataWeave. - In Mule 3: Example: Mixin used in the Mapper Configuration ```java public abstract class AppleMixin { AppleMixin(@JsonProperty("bitten") boolean wasBitten) { super(); } } ``` Example: Transformer Referencing the Mapper ```xml ``` - In Mule 4: Example: Using DataWeave as the Mapper ```xml ``` You don’t have to define a mapper or a mixin class in Mule 4. The mapping rules are defined using DataWeave code. ### Object to JSON Transformer The mapping rules for the `json:object-to-json-transformer` are also expressed using DataWeave: In Mule 3: - Example: Transformer with Mixins ```xml ``` In Mule 4: - Example: Using DataWeave as the Mapper ```xml ``` In Mule 4 you can set the output format in the transformation. In this case, the expression defines the output as `application/json`, so the transformation function returns a JSON payload. ## Migrating XSLT Operations In Mule 4, the JSON module does not provide a component that transforms the JSON based on an XSLT mapping. Possible ways to handle this case are: - Migrate the XSLT to a DataWeave transformation (recommended) - Use XSLT support of the XML module, first converting the payload to XML. Mule 4 Example: Using XSLT to Transform JSON ```xml ... #[output application/xml --- payload] (the XSLT transformation) ... ... ``` ## See also - [JSON Module](https://docs.mulesoft.com/json-module/latest/) - [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) - [XML Module](https://docs.mulesoft.com/xml-module/latest/) --- product: Mule Runtime version: 4.4 --- # Migrating the JSON Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A new JSON module in Mule 4 replaces the one that was bundled in with Mule 3 for schema validation. To migrate transformations involving JSON, MuleSoft recommends that you use DataWeave. ## Migrating Transformers In Mule 3, many components required the payload to be a POJO so that its fields could be accessed. In Mule 4, DataWeave can be used as a query language directly on the JSON payload, which completely avoids the need to convert the payload to a POJO as an intermediate step. ### JSON to Object Transformer For mapping rules that are configured for the `json:json-to-object-transformer`, you can express the rules in DataWeave. - In Mule 3: Example: Mixin used in the Mapper Configuration ```java public abstract class AppleMixin { AppleMixin(@JsonProperty("bitten") boolean wasBitten) { super(); } } ``` Example: Transformer Referencing the Mapper ```xml ``` - In Mule 4: Example: Using DataWeave as the Mapper ```xml ``` You don’t have to define a mapper or a mixin class in Mule 4. The mapping rules are defined using DataWeave code. ### Object to JSON Transformer The mapping rules for the `json:object-to-json-transformer` are also expressed using DataWeave: In Mule 3: - Example: Transformer with Mixins ```xml ``` In Mule 4: - Example: Using DataWeave as the Mapper ```xml ``` In Mule 4 you can set the output format in the transformation. In this case, the expression defines the output as `application/json`, so the transformation function returns a JSON payload. ## Migrating XSLT Operations In Mule 4, the JSON module does not provide a component that transforms the JSON based on an XSLT mapping. Possible ways to handle this case are: - Migrate the XSLT to a DataWeave transformation (recommended) - Use XSLT support of the XML module, first converting the payload to XML. Mule 4 Example: Using XSLT to Transform JSON ```xml ... #[output application/xml --- payload] (the XSLT transformation) ... ... ``` ## See also - [JSON Module](https://docs.mulesoft.com/json-module/latest/) - [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) - [XML Module](https://docs.mulesoft.com/xml-module/latest/) --- product: Mule Runtime version: 4.3 --- # Migrating the OAuth2 Provider > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The new OAuth2 Provider Module from Mule 4 comes to replace the previous provider from the Anypoint Enterprise Security. However, there are some configuration changes that need to be taken into account when migrating the applications. ## Global Configuration Migration The following are the changes made in the Providers global configuration and the differences that they have between versions. ### Changed Attributes Attribute status: - Kept: Has same name, type and location. - Moved: The attribute has the same type and name but the location where it should be configured changed. - Changed: The type or name changed but the location is the same. - Removed: The attribute no longer exists.
Mule 3 AttributeStatusMule 4 Config

Name

Kept

Name

Provider Name

Kept

Provider Name

Host

Removed

The host is taken from the Http Configuration in Listener Config

Port

Removed

The port is taken from the Http Configuration in Listener Config

Client Store Ref

Changed

The attribute is now an Object Store. Needs to be a ref or an Private Object Store definition

Authorization Code Store Ref

Moved, Changed

The authorization code store should now be configured as an attribute of Authorization Config and it should be an Object Store

Token Generator Strategy

Kept

Token Generator Strategy

Token Store Ref

Moved, Changed

The token store should now be configured as an attribute of Token Config and it should be an Object Store

Login Page

Moved

The login page is configured as an attribute of Authorization Config

Scopes

Kept

Should now be comma separated

Default Scopes

Kept

Should now be comma separated

Supported Grant Types

Kept

Should now be comma separated

Authorization Endpoint Path

Changed, Moved

Configurable in the attribute path of Authorization Config

Access Token Endpoint Path

Changed, Moved

Configurable in the attribute path of Token Config

Authorization Ttl Seconds

Removed

The authorization code Ttl will be taken from the entry Ttl configured in the Authorization Code Store object store.

Token Ttl Seconds

Moved, Changed

The token Ttl will be taken from the Token Store object store. Due to a limitation in the code, it is asked that the field is also configured in the attributes tokenTtl and tokenTtlTimeUnit of TokenConfig. The Token Store entryTtl and Token Config tokenTtl (and tokenTtlTimeUnit) must be the same.

Refresh Token Ttl Seconds

Removed

The refresh token Ttl will be taken from the entry Ttl of the Object Store configured in the Refresh Token Strategy in case there is one.

Connector

Removed

Transports were removed from Mule 4 so this field has no meaning anymore.

HttpListenerConfig

Changed

Now it’s called Listener Config and it’s mandatory

Resource Owner Security Provider Ref

Changed

Ref has been removed from the attribute’s name. The Spring Module should be used if a Spring Security Provider is configured.

Client Security Provider Ref

Changed

Ref has been removed from the attribute’s name. The Spring Module should be used if a Spring Security Provider is configured.

Enable Refresh Token

Removed

Configurable with a different Refresh Token Strategy

Issue New Refresh Token

Removed

Configurable with a different Refresh Token Strategy

Rate Limiter

Changed

You can no longer add a custom implementation from a spring bean. Only Period Rate Limiter is implemented for now.

Clients

Kept

Each client definition changed

Pre Flow

Removed

Pre flow functionality will not be supported in this version

## Stores Authentication Code, Token or Refresh token stores no longer exist and there is no attribute that lets you reference a custom implementation of any of those. Any storage configuration is now done with an Object Store. If a custom behavior is needed, then a custom implementation of an Object Store should be used to configure any of those attributes ## Security Providers In Mule 4 we decoupled the applications configuration completely from Spring, so for some of the attributes that were configured by referencing a Spring Bean, the way of configuring them has changed. Spring security providers can still be used but, in that case, the Spring Module is needed in order for the application to work. ## Refresh Token Attributes In Mule 3, there were 2 attributes that allowed the refresh token behavior configuration. As now we have different Refresh Token Strategies, the configuration should be done the following way.

Enable Refresh Token

Issue New Refresh Token

Refresh Token Strategy

False

-

No Refresh Token Strategy

True

False

Single Refresh Token Strategy

True

True

Multiple Refresh Token Strategy

## Clients In both Mule versions you have the possibility to define a list of clients that will be authorized to make requests to the Authentication Server. The way to add the clients remains the same except for some attribute names. Due to a limitation in the new version, the names of the child elements had to be changed by adding the _clients_ and _client_ prefixes. - Redirect Uri(s) → Client Redirect Uris(s) - Authorized Grant Type(s) → Client Authorized Grant Type(s) - Scope(s) → Client Scope(s) ## Operations The following are the operations available in the module for Mule 3 and the changes they have for Mule 4 ### Validate Client The operation was removed in Mule 4. ### Validate Now the operation is called **Validate Token**. Since the OAuth2 Provider operations are no longer linked to HTTP, an expression to resolve the token to validate is required. In Mule 3, after token validation, if there was a resource owner authentication involved, a new security context was created with that resource owner authentication. Also, the token holder with the token information was saved in a flow variable called: _mule.oauth2.access\_token\_store\_holder_. Now, in Mule 4, that same information is saved a little bit differently. After token validation, the security context will be created with a token authentication accessible by `#[authentication]`. The token holder that was in a variable is saved as an attribute of that token authentication : `#[authentication.tokenHolder]`. At the same time, if there was a resource owner involved, it information can be reached by evaluating `#[authentication.tokenHolder.resourceOwnerAuthentication]` ### Create Client The operation remains the same except for a new attribute that was added: **Fail If Present**. **Fail If Present** lets you decide what to do if a client with the same id of the one to be added already exists. - If true, the operation will fail - If false, the client information will be updated ### Delete Client The operation remains the same. ### Revoke Token The operation remains the same. ## Example Here is an example of the same application configured in Mule 3 And Mule 4. The application has an OAuth2 Provider that grants tokens and a flow that listens to HTTP requests and has a token validation before processing some logic. Keep in mind that the Mule 4 configuration is using the Spring Module and the Object Store Connector. In both cases the application has been split into multiple files. For Mule 3 there are 2: One for common configuration and another one for the actual OAuth2 Provider configuration. For Mule 4 there are 3 files: One for bean definition, one for common configuration and one for the actual OAuth2 Provider configuration. ### Mule 3 #### Common configuration ```xml ``` #### Application configuration ```xml http://fake/redirect AUTHORIZATION_CODE ``` ### Mule 4 #### Bean Configuration ```xml ``` #### Common Configuration ```xml ``` #### Application Configuration ```xml http://fake/redirect AUTHORIZATION_CODE ``` ## See Also - [OAuth2 Provider Documentation Reference](https://docs.mulesoft.com/oauth2-provider-module/latest/oauth2-provider-module-reference) --- product: Mule Runtime version: 4.4 --- # Migrating the OAuth2 Provider > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The new OAuth2 Provider Module from Mule 4 comes to replace the previous provider from the Anypoint Enterprise Security. However, there are some configuration changes that need to be taken into account when migrating the applications. ## Global Configuration Migration The following are the changes made in the Providers global configuration and the differences that they have between versions. ### Changed Attributes Attribute status: - Kept: Has same name, type and location. - Moved: The attribute has the same type and name but the location where it should be configured changed. - Changed: The type or name changed but the location is the same. - Removed: The attribute no longer exists.
Mule 3 AttributeStatusMule 4 Config

Name

Kept

Name

Provider Name

Kept

Provider Name

Host

Removed

The host is taken from the Http Configuration in Listener Config

Port

Removed

The port is taken from the Http Configuration in Listener Config

Client Store Ref

Changed

The attribute is now an Object Store. Needs to be a ref or an Private Object Store definition

Authorization Code Store Ref

Moved, Changed

The authorization code store should now be configured as an attribute of Authorization Config and it should be an Object Store

Token Generator Strategy

Kept

Token Generator Strategy

Token Store Ref

Moved, Changed

The token store should now be configured as an attribute of Token Config and it should be an Object Store

Login Page

Moved

The login page is configured as an attribute of Authorization Config

Scopes

Kept

Should now be comma separated

Default Scopes

Kept

Should now be comma separated

Supported Grant Types

Kept

Should now be comma separated

Authorization Endpoint Path

Changed, Moved

Configurable in the attribute path of Authorization Config

Access Token Endpoint Path

Changed, Moved

Configurable in the attribute path of Token Config

Authorization Ttl Seconds

Removed

The authorization code Ttl will be taken from the entry Ttl configured in the Authorization Code Store object store.

Token Ttl Seconds

Moved, Changed

The token Ttl will be taken from the Token Store object store. Due to a limitation in the code, it is asked that the field is also configured in the attributes tokenTtl and tokenTtlTimeUnit of TokenConfig. The Token Store entryTtl and Token Config tokenTtl (and tokenTtlTimeUnit) must be the same.

Refresh Token Ttl Seconds

Removed

The refresh token Ttl will be taken from the entry Ttl of the Object Store configured in the Refresh Token Strategy in case there is one.

Connector

Removed

Transports were removed from Mule 4 so this field has no meaning anymore.

HttpListenerConfig

Changed

Now it’s called Listener Config and it’s mandatory

Resource Owner Security Provider Ref

Changed

Ref has been removed from the attribute’s name. The Spring Module should be used if a Spring Security Provider is configured.

Client Security Provider Ref

Changed

Ref has been removed from the attribute’s name. The Spring Module should be used if a Spring Security Provider is configured.

Enable Refresh Token

Removed

Configurable with a different Refresh Token Strategy

Issue New Refresh Token

Removed

Configurable with a different Refresh Token Strategy

Rate Limiter

Changed

You can no longer add a custom implementation from a spring bean. Only Period Rate Limiter is implemented for now.

Clients

Kept

Each client definition changed

Pre Flow

Removed

Pre flow functionality will not be supported in this version

## Stores Authentication Code, Token or Refresh token stores no longer exist and there is no attribute that lets you reference a custom implementation of any of those. Any storage configuration is now done with an Object Store. If a custom behavior is needed, then a custom implementation of an Object Store should be used to configure any of those attributes ## Security Providers In Mule 4 we decoupled the applications configuration completely from Spring, so for some of the attributes that were configured by referencing a Spring Bean, the way of configuring them has changed. Spring security providers can still be used but, in that case, the Spring Module is needed in order for the application to work. ## Refresh Token Attributes In Mule 3, there were 2 attributes that allowed the refresh token behavior configuration. As now we have different Refresh Token Strategies, the configuration should be done the following way.

Enable Refresh Token

Issue New Refresh Token

Refresh Token Strategy

False

-

No Refresh Token Strategy

True

False

Single Refresh Token Strategy

True

True

Multiple Refresh Token Strategy

## Clients In both Mule versions you have the possibility to define a list of clients that will be authorized to make requests to the Authentication Server. The way to add the clients remains the same except for some attribute names. Due to a limitation in the new version, the names of the child elements had to be changed by adding the _clients_ and _client_ prefixes. - Redirect Uri(s) → Client Redirect Uris(s) - Authorized Grant Type(s) → Client Authorized Grant Type(s) - Scope(s) → Client Scope(s) ## Operations The following are the operations available in the module for Mule 3 and the changes they have for Mule 4 ### Validate Client The operation was removed in Mule 4. ### Validate Now the operation is called **Validate Token**. Since the OAuth2 Provider operations are no longer linked to HTTP, an expression to resolve the token to validate is required. In Mule 3, after token validation, if there was a resource owner authentication involved, a new security context was created with that resource owner authentication. Also, the token holder with the token information was saved in a flow variable called: _mule.oauth2.access\_token\_store\_holder_. Now, in Mule 4, that same information is saved a little bit differently. After token validation, the security context will be created with a token authentication accessible by `#[authentication]`. The token holder that was in a variable is saved as an attribute of that token authentication : `#[authentication.tokenHolder]`. At the same time, if there was a resource owner involved, it information can be reached by evaluating `#[authentication.tokenHolder.resourceOwnerAuthentication]` ### Create Client The operation remains the same except for a new attribute that was added: **Fail If Present**. **Fail If Present** lets you decide what to do if a client with the same id of the one to be added already exists. - If true, the operation will fail - If false, the client information will be updated ### Delete Client The operation remains the same. ### Revoke Token The operation remains the same. ## Example Here is an example of the same application configured in Mule 3 And Mule 4. The application has an OAuth2 Provider that grants tokens and a flow that listens to HTTP requests and has a token validation before processing some logic. Keep in mind that the Mule 4 configuration is using the Spring Module and the Object Store Connector. In both cases the application has been split into multiple files. For Mule 3 there are 2: One for common configuration and another one for the actual OAuth2 Provider configuration. For Mule 4 there are 3 files: One for bean definition, one for common configuration and one for the actual OAuth2 Provider configuration. ### Mule 3 #### Common configuration ```xml ``` #### Application configuration ```xml http://fake/redirect AUTHORIZATION_CODE ``` ### Mule 4 #### Bean Configuration ```xml ``` #### Common Configuration ```xml ``` #### Application Configuration ```xml http://fake/redirect AUTHORIZATION_CODE ``` ## See Also - [OAuth2 Provider Documentation Reference](https://docs.mulesoft.com/oauth2-provider-module/latest/oauth2-provider-module-reference) --- product: Mule Runtime version: 4.3 --- # Migrating the Object Store Connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Object Store Connector in Mule 4 is very similar to the one in Mule 3. The main differences between these major versions are: - How custom Object Stores are created: on Mule 4 creation of a Custom Object Store does not require the usage of Spring or the knowledge of the existence of certain java classes. - Keys must always be Strings: the Object Store Connector used to accept any `Serializable` as keys. On Mule 4 all keys must be of type `String`. ## What’s covered in this section: - [Namespace Change](#namespace) - [Using Top Level Objects](#configs-object-stores) - [Creating Custom Object Stores](#custom-object-store) - [Changes to Keys](#change-on-keys) - [Storing a value](#storing-values) - [Default Value to Persistent Attribute](#persistent-default-value) - [Cleaning an Object Store](#dispose-clear) - [Removal of the Dual Store Operation](#dual-store) - [Remove Operation Behavior](#remove-behavior) ## Namespace Change On the Mule 3 ObjectStore Connector the namespace used was `objectstore` . This namespace has change to `os` on the new Mule 4 Connector. Mule 3 example ```xml ``` Mule 4 example ```xml ``` ## Using Top Level Objects You may have noticed in the previous example that the `config-ref` parameter was removed, and instead an `objectStore` parameter appears. This is because on Mule 3 most of the connector operations require a _Connector Configuration reference_, while on Mule 4 most operations will instead receive a reference to an _Object Store top level element_. ## Creating Custom Object Stores Custom Object Stores are global definitions of an OS that you can reference by name to use it in an operation, allowing you to tweak and configure the Object Store behavior to your needs. On Mule 3, in order to create a new ObjectStore you needed to create a spring bean and know the specific java classes used for the ObjectStore. On Mule 4 this is much easier, you just have to create a global element that declares the ObjectStore using the `os:object-store` component. This are examples of how this was done on Mule 3 and how it is done now on Mule 4 for a simple case where `store` and `retrieve` are exposed through HTTP endpoints using persistent custom object stores: Mule 3 example ```xml (1) (2) (4) 1Creates the custom object store using Spring beans and a reference to a java class.2References the custom object store in a configuration.3Before using the store operation, a DataWeave transformation is used to set on the payload what is going to be stored.4The payload is stored in the object store. Implementing the same app in Mule 4 would look like this: Mule 4 example ```xml (1) (2) #[{ id: attributes.queryParams.id, book: attributes.queryParams.book, author: attributes.queryParams.author }] ``` As you may see, main differences are:
1A new object store is created without any knowledge of spring beans nor java classes. Note that what is being defined here is no a configuration, but rather an object store top level element.
2Without the need to store a value on a variable or the payload, an inline expression defines what is going to be stores in the object store.
Note that on Mule 3 you used to have to specify a partition of the Object Store. On Mule 4 you no longer have to specify a partition, instead you just use another Object Store. Also, you can specify the time units for both the entry time to live and the frequency on which you will check if entries have expired or exceed the maximum amount of entries. ## Changes to Keys On Mule 3 the keys used to reference values on an object store could be any `Serializable`. On Mule 4 only `String` objects are used for this purpose. In case that you are using a `Serializable` that is not a `String` as keys, you should convert it into `String` values. ## Storing a value On Mule 4 the value parameter now is taken as a content parameter, this means that it should be defined inline. This was configured as an attribute on Mule 3. Also, the way to update a value on an object store had a minor change. On Mule 3 you had a flag called `overwrite` that by default comes as false. On Mule 4 you have a flag called `failIfPresent` that by default comes as false. This means that now when using the store operation with an already used key, the default behavior is to overwrite the value. > [!WARNING] In Mule 4, when the key already exists and the flag `failIfPresent` is set to true, the > error OS:KEY\_ALREADY\_EXISTS will be thrown. When migrating pay close attention to how flags are configure, since the default behaviors are different. Mule 3 example ```xml (1) ```
1Since on Mule 3 you cannot insert the DataWeave expression inline, your options are to to either save the content on a variable or modify the payload. In this it was assigned to the client variable.
Mule 4 example ```xml #[{ (1) id: payload.id, name: payload.name, lname: payload.lname, age: payload.age }] ```
1On Mule 4 you can insert the content to store inline. After this operation the payload remains unchanged.
## Default Value to Persistent Attribute On Mule 4 object stores are persistent by default, while on the Mule 3 connector they are stored on-memory by default. Because of this you will have to be carefull when migrating your implementation. Not saying explicitly the persistence of the object store will mean different things. This example shows how after migrating, the persistent attribute had to be explicitly added: Mule 3 example ```xml ``` Mule 4 example ```xml ``` ## Cleaning an Object Store The dispose operation on Mule 3 was used to clear a specific partition of an object store. On Mule 4 we have the clear operation that clears a whole object store. There is no notion of partition anymore. Mule 3 example ```xml ``` Mule 4 example ```xml ``` > [!WARNING] On Mule 4 the clear operation will clear the whole Object Store. ## Removal of the Dual Store Operation The Mule 3 Object Store Connector had an operation `dual-store` that stored a value using key and also stored the same key using value. As key is restricted to be a `String`, on Mule 4 this operation would not make sense, so it was removed. ## Remove Operation Behavior On Mule 3 the `remove` operation had a flag named `ignoreNotExists` which defaults to false that indicated whether the operation should fail if the key that was going to be removed did not exist. On Mule 4 if the key does not exist, the error `OS:KEY_NOT_FOUND` will be thrown and the you can handle it however you want on the error handling. --- product: Mule Runtime version: 4.4 --- # Migrating the Object Store Connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Object Store Connector in Mule 4 is very similar to the one in Mule 3. The main differences between these major versions are: - How custom Object Stores are created: on Mule 4 creation of a Custom Object Store does not require the usage of Spring or the knowledge of the existence of certain java classes. - Keys must always be Strings: the Object Store Connector used to accept any `Serializable` as keys. On Mule 4 all keys must be of type `String`. ## What’s covered in this section: - [Namespace Change](#namespace) - [Using Top Level Objects](#configs-object-stores) - [Creating Custom Object Stores](#custom-object-store) - [Changes to Keys](#change-on-keys) - [Storing a value](#storing-values) - [Default Value to Persistent Attribute](#persistent-default-value) - [Cleaning an Object Store](#dispose-clear) - [Removal of the Dual Store Operation](#dual-store) - [Remove Operation Behavior](#remove-behavior) ## Namespace Change On the Mule 3 ObjectStore Connector the namespace used was `objectstore` . This namespace has change to `os` on the new Mule 4 Connector. Mule 3 example ```xml ``` Mule 4 example ```xml ``` ## Using Top Level Objects You may have noticed in the previous example that the `config-ref` parameter was removed, and instead an `objectStore` parameter appears. This is because on Mule 3 most of the connector operations require a _Connector Configuration reference_, while on Mule 4 most operations will instead receive a reference to an _Object Store top level element_. ## Creating Custom Object Stores Custom Object Stores are global definitions of an OS that you can reference by name to use it in an operation, allowing you to tweak and configure the Object Store behavior to your needs. On Mule 3, in order to create a new ObjectStore you needed to create a spring bean and know the specific java classes used for the ObjectStore. On Mule 4 this is much easier, you just have to create a global element that declares the ObjectStore using the `os:object-store` component. This are examples of how this was done on Mule 3 and how it is done now on Mule 4 for a simple case where `store` and `retrieve` are exposed through HTTP endpoints using persistent custom object stores: Mule 3 example ```xml (1) (2) (4) ``` In this snippet a couple of things are to be noted:
1Creates the custom object store using Spring beans and a reference to a java class.
2References the custom object store in a configuration.
3Before using the store operation, a DataWeave transformation is used to set on the payload what is going to be stored.
4The payload is stored in the object store.
Implementing the same app in Mule 4 would look like this: Mule 4 example ```xml (1) (2) #[{ id: attributes.queryParams.id, book: attributes.queryParams.book, author: attributes.queryParams.author }] ``` As you may see, main differences are:
1A new object store is created without any knowledge of spring beans nor java classes. Note that what is being defined here is no a configuration, but rather an object store top level element.
2Without the need to store a value on a variable or the payload, an inline expression defines what is going to be stores in the object store.
Note that on Mule 3 you used to have to specify a partition of the Object Store. On Mule 4 you no longer have to specify a partition, instead you just use another Object Store. Also, you can specify the time units for both the entry time to live and the frequency on which you will check if entries have expired or exceed the maximum amount of entries. ## Changes to Keys On Mule 3 the keys used to reference values on an object store could be any `Serializable`. On Mule 4 only `String` objects are used for this purpose. In case that you are using a `Serializable` that is not a `String` as keys, you should convert it into `String` values. ## Storing a value On Mule 4 the value parameter now is taken as a content parameter, this means that it should be defined inline. This was configured as an attribute on Mule 3. Also, the way to update a value on an object store had a minor change. On Mule 3 you had a flag called `overwrite` that by default comes as false. On Mule 4 you have a flag called `failIfPresent` that by default comes as false. This means that now when using the store operation with an already used key, the default behavior is to overwrite the value. > [!WARNING] In Mule 4, when the key already exists and the flag `failIfPresent` is set to true, the > error OS:KEY\_ALREADY\_EXISTS will be thrown. When migrating pay close attention to how flags are configure, since the default behaviors are different. Mule 3 example ```xml (1) ```
1Since on Mule 3 you cannot insert the DataWeave expression inline, your options are to to either save the content on a variable or modify the payload. In this it was assigned to the client variable.
Mule 4 example ```xml #[{ (1) id: payload.id, name: payload.name, lname: payload.lname, age: payload.age }] ```
1On Mule 4 you can insert the content to store inline. After this operation the payload remains unchanged.
## Default Value to Persistent Attribute On Mule 4 object stores are persistent by default, while on the Mule 3 connector they are stored on-memory by default. Because of this you will have to be careful when migrating your implementation. Not saying explicitly the persistence of the object store will mean different things. This example shows how after migrating, the persistent attribute had to be explicitly added: Mule 3 example ```xml ``` Mule 4 example ```xml ``` ## Cleaning an Object Store The dispose operation on Mule 3 was used to clear a specific partition of an object store. On Mule 4 we have the clear operation that clears a whole object store. There is no notion of partition anymore. Mule 3 example ```xml ``` Mule 4 example ```xml ``` > [!WARNING] On Mule 4 the clear operation will clear the whole Object Store. ## Removal of the Dual Store Operation The Mule 3 Object Store Connector had an operation `dual-store` that stored a value using key and also stored the same key using value. As key is restricted to be a `String`, on Mule 4 this operation would not make sense, so it was removed. ## Remove Operation Behavior On Mule 3 the `remove` operation had a flag named `ignoreNotExists` which defaults to false that indicated whether the operation should fail if the key that was going to be removed did not exist. On Mule 4 if the key does not exist, the error `OS:KEY_NOT_FOUND` will be thrown and the you can handle it however you want on the error handling. --- product: Mule Runtime version: 4.3 --- # Migrating the Poll Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 3, the `` element was used to trigger a certain flow at a fixed frequency of time. This element was also a scope which required one (and only one) message processor to live inside of it. The output of that processor would be the message that the flow receives. Mule 3 Example: Poll ```xml SELECT * FROM PERSON>
``` In Mule 4, the `` element was replaced with the `` element. Main differences are: - It just triggers the flow. It’s no longer a scope - It supports both fixed frequency and cron expressions Mule 4 Example: Scheduler ```xml SELECT * FROM PERSON>
``` For more information on the `` element, please read the [Scheduler documentation](https://docs.mulesoft.com/mule-runtime/4.3/scheduler-concept). ## Migrating a Watermark The `` element also supported a `` element which was used to aid and scheduled synchronizations. That element doesn’t exist anymore. Instead, please read the [Migrating Watermarks](https://docs.mulesoft.com/mule-runtime/4.3/migration-patterns-watermark) page. ## Quartz Transport In Mule 3, a `quartz` transport existed that was deprecated in favor of the `poll`, so most of its uses may also be replaced by the `scheduler` in Mule 4. Some features of the `quartz` transport do not exist in Mule 4, so a different approach is necessary to migrate those use cases. ### repeatCount `repeatCount` is not supported in Mule 4 by the `scheduler`. If you really need to fetch it, compare and store a counter in an [Object Store](https://docs.mulesoft.com/object-store-connector/latest/). ### quartz:outbound-endpoint This endpoint is not supported in Mule 4. An alternative approach is to write the events to a queue (JMS or VM, for instance) and have another flow with a Scheduler that consumes all the messages from the queue and processes them. ### Unsupported job-endpoint The transport used in a `job-endpoint`, when migrated to a Mule 4, can be migrated to a connector that has a polling source (such as File). In that case, you can put the Scheduler configuration directly into the polling source. Mule 3 Example: Polling source ```xml ``` Mule 4 Example: Polling source ```xml ``` ## See Also - [Scheduler Endpoint (Trigger)](https://docs.mulesoft.com/mule-runtime/4.3/scheduler-concept) --- product: Mule Runtime version: 4.4 --- # Migrating the Poll Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 3, the `` element was used to trigger a certain flow at a fixed frequency of time. This element was also a scope which required one (and only one) message processor to live inside of it. The output of that processor would be the message that the flow receives. Mule 3 Example: Poll ```xml SELECT * FROM PERSON>
``` In Mule 4, the `` element was replaced with the `` element. Main differences are: - It just triggers the flow. It’s no longer a scope - It supports both fixed frequency and cron expressions Mule 4 Example: Scheduler ```xml SELECT * FROM PERSON>
``` For more information on the `` element, please read the [Scheduler documentation](https://docs.mulesoft.com/mule-runtime/4.4/scheduler-concept). ## Migrating a Watermark The `` element also supported a `` element which was used to aid and scheduled synchronizations. That element doesn’t exist anymore. Instead, please read the [Migrating Watermarks](https://docs.mulesoft.com/mule-runtime/4.4/migration-patterns-watermark) page. ## Quartz Transport In Mule 3, a `quartz` transport existed that was deprecated in favor of the `poll`, so most of its uses may also be replaced by the `scheduler` in Mule 4. Some features of the `quartz` transport do not exist in Mule 4, so a different approach is necessary to migrate those use cases. ### repeatCount `repeatCount` is not supported in Mule 4 by the `scheduler`. If you really need to fetch it, compare and store a counter in an [Object Store](https://docs.mulesoft.com/object-store-connector/latest/). ### quartz:outbound-endpoint This endpoint is not supported in Mule 4. An alternative approach is to write the events to a queue (JMS or VM, for instance) and have another flow with a Scheduler that consumes all the messages from the queue and processes them. ### Unsupported job-endpoint The transport used in a `job-endpoint`, when migrated to a Mule 4, can be migrated to a connector that has a polling source (such as File). In that case, you can put the Scheduler configuration directly into the polling source. Mule 3 Example: Polling source ```xml ``` Mule 4 Example: Polling source ```xml ``` ## See Also - [Scheduler Endpoint (Trigger)](https://docs.mulesoft.com/mule-runtime/4.4/scheduler-concept) --- product: Mule Runtime version: 4.3 --- # Migrating the Scatter-Gather Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The most important change in Scatter-Gather router between Mule 3 and Mule 4 is in the `AggregationStrategy` used to consolidate the results of the different routes. Instead of providing a Java class with the aggregation logic, you can perform the aggregation with a DataWeave transformation. The payload Scatter-Gather returns is a collection of messages, where each the result of each route. Those messages are accessible with DataWeave. ## Example This is a Mule 3 Scatter-Gather with a `custom-aggregation-strategy` element referencing the Java class with the aggregation strategy: ... ... And the aggregation strategy implementation is: package com.example.poc; import ... public class CustomSGAggregationStrategy implements AggregationStrategy { @Override public MuleEvent aggregate(AggregationContext context) throws MuleException { StringBuilder responseBuilder = new StringBuilder(); MuleEvent result = null; ArrayList < MarketRate > marketRates = new ArrayList < > (); for (MuleEvent event: context.collectEventsWithoutExceptions()) { String response = (String) event.getMessage().getPayload(); String\[\] spiltResponse = StringUtils.split(response, ","); MarketRate marketRate = new MarketRate(); marketRate.setEvent(event); marketRate.setMarketName(spiltResponse\[0\]); marketRate.setMarketRate(new Integer(spiltResponse\[1\])); marketRates.add(marketRate); System.out.println(marketRate); } Collections.sort(marketRates); result = DefaultMuleEvent.copy(marketRates.get(0).getEvent()); result.getMessage().setPayload(marketRates.get(0).toString()); return result; } } For Mule 4, the Java class is removed, and the flow elements become: ... ... (response.payload splitBy(','))\[1\]) orderBy ((rate, index) -> rate))\[0\] \]\]\]> Notice the `ee:transform` element that replicates the logic of the `CustomSGAggregationStrategy`, in DataWeave rather than Java. ## See Also [About Scatter-Gather](https://docs.mulesoft.com/mule-runtime/4.3/scatter-gather-concept) [About the Transform Component](https://docs.mulesoft.com/mule-runtime/4.3/transform-component-about) [DataWeave Scripts](https://docs.mulesoft.com/dataweave/2.3/dataweave-language-introduction) --- product: Mule Runtime version: 4.4 --- # Migrating the Scatter-Gather Router > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The most important change in Scatter-Gather router between Mule 3 and Mule 4 is in the `AggregationStrategy` used to consolidate the results of the different routes. Instead of providing a Java class with the aggregation logic, you can perform the aggregation with a DataWeave transformation. The payload Scatter-Gather returns is a collection of messages, where each the result of each route. Those messages are accessible with DataWeave. ## Example This is a Mule 3 Scatter-Gather with a `custom-aggregation-strategy` element referencing the Java class with the aggregation strategy: ... ... And the aggregation strategy implementation is: package com.example.poc; import ... public class CustomSGAggregationStrategy implements AggregationStrategy { @Override public MuleEvent aggregate(AggregationContext context) throws MuleException { StringBuilder responseBuilder = new StringBuilder(); MuleEvent result = null; ArrayList < MarketRate > marketRates = new ArrayList < > (); for (MuleEvent event: context.collectEventsWithoutExceptions()) { String response = (String) event.getMessage().getPayload(); String\[\] spiltResponse = StringUtils.split(response, ","); MarketRate marketRate = new MarketRate(); marketRate.setEvent(event); marketRate.setMarketName(spiltResponse\[0\]); marketRate.setMarketRate(new Integer(spiltResponse\[1\])); marketRates.add(marketRate); System.out.println(marketRate); } Collections.sort(marketRates); result = DefaultMuleEvent.copy(marketRates.get(0).getEvent()); result.getMessage().setPayload(marketRates.get(0).toString()); return result; } } For Mule 4, the Java class is removed, and the flow elements become: ... ... (response.payload splitBy(','))\[1\]) orderBy ((rate, index) -> rate))\[0\] \]\]\]> Notice the `ee:transform` element that replicates the logic of the `CustomSGAggregationStrategy`, in DataWeave rather than Java. ## See Also [About Scatter-Gather](https://docs.mulesoft.com/mule-runtime/4.4/scatter-gather-concept) [About the Transform Component](https://docs.mulesoft.com/mule-runtime/4.4/transform-component-about) [DataWeave Scripts](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction) --- product: Mule Runtime version: 4.3 --- # Migrating the Scripting Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The `` component in Mule 3 is replaced with a new `` module. This new module is pretty similar in functionality, with just some syntax changes: Mule 3 Example: Scripting ```xml ``` - Mule 4 Example: Scripting ```xml ${file::greedy.groovy} #[{currency: vars.currency}] ``` As you can see, the main difference here is that now you can use DataWeave to generate the input parameters. ## Accessing Variables from the Script The previous example uses a variable to show how to pass parameters into the script, it’s best to keep the script decoupled from the rest of the flow, so that changes to the Mule applications don’t require changes to the script. However, you can still access the variables from the script using the `vars` keyword. For example: Mule 4 Example: Accessing variables directly ```xml return "currency is " + vars.currency ``` To use the Scripting Module, simply add it to your application using the Studio palette or add the following dependency in your `pom.xml` file: ```xml org.mule.modules mule-scripting-module 1.1.0 mule-plugin ``` ## See Also - [Scripting Module Documentation](https://docs.mulesoft.com/scripting-module/latest/) --- product: Mule Runtime version: 4.4 --- # Migrating the Scripting Component > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The `` component in Mule 3 is replaced with a new `` module. This new module is pretty similar in functionality, with just some syntax changes: Mule 3 Example: Scripting ```xml ``` - Mule 4 Example: Scripting ```xml ${file::greedy.groovy} #[{currency: vars.currency}] ``` As you can see, the main difference here is that now you can use DataWeave to generate the input parameters. ## Accessing Variables from the Script The previous example uses a variable to show how to pass parameters into the script, it’s best to keep the script decoupled from the rest of the flow, so that changes to the Mule applications don’t require changes to the script. However, you can still access the variables from the script using the `vars` keyword. For example: Mule 4 Example: Accessing variables directly ```xml return "currency is " + vars.currency ``` To use the Scripting Module, simply add it to your application using the Studio palette or add the following dependency in your `pom.xml` file: ```xml org.mule.modules mule-scripting-module 1.1.0 mule-plugin ``` ## See Also - [Scripting Module Documentation](https://docs.mulesoft.com/scripting-module/latest/) --- product: Mule Runtime version: 4.3 --- # Migrating the Secure Properties Placeholder > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 3, the Secure Properties Placeholder was part of the Security Module. In Mule 4, it is separated in its own Secure Configuration Properties module. Example: Complete Secure Properties Placeholder in Mule 3 ```xml ``` Differences between Mule 3 and Mule 4: - The Mule 3 `location` attribute is replaced by `file` in Mule 4 for consistency with other components. - In Mule 3, `location` can define more than one file, separated by a comma (`,`). In Mule 4, this is not possible for troubleshooting purposes. Instead, you need to to define a `` tag for each file. - For overlapping properties between files, Mule 3 preserves the last definition. The Mule 4 module preserves the first definition. - The encryption attributes (`mode` and `algorithm`) are defined in the child tag ``, and the supported algorithms and modes are the same for both Mule 3 and 4 (see [Mule 4 Secure Configuration Properties](https://docs.mulesoft.com/mule-runtime/4.3/secure-configuration-properties)). A full migration of the Mule 3 example looks like this: Example: Complete Migration Example ```xml ``` ## See Also [Mule 4 Secure Configuration Properties](https://docs.mulesoft.com/mule-runtime/4.3/secure-configuration-properties) --- product: Mule Runtime version: 4.4 --- # Migrating the Secure Properties Placeholder > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 3, the Secure Properties Placeholder was part of the Security Module. In Mule 4, it is separated in its own Secure Configuration Properties module. Example: Complete Secure Properties Placeholder in Mule 3 ```xml ``` Differences between Mule 3 and Mule 4: - The Mule 3 `location` attribute is replaced by `file` in Mule 4 for consistency with other components. - In Mule 3, `location` can define more than one file, separated by a comma (`,`). In Mule 4, this is not possible for troubleshooting purposes. Instead, you need to to define a `` tag for each file. - For overlapping properties between files, Mule 3 preserves the last definition. The Mule 4 module preserves the first definition. - The encryption attributes (`mode` and `algorithm`) are defined in the child tag ``, and the supported algorithms and modes are the same for both Mule 3 and 4 (see [Mule 4 Secure Configuration Properties](https://docs.mulesoft.com/mule-runtime/4.4/secure-configuration-properties)). A full migration of the Mule 3 example looks like this: Example: Complete Migration Example ```xml ``` ## See Also [Mule 4 Secure Configuration Properties](https://docs.mulesoft.com/mule-runtime/4.4/secure-configuration-properties) --- product: Mule Runtime version: 4.3 --- # Migrating the Security Filters > For the full documentation index, see: https://docs.mulesoft.com/llms.txt In Mule 3, the Security Filters where part of the Mule Module Security. In Mule 4, this where migrated to the [Mule Validation Module](https://docs.mulesoft.com/validation-connector/latest/). ## IP filters In mule 3 we had three different options to filter by IP: \* `` \* `` \* `` ### Filtering By one IP Example: Filtering by one IP in Mule 3 ```xml ``` This will filter those IPs that matches the regex. In mule4: Example: Filtering by one IP in Mule 4 ```xml ``` Where is necessary to set that `ip` variable (or whichever variable suits). ### Filtering by range of IPs In mule 3, we had two ways of defining subnet mask to filter with: Example: Filtering by IP range in Mule 3 ```xml ``` Both are replaced by: Example: Filtering by IP range in Mule 4 ```xml ``` Where is necessary to set that `ip` variable (or whichever variable suits). 1. _Are there other similar validations added in mule 4?_ Yes, there is also a WhiteList validation, which only allows IPs from a IP Filter List. ## Time Expiration Filters In mule 3 we could filter the message if it had elapsed some defined time from a starting date. For example: Example: Filtering by elapsed time in Mule 3 ```xml ``` In Mule 4, this validation is in the validations module: Example: Filtering by elapsed time in Mule 4 ```xml ``` 1. _Are there other similar validations added in mule 4?_ Yes, there is also a Time Elapsed validation, which validates if the time elapsed has exceeded a certain amount of time. ## See Also [Validation Connector Technical Reference](https://docs.mulesoft.com/validation-connector/latest/validation-documentation) --- product: Mule Runtime version: 4.4 --- # Migrating the Security Filters > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!NOTE] Where possible, we changed noninclusive terms to align with our company value of Equality. > We maintained certain terms to avoid any effect on customer implementations. In Mule 3, the Security Filters where part of the Mule Module Security. In Mule 4, this where migrated to the [Mule Validation Module](https://docs.mulesoft.com/validation-connector/latest/). ## IP filters In mule 3 we had three different options to filter by IP: \* `` \* `` \* `` ### Filtering By one IP Example: Filtering by one IP in Mule 3 ```xml ``` This will filter those IPs that matches the regex. In mule4: Example: Filtering by one IP in Mule 4 ```xml ``` Where is necessary to set that `ip` variable (or whichever variable suits). ### Filtering by range of IPs In mule 3, we had two ways of defining subnet mask to filter with: Example: Filtering by IP range in Mule 3 ```xml ``` Both are replaced by: Example: Filtering by IP range in Mule 4 ```xml ``` Where is necessary to set that `ip` variable (or whichever variable suits). 1. _Are there other similar validations added in mule 4?_ Yes, there is also a WhiteList validation, which only allows IPs from a IP Filter List. ## Time Expiration Filters In mule 3 we could filter the message if it had elapsed some defined time from a starting date. For example: Example: Filtering by elapsed time in Mule 3 ```xml ``` In Mule 4, this validation is in the validations module: Example: Filtering by elapsed time in Mule 4 ```xml ``` 1. _Are there other similar validations added in mule 4?_ Yes, there is also a Time Elapsed validation, which validates if the time elapsed has exceeded a certain amount of time. ## See Also [Validation Connector Technical Reference](https://docs.mulesoft.com/validation-connector/latest/validation-documentation) --- product: Mule Runtime version: 4.3 --- # Migrating the Spring Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 3 allowed to define Spring beans as part of the Mule application using the Spring DSL directly. This approach requires Mule applications to be exposed to the Spring versions and components that the runtime uses internally. This causes two problems: - Users were limited to the Spring version and modules available in the Mule runtime. - Any changes or upgrades in the runtime can potentially affect applications defining To fix this problem in Mule 4, we decided to package our Spring support as a separate module. So, instead of defining your Spring beans directly on your application, you now have to define them in their own file and reference them through the Spring module. Mule 3 example: ```xml ... ``` Mule 4 example: ```xml ... ``` > [!TIP] See [Spring Module](https://docs.mulesoft.com/spring-module/latest/) to find an example XML file and also > further configuration instructions. ## Configure Spring Module Dependencies in Mule 4 The Spring Module does not include any Spring dependency, you need to configure the dependencies you want to use. Because Mule connector dependencies are isolated from each other and from the Mule application dependencies, after configuring Spring dependencies you also have to declare them as shared libraries to make these dependencies available for the Spring Module. To configure Spring dependencies and also declare them as shared libraries, add the following to your application’s `pom.xml`: ```xml 4.3.17.RELEASE 4.2.6.RELEASE 3.4.0 org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} org.springframework.security spring-security-core org.springframework spring-beans org.springframework spring-context org.springframework spring-core org.springframework.security spring-security-config org.springframework.security spring-security-core ${springSecurityVersion} org.springframework spring-beans ${springVersion} org.springframework spring-context ${springVersion} org.springframework spring-core ${springVersion} org.springframework.security spring-security-config ${springSecurityVersion} ``` ## Add the Spring Module to your Mule 4 Project To use the Spring module, add it to your application using the Studio palette or add the following dependency in your `pom.xml` file: ```xml org.mule.modules mule-spring-module 1.2.0 mule-plugin ``` ## See Also - [Spring Module in Mule 4](https://docs.mulesoft.com/spring-module/latest/) - [Configure Shared Libraries in Mule 4](https://docs.mulesoft.com/mule-runtime/4.3/mmp-concept#configure-shared-libraries) - [Class-loading Isolation in Mule 4](https://docs.mulesoft.com/mule-runtime/4.3/about-classloading-isolation) --- product: Mule Runtime version: 4.4 --- # Migrating the Spring Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 3 allowed to define Spring beans as part of the Mule application using the Spring DSL directly. This approach requires Mule applications to be exposed to the Spring versions and components that the runtime uses internally. This causes two problems: - Users were limited to the Spring version and modules available in the Mule runtime. - Any changes or upgrades in the runtime can potentially affect applications defining To fix this problem in Mule 4, we decided to package our Spring support as a separate module. So, instead of defining your Spring beans directly on your application, you now have to define them in their own file and reference them through the Spring module. Mule 3 example: ```xml ... ``` Mule 4 example: ```xml ... ``` > [!TIP] See [Spring Module](https://docs.mulesoft.com/spring-module/latest/) to find an example XML file and also > further configuration instructions. ## Configure Spring Module Dependencies in Mule 4 The Spring Module does not include any Spring dependency, you need to configure the dependencies you want to use. Because Mule connector dependencies are isolated from each other and from the Mule application dependencies, after configuring Spring dependencies you also have to declare them as shared libraries to make these dependencies available for the Spring Module. To configure Spring dependencies and also declare them as shared libraries, add the following to your application’s `pom.xml`: ```xml 4.3.17.RELEASE 4.2.6.RELEASE 3.4.0 org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} org.springframework.security spring-security-core org.springframework spring-beans org.springframework spring-context org.springframework spring-core org.springframework.security spring-security-config org.springframework.security spring-security-core ${springSecurityVersion} org.springframework spring-beans ${springVersion} org.springframework spring-context ${springVersion} org.springframework spring-core ${springVersion} org.springframework.security spring-security-config ${springSecurityVersion} ``` ## Add the Spring Module to your Mule 4 Project To use the Spring module, add it to your application using the Studio palette or add the following dependency in your `pom.xml` file: ```xml org.mule.modules mule-spring-module 1.2.0 mule-plugin ``` ## See Also - [Spring Module in Mule 4](https://docs.mulesoft.com/spring-module/latest/) - [Configure Shared Libraries in Mule 4](https://docs.mulesoft.com/mule-runtime/4.4/mmp-concept#configure-shared-libraries) - [Class-loading Isolation in Mule 4](https://docs.mulesoft.com/mule-runtime/4.4/about-classloading-isolation) --- product: Mule Runtime version: 4.3 --- # Migrating the Until Successful > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Until Successful component for Mule 4 handles some processes differently than the Mule 3 version. Some elements and attributes associated with these changes are no longer present in Mule 4. In Mule 4, you can either achieve the same functionality through different attributes or components, or you no longer need to configure the functionality in Mule 4. A manual migration of the Until Successful component involves these modifications: - Removal of any `` elements. - Replacement of the `secondsBetweenRetries` attribute with `millisBetweenRetries`. - Removal of the `failureExpression` and use of a Validation processor for Mule 4, instead. - Replacement of the `deadLetterQueue-ref` attribute with an Error Handler for Mule 4. - Removal of any `` elements. - Removal of the `ackExpression` attribute and use of a Set Payload component, instead. - Removal of any `synchronous` attributes. These changes are detailed in the next sections. ## Processor Chains Not Used in Mule 4 In Mule 3, executing more than one processor inside the Until Successful scope requires you to wrap the processors inside a processor chain (``). In Mule 4, Until Successful supports multiple processors without the need for a processor chain. Mule 3: ```xml ``` Notice that in the Mule 4 example, the `` element is not present. Mule 4: ```xml ``` ## Retry Attributes Revised in Mule 4 The Mule 3 `secondsBetweenRetries` attribute has been removed from Mule 4. You can use the `millisBetweenRetries` attribute in Mule 4. Mule 3: ```xml ``` The Mule 4 example replaces `secondsBetweenRetries="10"` with `millisBetweenRetries="10000"`. Mule 4: ```xml ``` ## Failure Expressions Require Modifications The `failureExpression` attribute has been removed. You can replace it with a Validation processor that sets your verification expression. Mule 3: ```xml ``` The `failureExpression` setting in the Mule 3 example is replaced by a `` configuration in Mule 4. Mule 4: ```xml ``` ## Dead Letter Queue Reference through Mule 4 Error Handler The Mule 3 `deadLetterQueue-ref` attribute enables you to send undeliverable messages to an endpoint or processor once all retries result in failure. In Mule 4, you can instead use an error handler to catch all the `RETRY_EXHAUSTED` exceptions and send the message to that endpoint or processor. Mule 3: ```xml ``` The Mule 4 example references the `dlqChannel` through the On Error Propagate `` element within an Error Handler ``. Mule 4: ```xml ``` ## Threading Profile Removed, Not Needed in Mule 4 In Mule 3, you can tune execution threads using the `` child element. Mule 4 introduces several changes to the execution engine. Because of the associated non-blocking architecture in Mule 4, you no longer need to tune threads manually. Mule 3: ```xml ``` The Mule 4 example removes the `` element. Mule 4: ```xml ``` ## ackExpression Attribute Removed, Use Set Payload The Mule 3 `ackExpression` attribute configures synchronous production of a response payload. This attribute no longer exists in Mule 4. To achieve this behavior in your app, you can configure a Set Payload component after Until Successful. Mule 3: ```xml ``` The Mule 4 example sets the `#[message:correlationId]` value through the Set Payload `` component. Mule 4: ```xml ``` ## Synchronous Attribute Removed, Not Needed The `synchronous` attribute has been removed because it is no longer needed. In Mule 4, several changes were introduced to the execution engine. With the non-blocking architecture, you no longer need it. ## See Also - [Introduction to Mule 4: Execution Engine Threads and Concurrency](https://docs.mulesoft.com/mule-runtime/4.3/intro-engine). - [Execution Engine](https://docs.mulesoft.com/mule-runtime/4.3/execution-engine) - [Until Successful Scope](https://docs.mulesoft.com/mule-runtime/4.3/until-successful-scope) --- product: Mule Runtime version: 4.4 --- # Migrating the Until Successful > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Until Successful component for Mule 4 handles some processes differently than the Mule 3 version. Some elements and attributes associated with these changes are no longer present in Mule 4. In Mule 4, you can either achieve the same functionality through different attributes or components, or you no longer need to configure the functionality in Mule 4. A manual migration of the Until Successful component involves these modifications: - Removal of any `` elements. - Replacement of the `secondsBetweenRetries` attribute with `millisBetweenRetries`. - Removal of the `failureExpression` and use of a Validation processor for Mule 4, instead. - Replacement of the `deadLetterQueue-ref` attribute with an Error Handler for Mule 4. - Removal of any `` elements. - Removal of the `ackExpression` attribute and use of a Set Payload component, instead. - Removal of any `synchronous` attributes. These changes are detailed in the next sections. ## Processor Chains Not Used in Mule 4 In Mule 3, executing more than one processor inside the Until Successful scope requires you to wrap the processors inside a processor chain (``). In Mule 4, Until Successful supports multiple processors without the need for a processor chain. Mule 3: ```xml ``` Notice that in the Mule 4 example, the `` element is not present. Mule 4: ```xml ``` ## Retry Attributes Revised in Mule 4 The Mule 3 `secondsBetweenRetries` attribute has been removed from Mule 4. You can use the `millisBetweenRetries` attribute in Mule 4. Mule 3: ```xml ``` The Mule 4 example replaces `secondsBetweenRetries="10"` with `millisBetweenRetries="10000"`. Mule 4: ```xml ``` ## Failure Expressions Require Modifications The `failureExpression` attribute has been removed. You can replace it with a Validation processor that sets your verification expression. Mule 3: ```xml ``` The `failureExpression` setting in the Mule 3 example is replaced by a `` configuration in Mule 4. Mule 4: ```xml ``` ## Dead Letter Queue Reference through Mule 4 Error Handler The Mule 3 `deadLetterQueue-ref` attribute enables you to send undeliverable messages to an endpoint or processor once all retries result in failure. In Mule 4, you can instead use an error handler to catch all the `RETRY_EXHAUSTED` exceptions and send the message to that endpoint or processor. Mule 3: ```xml ``` The Mule 4 example references the `dlqChannel` through the On Error Propagate `` element within an Error Handler ``. Mule 4: ```xml ``` ## Threading Profile Removed, Not Needed in Mule 4 In Mule 3, you can tune execution threads using the `` child element. Mule 4 introduces several changes to the execution engine. Because of the associated non-blocking architecture in Mule 4, you no longer need to tune threads manually. Mule 3: ```xml ``` The Mule 4 example removes the `` element. Mule 4: ```xml ``` ## ackExpression Attribute Removed, Use Set Payload The Mule 3 `ackExpression` attribute configures synchronous production of a response payload. This attribute no longer exists in Mule 4. To achieve this behavior in your app, you can configure a Set Payload component after Until Successful. Mule 3: ```xml ``` The Mule 4 example sets the `#[message:correlationId]` value through the Set Payload `` component. Mule 4: ```xml ``` ## Synchronous Attribute Removed, Not Needed The `synchronous` attribute has been removed because it is no longer needed. In Mule 4, several changes were introduced to the execution engine. With the non-blocking architecture, you no longer need it. ## See Also - [Introduction to Mule 4: Execution Engine Threads and Concurrency](https://docs.mulesoft.com/mule-runtime/4.4/intro-engine). - [Execution Engine](https://docs.mulesoft.com/mule-runtime/4.4/execution-engine) - [Until Successful Scope](https://docs.mulesoft.com/mule-runtime/4.4/until-successful-scope) --- product: Mule Runtime version: 4.3 --- # Migrating the Validation Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Validation Module in Mule 4 is very similar to the one in Mule 3. The most impacted areas between these mayor versions were error handling and support in expressions. Error handling is different because Mule 4 Extensions have a different way to declare errors through error types. Regarding expressions, Mule 4 only supports MEL expressions within the compatibility module, all other expressions must be DataWeave expressions. What’s covered in this section: - [Error Types](#errors) - [From functions in MEL Expressions to functions in DataWeave](#functions) - [The use of the All scope](#all_scope) - [Build a custom Validator](#custom_validator) ## Error Types In the Mule 3 Validation Module, any failure during a validation will throw the same exception or a configured one and you are able to customize the message depending on the error. On the other hand, in Mule 4, modules declare their own error types. In the case of this module, validation operations have different error types which implies the type of validation that have failed. In the case of the `all` scope, the type is **VALIDATION:MULTIPLE** regardless of the validation or validations that failed inside the `all` scope. You can still customize the error message or use a default one. The examples below show validators that will fail if the variable email is not a possible valid email. Mule 3 example ```xml ``` If this validation fails, a **ValidationException** will be thrown. Mule 4 example ```xml ``` If this validation fails, the error will be of type **VALIDATION:INVALID\_EMAIL**. ## From functions in MEL Expressions to functions in DataWeave In the same way that in Mule 3 you could execute validation in expressions, you can do that in Mule 4. The difference is that in Mule 4, these validations are called within DataWeave expressions instead of MEL expressions. This is the list of supported functions in Mule 4 : `isEmail`, `matchesRegex`, `isTime`, `isNumber`, `isIp` and `isUrl` In the examples below we can see how to execute different operations depending if the content on a variable named unknownVariable is: a valid email, a valid Url or neither of those. Mule 3 example ```xml ``` Inside the MEL expression we used validator to access to the validation methods. Mule 4 example ```xml ``` In the Validation module, there are functions declared to be called from within DataWeave expressions. Like any other function in Mule 4, they are invoked using ExtensionName::functionName , in this case `Validation::isEmail(vars.email)`. ## The use of the All scope In Mule 4 You can still group a set of validation the same way you did in Mule 3, only a minor part of the dsl has changed. Mule 3 example ```xml ``` Mule 4 example ```xml ``` ## Build a custom Validator Custom Validators were replaced with the Extension Validators, these Validators are just like operations with the difference that they always return void. In order to signal that the validation have failed, the java method should throw a `ModuleException` with the respective error type. Through the usage of these Validators we can create our own error types that better explain the validation that failed and the user experience of using them is just like using any other operation. For more depth of what extension validators are, see the Extension Validators Documentation. **Note:** these validators can also be used inside the `all` validation scope. Let’s see how to migrate a Mule 3 Custom Validator into Mule 4. In the examples below, we can see that we used to get the whole event, and from it we took the information that we needed for the validation. In the Mule 4 example, we give the Validator only with the desired parameters. Mule 3 example This is how the Custom Validator used to look in the dsl. ```xml ``` This is how the Validator interface was implemented, see that the information you took for the validation had to be on specific parts of the message, in this case the flow variables price and balance. ```java public class BalanceValidator implements Validator { @Override public ValidationResult validate(MuleEvent event) { Integer price = new Integer((String) event.getMessage().getInvocationProperty("price")); Integer balance = new Integer((String) event.getMessage().getInvocationProperty("balance")); return new ValidationResult() { @Override public boolean isError() { return price > balance; } @Override public String getMessage() { return "There is not enough money to make the transaction"; } }; } } ``` Mule 4 example This is how you use Extension Validators in Mule 4, we can see that the namespace and tag name are more descriptive to what we are validating. Also, the parameters here are part of the dsl and we can put the expression here instead of having to set it to a variable before. ```xml ``` To achieve this we create a simple extension named `balance`: ```java @Operations({BalanceOperations.class}) @Extension(name = "balance") @ErrorTypes(BalanceError.class) public class BalanceExtension { } ``` In the `BalanceOperations` class we add our validation method and we annotate it with `@Validator`. The method needs to throw an error type which comes from the generic validation error type. ```java public class BalanceOperations { @Validator @Throws(BalanceErrorsProvider.class) public void hasSufficientFunds(Integer balance, Integer price) throws Exception { if (price > balance){ throw new ModuleException(BalanceError.INSUFFICIENT_FUNDS, new IllegalArgumentException("There is not enough money to make the transaction")); } } } ``` Here we create the error that will be thrown if the validation fails. See that is has a name according to the validations failure. ```java public enum BalanceError implements ErrorTypeDefinition { INSUFFICIENT_FUNDS(MuleErrors.VALIDATION); private ErrorTypeDefinition> parent; BalanceError(ErrorTypeDefinition> parent) { this.parent = parent; } @Override public Optional>> getParent() { return Optional.ofNullable(parent); } } ``` The Validator method needs an `ErrorTypeProvider` that knows all the error types the validation can throw, in this case we create an `ErrorTypeProvider` that says that the only error the method can throw is of type **BALANCE:INSUFFICIENT\_FUNDS** ```java public class BalanceErrorsProvider implements ErrorTypeProvider { @Override public Set getErrorTypes() { HashSet errors = new HashSet<>(); errors.add(BalanceError.INSUFFICIENT_FUNDS); return errors; } } ``` --- product: Mule Runtime version: 4.4 --- # Migrating the Validation Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Validation Module in Mule 4 is very similar to the one in Mule 3. The most impacted areas between these mayor versions were error handling and support in expressions. Error handling is different because Mule 4 Extensions have a different way to declare errors through error types. Regarding expressions, Mule 4 only supports MEL expressions within the compatibility module, all other expressions must be DataWeave expressions. What’s covered in this section: - [Error Types](#errors) - [From functions in MEL Expressions to functions in DataWeave](#functions) - [The use of the All scope](#all_scope) - [Build a custom Validator](#custom_validator) ## Error Types In the Mule 3 Validation Module, any failure during a validation will throw the same exception or a configured one and you are able to customize the message depending on the error. On the other hand, in Mule 4, modules declare their own error types. In the case of this module, validation operations have different error types which implies the type of validation that have failed. In the case of the `all` scope, the type is **VALIDATION:MULTIPLE** regardless of the validation or validations that failed inside the `all` scope. You can still customize the error message or use a default one. The examples below show validators that will fail if the variable email is not a possible valid email. Mule 3 example ```xml ``` If this validation fails, a **ValidationException** will be thrown. Mule 4 example ```xml ``` If this validation fails, the error will be of type **VALIDATION:INVALID\_EMAIL**. ## From functions in MEL Expressions to functions in DataWeave In the same way that in Mule 3 you could execute validation in expressions, you can do that in Mule 4. The difference is that in Mule 4, these validations are called within DataWeave expressions instead of MEL expressions. This is the list of supported functions in Mule 4 : `isEmail`, `matchesRegex`, `isTime`, `isNumber`, `isIp` and `isUrl` In the examples below we can see how to execute different operations depending if the content on a variable named unknownVariable is: a valid email, a valid Url or neither of those. Mule 3 example ```xml ``` Inside the MEL expression we used validator to access to the validation methods. Mule 4 example ```xml ``` In the Validation module, there are functions declared to be called from within DataWeave expressions. Like any other function in Mule 4, they are invoked using ExtensionName::functionName , in this case `Validation::isEmail(vars.email)`. ## The use of the All scope In Mule 4 You can still group a set of validation the same way you did in Mule 3, only a minor part of the dsl has changed. Mule 3 example ```xml ``` Mule 4 example ```xml ``` ## Build a custom Validator Custom Validators were replaced with the Extension Validators, these Validators are just like operations with the difference that they always return void. In order to signal that the validation have failed, the java method should throw a `ModuleException` with the respective error type. Through the usage of these Validators we can create our own error types that better explain the validation that failed and the user experience of using them is just like using any other operation. For more depth of what extension validators are, see the Extension Validators Documentation. **Note:** these validators can also be used inside the `all` validation scope. Let’s see how to migrate a Mule 3 Custom Validator into Mule 4. In the examples below, we can see that we used to get the whole event, and from it we took the information that we needed for the validation. In the Mule 4 example, we give the Validator only with the desired parameters. Mule 3 example This is how the Custom Validator used to look in the dsl. ```xml ``` This is how the Validator interface was implemented, see that the information you took for the validation had to be on specific parts of the message, in this case the flow variables price and balance. ```java public class BalanceValidator implements Validator { @Override public ValidationResult validate(MuleEvent event) { Integer price = new Integer((String) event.getMessage().getInvocationProperty("price")); Integer balance = new Integer((String) event.getMessage().getInvocationProperty("balance")); return new ValidationResult() { @Override public boolean isError() { return price > balance; } @Override public String getMessage() { return "There is not enough money to make the transaction"; } }; } } ``` Mule 4 example This is how you use Extension Validators in Mule 4, we can see that the namespace and tag name are more descriptive to what we are validating. Also, the parameters here are part of the dsl and we can put the expression here instead of having to set it to a variable before. ```xml ``` To achieve this we create a simple extension named `balance`: ```java @Operations({BalanceOperations.class}) @Extension(name = "balance") @ErrorTypes(BalanceError.class) public class BalanceExtension { } ``` In the `BalanceOperations` class we add our validation method and we annotate it with `@Validator`. The method needs to throw an error type which comes from the generic validation error type. ```java public class BalanceOperations { @Validator @Throws(BalanceErrorsProvider.class) public void hasSufficientFunds(Integer balance, Integer price) throws Exception { if (price > balance){ throw new ModuleException(BalanceError.INSUFFICIENT_FUNDS, new IllegalArgumentException("There is not enough money to make the transaction")); } } } ``` Here we create the error that will be thrown if the validation fails. See that is has a name according to the validations failure. ```java public enum BalanceError implements ErrorTypeDefinition { INSUFFICIENT_FUNDS(MuleErrors.VALIDATION); private ErrorTypeDefinition> parent; BalanceError(ErrorTypeDefinition> parent) { this.parent = parent; } @Override public Optional>> getParent() { return Optional.ofNullable(parent); } } ``` The Validator method needs an `ErrorTypeProvider` that knows all the error types the validation can throw, in this case we create an `ErrorTypeProvider` that says that the only error the method can throw is of type **BALANCE:INSUFFICIENT\_FUNDS** ```java public class BalanceErrorsProvider implements ErrorTypeProvider { @Override public Set getErrorTypes() { HashSet errors = new HashSet<>(); errors.add(BalanceError.INSUFFICIENT_FUNDS); return errors; } } ``` --- product: Mule Runtime version: 4.3 --- # Migrating the VM Transport > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The VM transport was completely rewritten. It evolved away from the Mule 3 transport model into an operation-based connector. This enables many new capabilities: - The ability to consume messages from a queue on demand, unlike the old transport, which only provided a polling inbound endpoint. - Enhanced [DataSense](https://docs.mulesoft.com/studio/datasense-explorer). ## What’s Covered Here? - [Migrating VM Transport Configurations](#file_configs) - [Migrating an Inbound Endpoint](#vm_listener) - [Migrating an Outbound Endpoint](#vm_outbound) ## Migrating VM Transport Configurations In Mule 3, all transport configurations are set under a top-level element called ``. Each configuration could handle multiple queues, but with the limitation that all of them had to be either transient or persistent. Two separate transport configs were needed in order to combine transient and persistent. Mule 3 Example: Defining a Persistent VM Transport ```xml ``` In Mule 4, each connector configuration defines the queues that it is going to handle in advance. Each of these queues can have their own settings, allowing for clarity and flexibility. However, each config can ONLY access the queues it has defined. This is a restriction put in place to avoid publishing to a queue in which nobody is listening, which is a common mistake. Mule 4 Example: Defining a VM connector config ```xml ``` ## Migrating an Inbound Endpoint In Mule 3, a `` message source was used to listen on a specific queue for messages. For each element in the queue, a new message was triggered. Mule 3 Example: VM Inbound Endpoint ```xml ... ``` This configuration defines a transactional inbound endpoint which listens to a queue called `persistentQueue`. Also, the `exchange-pattern` parameter was used to determine if the flow was to send a response or not. If configured to `request-response`, the endpoint responds with whatever message was obtained at the end of the flow (more on this on the [Migrating an Outbound Endpoint](#vm_outbound) section). In Mule 4, the `` message source is used instead: Mule 4 Example: VM listener ```xml #[lower(payload.salute)] ... ``` Main differences are: - The listener points to a config and can only listen to a queue defined in that config. - Now, you can use the `` element to control the response. If not provided, the message payload that results at the end of the flow will be settings. - You no longer need to use an `exchange-pattern` to control whether or not a response is sent. The connector automatically knows when to send it depending on the message being generated through the `` or `` operations. ### Listening for Messages In Order Another inbound endpoint use case was listening for messages in order. In Mule 3, this had to be configured at the connector level using the `numberOfConcurrentTransactedReceivers` parameters. Mule 3 Example: Listening for Messages In Order ```xml ``` In Mule 4, you can now do it at the listener level: Mule 4 Example: Listening for Messages In Order ```xml ... ``` By setting both, the flow’s `maxConcurrency` and the listener’s `numberOfConsumers` to 1, you can process the messages in order. ## Migrating an Outbound Endpoint The Mule 3 transport uses the `` component to publish a message into a queue: Mule 3 Example: Posting a Message to a Queue ```xml ``` The `exchange-pattern` parameters play a key role in the behavior of the example above. If the pattern is `one-way`, then the message will be sent and the execution continues with the same message payload. If `request-response` is used, then the execution waits for a response coming from a flow with a `` listening on the same queue, and the obtained response is then propagated to the next message processor. Mule 4 achieves this through two different operations: Mule 4 Example: Posting a Message to a Queue ```xml #[upper(payload)] #[upper(payload)] ``` Both operation are configured similarly and allow you to use DataWeave to build the content of the message being sent. However, while the `` operation publishes the content and continues with the same message, the `` operation will wait for the response emitted by the `` of the referenced queue. To use the VM connector, simply add it to your application using the Studio palette, or add the following dependency in your `pom.xml` file: ```xml org.mule.connectors mule-vm-connector 1.1.0 mule-plugin ``` ## See also - [About the File Connector](https://docs.mulesoft.com/file-connector/latest/) --- product: Mule Runtime version: 4.4 --- # Migrating the VM Transport > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The VM transport was completely rewritten. It evolved away from the Mule 3 transport model into an operation-based connector. This enables many new capabilities: - The ability to consume messages from a queue on demand, unlike the old transport, which only provided a polling inbound endpoint. - Enhanced [DataSense](https://docs.mulesoft.com/studio/datasense-explorer). ## What’s Covered Here? - [Migrating VM Transport Configurations](#file_configs) - [Migrating an Inbound Endpoint](#vm_listener) - [Migrating an Outbound Endpoint](#vm_outbound) ## Migrating VM Transport Configurations In Mule 3, all transport configurations are set under a top-level element called ``. Each configuration could handle multiple queues, but with the limitation that all of them had to be either transient or persistent. Two separate transport configs were needed in order to combine transient and persistent. Mule 3 Example: Defining a Persistent VM Transport ```xml ``` In Mule 4, each connector configuration defines the queues that it is going to handle in advance. Each of these queues can have their own settings, allowing for clarity and flexibility. However, each config can ONLY access the queues it has defined. This is a restriction put in place to avoid publishing to a queue in which nobody is listening, which is a common mistake. Mule 4 Example: Defining a VM connector config ```xml ``` ## Migrating an Inbound Endpoint In Mule 3, a `` message source was used to listen on a specific queue for messages. For each element in the queue, a new message was triggered. Mule 3 Example: VM Inbound Endpoint ```xml ... ``` This configuration defines a transactional inbound endpoint which listens to a queue called `persistentQueue`. Also, the `exchange-pattern` parameter was used to determine if the flow was to send a response or not. If configured to `request-response`, the endpoint responds with whatever message was obtained at the end of the flow (more on this on the [Migrating an Outbound Endpoint](#vm_outbound) section). In Mule 4, the `` event source is used instead: Mule 4 Example: VM listener ```xml #[lower(payload.salute)] ... ``` Main differences are: - The listener points to a config and can only listen to a queue defined in that config. - Now, you can use the `` element to control the response. If not provided, the message payload that results at the end of the flow will be settings. - You no longer need to use an `exchange-pattern` to control whether or not a response is sent. The connector automatically knows when to send it depending on the message being generated through the `` or `` operations. ### Listening for Messages In Order Another inbound endpoint use case was listening for messages in order. In Mule 3, this had to be configured at the connector level using the `numberOfConcurrentTransactedReceivers` parameters. Mule 3 Example: Listening for Messages In Order ```xml ``` In Mule 4, you can now do it at the listener level: Mule 4 Example: Listening for Messages In Order ```xml ... ``` By setting both, the flow’s `maxConcurrency` and the listener’s `numberOfConsumers` to 1, you can process the messages in order. ## Migrating an Outbound Endpoint The Mule 3 transport uses the `` component to publish a message into a queue: Mule 3 Example: Posting a Message to a Queue ```xml ``` The `exchange-pattern` parameters play a key role in the behavior of the example above. If the pattern is `one-way`, then the message will be sent and the execution continues with the same message payload. If `request-response` is used, then the execution waits for a response coming from a flow with a `` listening on the same queue, and the obtained response is then propagated to the next message processor. Mule 4 achieves this through two different operations: Mule 4 Example: Posting a Message to a Queue ```xml #[upper(payload)] #[upper(payload)] ``` Both operation are configured similarly and allow you to use DataWeave to build the content of the message being sent. However, while the `` operation publishes the content and continues with the same message, the `` operation will wait for the response emitted by the `` of the referenced queue. To use the VM connector, simply add it to your application using the Studio palette, or add the following dependency in your `pom.xml` file: ```xml org.mule.connectors mule-vm-connector 1.1.0 mule-plugin ``` ## See also - [About the File Connector](https://docs.mulesoft.com/file-connector/latest/) --- product: Mule Runtime version: 4.3 --- # Migrating the XML Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A new XML module in Mule 4 replaces the one that was bundled in with Mule 3. The main changes are: - Removal of components and expressions, functions, and evaluators that were deprecated in Mule 3.6: - jxpath-filter - jaxen-filter - jxpath-extractor-transformer - is-xml-filter - xpath-filter - Changes to XPath, XSLT, and XQuery components to be consistent with the new Mule 4 components, mainly around: - DSL namespace prefix changed from `mxml` to `xml-module` - Consistency of return types - Syntax and UX changes - `xpath()` and `xpath3()` functions replaced by a new `XmlModule::xpath()` function - Improved error reporting for the schema validator - `schema-validation-filter` now replaced with `schema-validator` - No longer tied to Java: It no longer uses SAX, StaX, or DOM types. Mule 4 is now strongly typed and we have mime type information about which data is in XML format. The runtime does the rest. All XML documents are represented as either Strings or streams. This means the following no longer exist (and are no longer needed): - dom-to-xml-transformer - dom-to-output-handler-transformer - xml-to-dom-transformer - xml-prettyprinter-transformer - jaxb-object-to-xml-transformer - jaxb-xml-to-object-transformer - jaxb-context - object-to-xml-transformer - xml-to-object-transformer ## Migrating XSLT Operations ### Use an XSL Style Sheet in an External File Mule 3 Example: To use an XSL sheet in an external file ```xml ``` In Mule 4: Mule 4 Example: To use an XSL sheet in an external file ```xml ${file:::cities.xslt} ``` ### Use Context Properties Mule 3 Example: To set context properties ```xml ``` Mule 4 Example: To set context properties ```xml ${file::cities.xslt} #[{'output_location': vars.outputFile, 'user_id': vars.userId}] ``` ## Migrating XPath Operations and Expressions ### Use the XPath Extractor Transformer The XPath extractor no longer supports custom `resultType` parameter. It will now always return a List of Strings with all the matching elements. Mule 3 Example: To use the XPath extractor ```xml ``` Mule 4 Example: To use the XPath extractor ```xml ``` ### Use the XPath Expression Function Mule 3 originally had an `xpath()` MEL function. In Mule 3.6, it was deprecated in favor of a new `xpath3()` function. Now, both functions are replaced by a new `XmlModule::xpath()` DataWeave function, which becomes available when the module is added to an application. Mule 3 Example: Using the xpath3 function ```xml ``` Mule 3’s `xpath3()` function allowed you to specify the XPath expression and the input value, and it gave different options in terms of the expected output: `BOOLEAN`, `STRING`, `NUMBER`, `NODESET` or `NODE`, where `NODESET` and `NODE` required understanding of Java’s representation of a DOM tree. The new function also accepts the XPath expression and the input, but differs in these ways: - It adds support for custom context properties. - It does not allow specification of the output type. It will always return a List of Strings, just as `` does. Mule 4 Example: Using the xpath function ```xml ``` > [!TIP] You can use this function inside any DataWeave transformation. ### Use XPath with Custom Namespaces In Mule 3, a `` is needed to map custom namespaces prefixes: Mule 3 Example: Using custom namespaces ```xml ``` This approach has the limitation that only one namespace-manager could be used per application. In Mule 4, you can declare as many `namespace-directory` elements as you want, and then reference the one you need on each operation: Mule 4 Example: Using custom namespaces ```xml ``` Additionally, you could even choose not to declare a 'namespace-directory' and instead just map the namespace inline: Mule 4 Example: Inline custom namespaces mapping ```xml ``` ## Migrating XQuery Operations The main difference is that in Mule 3, the output type of this transformer would depend on the result of the transformation: - If the transformation generates many elements, a List is returned. - Depending on the transformation, the elements of that list could be String or some generic Java representation, such as a `Node`. - If the transformation generates only one element, it returns that element. In Mule 4, this will always return a List of Strings. Other than that, changes are around syntax only: Mule 3 Example: Using XQuery transformer ```xml { for $b in $books/BOOKLIST/BOOKS/ITEM, $c in $cities/cities/city return } ]]> ``` In Mule 4: Mule 4 Example: Using XQuery transformer ```xml { for $b in fn:doc($books)/BOOKLIST/BOOKS/ITEM, $c in fn:doc($cities)/cities/city return } ]]> #[{'books' : vars.books, 'cities': vars.cities}] ``` ## Validating XML Against a Schema In Mule 3, a filter was used to validate schemas: Mule 3 Example: Schema validation filter ```xml ``` If the validation fails, the message is dropped. In Mule 4, we replaced filters with validators: Mule 4 Example: Schema validator ```xml ``` This validator will raise an `XML-MODULE:SCHEMA_NOT_HONOURED` error. ## Installing the XML Module To use the XML module, simply add it to your application using the Studio palette, or add the following dependency in your `pom.xml` file: ```xml org.mule.modules mule-xml-module 1.1.0 mule-plugin ``` ## See also - [XML Module](https://docs.mulesoft.com/xml-module/latest/) --- product: Mule Runtime version: 4.4 --- # Migrating the XML Module > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A new XML module in Mule 4 replaces the one that was bundled in with Mule 3. The main changes are: - Removal of components and expressions, functions, and evaluators that were deprecated in Mule 3.6: - jxpath-filter - jaxen-filter - jxpath-extractor-transformer - is-xml-filter - xpath-filter - Changes to XPath, XSLT, and XQuery components to be consistent with the new Mule 4 components, mainly around: - DSL namespace prefix changed from `mxml` to `xml-module` - Consistency of return types - Syntax and UX changes - `xpath()` and `xpath3()` functions replaced by a new `XmlModule::xpath()` function - Improved error reporting for the schema validator - `schema-validation-filter` now replaced with `schema-validator` - No longer tied to Java: It no longer uses SAX, StaX, or DOM types. Mule 4 is now strongly typed and we have mime type information about which data is in XML format. The runtime does the rest. All XML documents are represented as either Strings or streams. This means the following no longer exist (and are no longer needed): - dom-to-xml-transformer - dom-to-output-handler-transformer - xml-to-dom-transformer - xml-prettyprinter-transformer - jaxb-object-to-xml-transformer - jaxb-xml-to-object-transformer - jaxb-context - object-to-xml-transformer - xml-to-object-transformer ## Migrating XSLT Operations ### Use an XSL Style Sheet in an External File Mule 3 Example: To use an XSL sheet in an external file ```xml ``` In Mule 4: Mule 4 Example: To use an XSL sheet in an external file ```xml ${file:::cities.xslt} ``` ### Use Context Properties Mule 3 Example: To set context properties ```xml ``` Mule 4 Example: To set context properties ```xml ${file::cities.xslt} #[{'output_location': vars.outputFile, 'user_id': vars.userId}] ``` ## Migrating XPath Operations and Expressions ### Use the XPath Extractor Transformer The XPath extractor no longer supports custom `resultType` parameter. It will now always return a List of Strings with all the matching elements. Mule 3 Example: To use the XPath extractor ```xml ``` Mule 4 Example: To use the XPath extractor ```xml ``` ### Use the XPath Expression Function Mule 3 originally had an `xpath()` MEL function. In Mule 3.6, it was deprecated in favor of a new `xpath3()` function. Now, both functions are replaced by a new `XmlModule::xpath()` DataWeave function, which becomes available when the module is added to an application. Mule 3 Example: Using the xpath3 function ```xml ``` Mule 3’s `xpath3()` function allowed you to specify the XPath expression and the input value, and it gave different options in terms of the expected output: `BOOLEAN`, `STRING`, `NUMBER`, `NODESET` or `NODE`, where `NODESET` and `NODE` required understanding of Java’s representation of a DOM tree. The new function also accepts the XPath expression and the input, but differs in these ways: - It adds support for custom context properties. - It does not allow specification of the output type. It will always return a List of Strings, just as `` does. Mule 4 Example: Using the xpath function ```xml ``` > [!TIP] You can use this function inside any DataWeave transformation. ### Use XPath with Custom Namespaces In Mule 3, a `` is needed to map custom namespaces prefixes: Mule 3 Example: Using custom namespaces ```xml ``` This approach has the limitation that only one namespace-manager could be used per application. In Mule 4, you can declare as many `namespace-directory` elements as you want, and then reference the one you need on each operation: Mule 4 Example: Using custom namespaces ```xml ``` Additionally, you could even choose not to declare a 'namespace-directory' and instead just map the namespace inline: Mule 4 Example: Inline custom namespaces mapping ```xml ``` ## Migrating XQuery Operations The main difference is that in Mule 3, the output type of this transformer would depend on the result of the transformation: - If the transformation generates many elements, a List is returned. - Depending on the transformation, the elements of that list could be String or some generic Java representation, such as a `Node`. - If the transformation generates only one element, it returns that element. In Mule 4, this will always return a List of Strings. Other than that, changes are around syntax only: Mule 3 Example: Using XQuery transformer ```xml { for $b in $books/BOOKLIST/BOOKS/ITEM, $c in $cities/cities/city return } ]]> ``` In Mule 4: Mule 4 Example: Using XQuery transformer ```xml { for $b in fn:doc($books)/BOOKLIST/BOOKS/ITEM, $c in fn:doc($cities)/cities/city return } ]]> #[{'books' : vars.books, 'cities': vars.cities}] ``` ## Validating XML Against a Schema In Mule 3, a filter was used to validate schemas: Mule 3 Example: Schema validation filter ```xml ``` If the validation fails, the message is dropped. In Mule 4, we replaced filters with validators: Mule 4 Example: Schema validator ```xml ``` This validator will raise an `XML-MODULE:SCHEMA_NOT_HONOURED` error. ## Installing the XML Module To use the XML module, simply add it to your application using the Studio palette, or add the following dependency in your `pom.xml` file: ```xml org.mule.modules mule-xml-module 1.1.0 mule-plugin ``` ## See also - [XML Module](https://docs.mulesoft.com/xml-module/latest/) --- product: Mule Runtime version: 4.3 --- # Migrating to the AMQP Connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As in other cases the AMQP connector was completely reshaped and evolved away from the Mule 3 transport model into an operation based connector with a simplified UX and fully DataSense enabled Message information. This means not only that using AMQP now provides the same experience regarding connection and configuration that any other connector, but also that publishing and consuming messages is simpler based on the structured Message information. ## Configuring The Connector Moving from a 3.x transport configuration to a AMQP Connector configuration in Mule 4 implies basically using most of the same parameters, but declaring them in a more cohesive way. Some parameters changed in Mule 4 AMQP Connector. This means for example that parameters that are used for consuming Messages are declared in a 'consumer-config' group, while general authentication parameters are configured in the General group. Also, a separation has been made between the parameters that affect the behavior of the connector (present in the config) from those that affect only how the connection is established (present at connection level): Mule 3 Example: Configuring The Connector ```xml ``` This same configuration is achieved in Mule 4 setting the same parameters in the context where they actually apply: Mule 4 Example: Configuring The Connector ```xml ``` Notice that `fallbackAddresses` is not supported anymore. ## Sending Messages With the new Mule 4 approach, the AMQP 'publish' operation relies only on its input parameters to completely build the AMQP Message to be published. For example, if we wanted to send a high priority AMQP Message with only a part of the payload in the body, and associate that Message to a group, we’ll need to: <1>) Use `transform` to set the payload to what the Message body is expected to be. <2>) Convert the resulting stream into a String to send it as a text message. <3>) Set an AMQP property with `priority` as key to set the AMQP Message Priority. Mule 3 Example: Sending a prioritized Message as part of a Group ```xml (1) (2) (3) ``` The same results can be achieved in Mule 4 using the AMQP Connector with the following configuration: Mule 4 Example: Sending a prioritized Message as part of a Group ```xml (2) (1) #[output application/json --- { order_id: payload.id, supplier: payload.warehouse }] (3) ``` Differences to be noted: 1. There’s no need of the `transform` component, since the `body` of the Message is created inline, thus the payload remains unmodified. 2) The `object-to-string` transformer was also removed, since the Connector can automatically handle the transformation output. 3) Priority is set as a property in the AmqpMessage operation and does not rely on the user knowing the exact key. As a summary, when publishing a Message in 3.x with the AMQP transport, we relied on the AmqpMessage payload, and outbound properties to configure the creation of the AMQP Message, which meant a deeper knowledge of how the transport worked. In 4.x, the AMQP Connector exposes every configurable element as a parameter in the scope were it belongs, thus exposing all the AMQP functionality in a clearer way. ## Listening For New Messages The AMQP transport `inbound-endpoint` allows you to wait for new AMQP Messages on a given queue. The output of this listener will contain the body of the message in the payload, and all the AMQP headers and properties encompassed in the `AMQP Attributes`. Mule 3 Example: Listening For Messages ```xml (2) (3) (4) ``` In this case, we are listening for Messages and then adapting them to the new format required: 1. Transform the MuleMessage using the metadata contained in the inboundProperties so the payload matches the new JSON format we need for the new API. 2) Convert the transformed payload to a JSON String. 3) Publish the payload to the defined exchange. Implementing the same in Mule 4 looks like this: Mule 4 Example: Listening For Messages ```xml (1) (2) #[output application/json --- { items: payload, costumer: attributes.properties.userProperties.costumer_id, (3) type: attributes.headers.type }] ``` Now, the flow has fewer components and is not required to modify the Message payload to publish with a different format:
1Definition of the new message is done inline, so it only creates the JSON for the new Message body.
2We use the message 'attributes' POJO instead of the 'inboundProperties', which now differentiate the 'headers' of the AMQP Messsage from the 'properties'.
## Consuming Messages Consuming Messages mid-flow from a given destination was not supported by Mule’s 3 AMQP transport, and the way to go was also adding the 'Mule Requester Module' to your application, which would then handle the mid-flow message consume. So, for example, if you wanted to expose your AMQP Queue, your application would be similar to this: Mule 3 Example: Consuming Messages Mid-Flow ```xml ``` Some things to notice here are: - All metadata regarding AMQP Message is completely lost, so logging the CorrelationId relies on you knowing the syntax to obtain the header. - We need both the AMQP and the configuration for the queue in the request. Mule 4 comes out of the box with the capability of consuming messages mid-flow by using 'consume' operation. This operation is very similar to the listener we saw before, with the difference that it can be used anywhere in the flow: Mule 4 Example: Consuming Messages Mid-Flow ```xml ``` ## Doing Request-Reply AMQP allows you to use the `reply_to` property to perform a implement the RPC pattern. This can be done either with a temporary temporary exclusive reply queue that is created on the fly by the client, or using an already existing queue. ### Request Reply With Temporary Auto-delete Private Reply Queue In Mule 3, for the first case where the reply queue is a temporary exclusive queue that will be discarded once the message arrives, we have the "request-response" exchange-pattern in the outbound endpoint: Mule 3 Example: Doing Request-Reply With Temporary Reply Destination ```xml ``` Instead, in Mule 4 you have a brand new operation called `publish-consume` which aims to solve this specific use case: Mule 4 Example: Doing Request-Reply With Temporary Reply Destination ```xml #[output application/xml --- { data: payload, costumer: attributes.queryParams.costumer_id }] ``` You may see that, again, the building of the Message is done inline of the operation, in the `message` element, and any transformation or configuration that affects the outgoing Message will be done as part of that element. ### Request Reply With Explicit Reply To Queue Doing a request-reply with an explicit `reply-to` queue was can be done in Mule 4 through the replyTo property: Mule 4 Example: Doing Request-Reply With Explicit Reply To ```xml #[output application/xml --- { data: payload, costumer: attributes.queryParams.costumer_id }] ``` ## Using Transactions Transactions support is quite similar in its configuration when moving from 3.x to 4.x, with the expected change from it being configured in the `inbound-endpoint` and `outbound-endpoint` to the normalized Mule 4 approach for operations and sources: Mule 3 Example: Using Transactions ```xml (1) (2) (3) (4) (5) (6) (7) ``` Things to note are:
1Transaction is initiated by the inbound endpoint with ALWAYS_BEGIN
2We make sure not to loose the original payload
3Payload is transformed so it can be sent through the outbound endpoint
4The outbound endpoint is configured to ALWAYS_JOIN
5We set up the exception strategy to catch all exceptions
6Original payload is restored so the original message is published to the dead.letter
7Finally we send the original message to the dead.letter attempting to join to the current transaction.
Same scenario can be implemented in Mule 4 with the following approach: Mule 4 Example: Using Transactions ```xml (1) (2) #[output application/xml --- payload (3) (4) ```
1Transaction is initiated by the listener with ALWAYS_BEGIN
2Publishing of the payload in XML format is done by the publish operation without modifying the current payload, also joining the transaction with ALWAYS_JOIN
3An error handler that catches any error occurred is used to make sure the Message is not lost
4Since the current payload is still the original Message received, we just publish it to the dead.letter using the JOIN_IF_POSSIBLE transactional action
## Enforcing the Existence of Queue and Exchanges In Mule 3, if you set `activeDeclarationsOnly` to false and the declared queue or exchange does not exist, the AMQP connector throws a `ShutdownSignalException` involving a 404 error. You can enforce the existence of a queue or exchange in Mule 4 using the `createFallbackQueue` and `createFallbackExchange` parameters. ```xml ``` --- product: Mule Runtime version: 4.4 --- # Migrating to the AMQP Connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt As in other cases the AMQP connector was completely reshaped and evolved away from the Mule 3 transport model into an operation based connector with a simplified UX and fully DataSense enabled Message information. This means not only that using AMQP now provides the same experience regarding connection and configuration that any other connector, but also that publishing and consuming messages is simpler based on the structured Message information. ## Configuring The Connector Moving from a 3.x transport configuration to a AMQP Connector configuration in Mule 4 implies basically using most of the same parameters, but declaring them in a more cohesive way. Some parameters changed in Mule 4 AMQP Connector. This means for example that parameters that are used for consuming Messages are declared in a 'consumer-config' group, while general authentication parameters are configured in the General group. Also, a separation has been made between the parameters that affect the behavior of the connector (present in the config) from those that affect only how the connection is established (present at connection level): Mule 3 Example: Configuring The Connector ```xml ``` This same configuration is achieved in Mule 4 setting the same parameters in the context where they actually apply: Mule 4 Example: Configuring The Connector ```xml ``` Notice that `fallbackAddresses` is not supported anymore. ## Sending Messages With the new Mule 4 approach, the AMQP 'publish' operation relies only on its input parameters to completely build the AMQP Message to be published. For example, if we wanted to send a high priority AMQP Message with only a part of the payload in the body, and associate that Message to a group, we’ll need to: <1>) Use `transform` to set the payload to what the Message body is expected to be. <2>) Convert the resulting stream into a String to send it as a text message. <3>) Set an AMQP property with `priority` as key to set the AMQP Message Priority. Mule 3 Example: Sending a prioritized Message as part of a Group ```xml (1) (2) (3) ``` The same results can be achieved in Mule 4 using the AMQP Connector with the following configuration: Mule 4 Example: Sending a prioritized Message as part of a Group ```xml (2) (1) #[output application/json --- { order_id: payload.id, supplier: payload.warehouse }] (3) ``` Differences to be noted: 1. There’s no need of the `transform` component, since the `body` of the Message is created inline, thus the payload remains unmodified. 2) The `object-to-string` transformer was also removed, since the Connector can automatically handle the transformation output. 3) Priority is set as a property in the AmqpMessage operation and does not rely on the user knowing the exact key. As a summary, when publishing a Message in 3.x with the AMQP transport, we relied on the AmqpMessage payload, and outbound properties to configure the creation of the AMQP Message, which meant a deeper knowledge of how the transport worked. In 4.x, the AMQP Connector exposes every configurable element as a parameter in the scope were it belongs, thus exposing all the AMQP functionality in a clearer way. ## Listening For New Messages The AMQP transport `inbound-endpoint` allows you to wait for new AMQP Messages on a given queue. The output of this listener will contain the body of the message in the payload, and all the AMQP headers and properties encompassed in the `AMQP Attributes`. Mule 3 Example: Listening For Messages ```xml (2) (3) (4) ``` In this case, we are listening for Messages and then adapting them to the new format required: 1. Transform the MuleMessage using the metadata contained in the inboundProperties so the payload matches the new JSON format we need for the new API. 2) Convert the transformed payload to a JSON String. 3) Publish the payload to the defined exchange. Implementing the same in Mule 4 looks like this: Mule 4 Example: Listening For Messages ```xml (1) (2) #[output application/json --- { items: payload, costumer: attributes.properties.userProperties.costumer_id, (3) type: attributes.headers.type }] ``` Now, the flow has fewer components and is not required to modify the Message payload to publish with a different format:
1Definition of the new message is done inline, so it only creates the JSON for the new Message body.
2We use the message 'attributes' POJO instead of the 'inboundProperties', which now differentiate the 'headers' of the AMQP Messsage from the 'properties'.
## Consuming Messages Consuming Messages mid-flow from a given destination was not supported by Mule’s 3 AMQP transport, and the way to go was also adding the 'Mule Requester Module' to your application, which would then handle the mid-flow message consume. So, for example, if you wanted to expose your AMQP Queue, your application would be similar to this: Mule 3 Example: Consuming Messages Mid-Flow ```xml ``` Some things to notice here are: - All metadata regarding AMQP Message is completely lost, so logging the CorrelationId relies on you knowing the syntax to obtain the header. - We need both the AMQP and the configuration for the queue in the request. Mule 4 comes out of the box with the capability of consuming messages mid-flow by using 'consume' operation. This operation is very similar to the listener we saw before, with the difference that it can be used anywhere in the flow: Mule 4 Example: Consuming Messages Mid-Flow ```xml ``` ## Doing Request-Reply AMQP allows you to use the `reply_to` property to perform a implement the RPC pattern. This can be done either with a temporary temporary exclusive reply queue that is created on the fly by the client, or using an already existing queue. ### Request Reply With Temporary Auto-delete Private Reply Queue In Mule 3, for the first case where the reply queue is a temporary exclusive queue that will be discarded once the message arrives, we have the "request-response" exchange-pattern in the outbound endpoint: Mule 3 Example: Doing Request-Reply With Temporary Reply Destination ```xml ``` Instead, in Mule 4 you have a brand new operation called `publish-consume` which aims to solve this specific use case: Mule 4 Example: Doing Request-Reply With Temporary Reply Destination ```xml #[output application/xml --- { data: payload, costumer: attributes.queryParams.costumer_id }] ``` You may see that, again, the building of the Message is done inline of the operation, in the `message` element, and any transformation or configuration that affects the outgoing Message will be done as part of that element. ### Request Reply With Explicit Reply To Queue Doing a request-reply with an explicit `reply-to` queue was can be done in Mule 4 through the replyTo property: Mule 4 Example: Doing Request-Reply With Explicit Reply To ```xml #[output application/xml --- { data: payload, costumer: attributes.queryParams.costumer_id }] ``` ## Using Transactions Transactions support is quite similar in its configuration when moving from 3.x to 4.x, with the expected change from it being configured in the `inbound-endpoint` and `outbound-endpoint` to the normalized Mule 4 approach for operations and sources: Mule 3 Example: Using Transactions ```xml (1) (2) (3) (4) (5) (6) (7) ``` Things to note are:
1Transaction is initiated by the inbound endpoint with ALWAYS_BEGIN
2We make sure not to loose the original payload
3Payload is transformed so it can be sent through the outbound endpoint
4The outbound endpoint is configured to ALWAYS_JOIN
5We set up the exception strategy to catch all exceptions
6Original payload is restored so the original message is published to the dead.letter
7Finally we send the original message to the dead.letter attempting to join to the current transaction.
Same scenario can be implemented in Mule 4 with the following approach: Mule 4 Example: Using Transactions ```xml (1) (2) #[output application/xml --- payload (3) (4) ```
1Transaction is initiated by the listener with ALWAYS_BEGIN
2Publishing of the payload in XML format is done by the publish operation without modifying the current payload, also joining the transaction with ALWAYS_JOIN
3An error handler that catches any error occurred is used to make sure the Message is not lost
4Since the current payload is still the original Message received, we just publish it to the dead.letter using the JOIN_IF_POSSIBLE transactional action
## Enforcing the Existence of Queue and Exchanges In Mule 3, if you set `activeDeclarationsOnly` to false and the declared queue or exchange does not exist, the AMQP connector throws a `ShutdownSignalException` involving a 404 error. You can enforce the existence of a queue or exchange in Mule 4 using the `createFallbackQueue` and `createFallbackExchange` parameters. ```xml ``` --- product: Mule Runtime version: 4.3 --- # Migrating to the Email connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The POP3, IMAP and SMTP transports were completely rewritten. They evolved away from the Mule 3 transport model into a single operation-based connector. This change enables many new capabilities: - The ability to list emails contents on demand, unlike the old IMAP and POP3 transports, which only provided a polling inbound endpoint. - Simplified experience to send emails. - Simplified experience to get the data of incoming emails. - Consistency between all mule connectors. - Advanced email matching functionality. They were merged to a bring similar experience either you want to receive or send and ## Migrating IMAP, POP3 or SMTP Server Configurations Here you can see examples on how to migrate each one of the email transports configurations that were in mule 3 to the new mule 4 email connector. In the following Mule 4 configuration examples you’ll see that most of the parameters that were declared in the `inbound-endpoint` or `outbound-endpoint` such as `user`, `password`, `host`, `port` between others have been moved to the `connection` element. ### Migrating a POP3 Inbound Endpoint Mule 3 Example: POP3 Inbound Configuration with Polling ```xml ... ``` Mule 4 Example: POP3 Configuration ```xml ... ``` > [!NOTE] the list-pop3 operation does not perform the polling, an scheduler is in charge to trigger > the flow. ### Migrating an IMAP Inbound Endpoint Mule 3 Example: IMAP Inbound Configuration with Polling ```xml ... ``` Mule 4 Example: POP3 Configuration ```xml ... ``` > [!NOTE] the list-imap operation does not perform the polling, an scheduler is in charge to trigger > the flow. ### Inbound Email Attachments In Mule 3, attachments in the received email were set on the `inboundAttachments` field of the Message. In the Email connector for Mule 4, the attachments are a field of the message payload, modeled as a Map and accessible through DataWeave. For instance, to reference an attachment called `photo_png`, the expression is `#[payload.attachments['photo_png']]`. ### Migrating an SMTP Outbound Endpoint Mule 3 Example: SMTP Outbound Configuration. ```xml ... ``` Mule 4 Example: SMTP Configuration ```xml #[payload] ``` In the Mule 3 transport, the properties of the outgoing email (subject, addresses, and so on) could be configured through outbound properties set in the event, before the execution of the outbound SMTP endpoint. In that case, the outbound properties took precedence over the values configured in the endpoint or connector themselves. Unlike Mule 3, attachments to be sent with an email must be configured explicitly on the `email:send` operation, rather that obtained from the `outboundAttachments` field of the Message. A suggested pattern for sending attachments is set them as variables in the flow and then reference those variables in the `email:send` operation to send those attachments. ### Migrating SSL/TLS Secured Connections In Mule 3, each transport/connector had its own TLS element. In Mule 4, the TLS context is the common element for configuring TLS across modules. In the next example we can see a Mule 3 example and how can it be migrated to Mule 4. > [!NOTE] the example uses an SMTP configuration but is the same for the IMAP and POP3 > configurations. Mule 3 Example ```xml ``` Mule 4 Example ```xml ``` ## Adding the Mule 4 Connector to a Project Now that the transport are not bounded with Mule, you need to add it to your app using the Studio palette or add the following dependency in your `pom.xml` file in order to use it ```xml org.mule.connectors mule-email-connector 1.1.0 mule-plugin ``` ## See also - [Email Connector](https://docs.mulesoft.com/email-connector/latest/) - [Connecting with Gmail in Mule 4 Using the Email Connector](https://docs.mulesoft.com/email-connector/latest/email-gmail) --- product: Mule Runtime version: 4.4 --- # Migrating to the Email connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The POP3, IMAP and SMTP transports were completely rewritten. They evolved away from the Mule 3 transport model into a single operation-based connector. This change enables many new capabilities: - The ability to list emails contents on demand, unlike the old IMAP and POP3 transports, which only provided a polling inbound endpoint. - Simplified experience to send emails. - Simplified experience to get the data of incoming emails. - Consistency between all mule connectors. - Advanced email matching functionality. They were merged to a bring similar experience either you want to receive or send and ## Migrating IMAP, POP3 or SMTP Server Configurations Here you can see examples on how to migrate each one of the email transports configurations that were in mule 3 to the new mule 4 email connector. In the following Mule 4 configuration examples you’ll see that most of the parameters that were declared in the `inbound-endpoint` or `outbound-endpoint` such as `user`, `password`, `host`, `port` between others have been moved to the `connection` element. ### Migrating a POP3 Inbound Endpoint Mule 3 Example: POP3 Inbound Configuration with Polling ```xml ... ``` Mule 4 Example: POP3 Configuration ```xml ... ``` > [!NOTE] the list-pop3 operation does not perform the polling, an scheduler is in charge to trigger > the flow. ### Migrating an IMAP Inbound Endpoint Mule 3 Example: IMAP Inbound Configuration with Polling ```xml ... ``` Mule 4 Example: POP3 Configuration ```xml ... ``` > [!NOTE] the list-imap operation does not perform the polling, an scheduler is in charge to trigger > the flow. ### Inbound Email Attachments In Mule 3, attachments in the received email were set on the `inboundAttachments` field of the Message. In the Email connector for Mule 4, the attachments are a field of the message payload, modeled as a Map and accessible through DataWeave. For instance, to reference an attachment called `photo_png`, the expression is `#[payload.attachments['photo_png']]`. ### Migrating an SMTP Outbound Endpoint Mule 3 Example: SMTP Outbound Configuration. ```xml ... ``` Mule 4 Example: SMTP Configuration ```xml #[payload] ``` In the Mule 3 transport, the properties of the outgoing email (subject, addresses, and so on) could be configured through outbound properties set in the event, before the execution of the outbound SMTP endpoint. In that case, the outbound properties took precedence over the values configured in the endpoint or connector themselves. Unlike Mule 3, attachments to be sent with an email must be configured explicitly on the `email:send` operation, rather that obtained from the `outboundAttachments` field of the Message. A suggested pattern for sending attachments is set them as variables in the flow and then reference those variables in the `email:send` operation to send those attachments. ### Migrating SSL/TLS Secured Connections In Mule 3, each transport/connector had its own TLS element. In Mule 4, the TLS context is the common element for configuring TLS across modules. In the next example we can see a Mule 3 example and how can it be migrated to Mule 4. > [!NOTE] the example uses an SMTP configuration but is the same for the IMAP and POP3 > configurations. Mule 3 Example ```xml ``` Mule 4 Example ```xml ``` ## Adding the Mule 4 Connector to a Project Now that the transport are not bounded with Mule, you need to add it to your app using the Studio palette or add the following dependency in your `pom.xml` file in order to use it ```xml org.mule.connectors mule-email-connector 1.1.0 mule-plugin ``` ## See also - [Email Connector](https://docs.mulesoft.com/email-connector/latest/) - [Connecting with Gmail in Mule 4 Using the Email Connector](https://docs.mulesoft.com/email-connector/latest/email-gmail) --- product: Mule Runtime version: 4.3 --- # Migrating to the FTP and SFTP Connectors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The FTP and SFTP transports were completely rewritten. They evolved away from the Mule 3 transport model into an operation based connector. This enables many new capabilities: - The ability to read files or fully list directory contents on demand, unlike the old transport, which only provided a polling inbound endpoint. - Top-level support for common file system operations such as copying, moving, renaming, deleting, creating directories, and more. - Support for locking files at the file system level. - Advanced file matching functionality. Furthermore, they were designed to be completely symmetrical. This means that, except for the connection configuration, they look and behave alike and have the exact same feature set. Furthermore, they also match the features and behavior of the File connector. ## Connecting to an FTP or SFTP Server ### Migrating an FTP Connection Mule 3 Example: FTP Inbound Connection with Polling ```xml ``` This example shows a simple Mule 4 FTP configuration. Mule 4 Example: FTP Connection ```xml ``` ### Migrating and SFTP Connection Mule 3 Example: SFTP Inbound Endpoint ```xml ``` Mule 4 Example: SFTP Connection Configuration ```xml ``` The SFTP connection also supports a connection through a proxy. Mule 4 Example: SFTP Connection through a Proxy ```xml ``` ## Migrating an Inbound Endpoint In Mule 3 a `` and `` message sources were used to poll a directory for files. For each file found, a new message was triggered. The message would hold the file’s content in the payload plus a number of file attributes as system properties. To avoid picking the same files over and over, `autoDelete` and `moveTo` parameters were provided, so that the files would leave the polled directory after being picked. Mule 4 offers an improved way of doing that. The `` and `` components (shown as `On New File` in the Studio palette) polls a directory and triggers a new message just like its predecessor did. However it has the following added capabilities: - You can use a `` and `` to only accept files with match a certain criteria - You’re no longer forced to either delete or move the file, although the option to do that is still available. - You can use any of the connector’s operation to change processed files in such a way that they no longer meet the matching criteria. - Watermark is automatically supported, allowing you to optionally filter automatically based on the file’s timestamp. Mule 3 Example: Inbound endpoint ```xml ``` Mule 4 Example: On New File ```xml ``` ## Migrating an Outbound Endpoint The Mule 3 transport uses the `` component to write the current payload to a file. The Mule 4 connector uses the `` operation instead. The most important differences are: - The `` required the content to be written in the message payload at the moment of execution. The `` operation can embed a DataWeave transformation that generates the content to be written. - The Mule 3 transport has the `outputAppend` parameter set at the config level, while the `` operation has a `mode` parameter. Mule 3 Example: Outbound Endpoint ```xml ``` Mule 4 Example: Write Operation ```xml #['Hello $(payload.name)'] ``` To use FTP in the SFTP connector, simply add it to your application using the Studio palette, or add the following dependency in your `pom.xml` file: ```xml org.mule.connectors mule-ftp-connector 1.1.0 mule-plugin org.mule.connectors mule-sftp-connector 1.1.0 mule-plugin ``` ### SFTP Outbound 'addSeqNo' Duplicate Handling In Mule 3, using `duplicateHandling="addSeqNo"` iterates though the file names until an unused index is found. In Mule 4, you need to replace this with a unique index, for example, through an Object Store or UUID. Mule 3 Example: Outbound SFTP Endpoint `addSeqNo` ```xml ``` Mule 4 Example: `sftp:write` with `uuid()` in the `path` ```xml ``` ## Migrating the SFTP tempDir In Mule 3, the SFTP transport allows for configuration of temporary directories to use when reading or writing files. The properties that allow this are: - In the `sftp:connector`: - `tempDirInbound` - `tempDirOutbound` - `useTempFileTimestampSuffix` - In the `sftp:inbound-endpoint`: - `tempDir` - `useTempFileTimestampSuffix` - In the `sftp:outbound-endpoint`: - `tempDir` - `useTempFileTimestampSuffix` These configurations are not allowed in the Mule 4 SFTP connector. However, the connector provides the `sftp:move` operation that you can use to replace this kind of configuration. Mule 3 Example: Inbound SFTP Endpoint `tempDir` ```xml ... ``` Mule 4 Example: `sftp:move` to a Temporary Directory ```xml ... ``` ## Archiving Files to a Local Drive In Mule 4, the `moveToDirectory` attribute on the listener in the SFTP connector only archives to another directory on the SFTP server, not to a local directory. You can archive files to a local drive by using the Write operation (`file:write`) in the File connector. Mule 4 Example: `file:write` to a Local Directory ```xml ``` ## See Also - [FTP Connector](https://docs.mulesoft.com/ftp-connector/latest/) - [SFTP Connector](https://docs.mulesoft.com/sftp-connector/latest/) --- product: Mule Runtime version: 4.4 --- # Migrating to the FTP and SFTP Connectors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The FTP and SFTP transports were completely rewritten. They evolved away from the Mule 3 transport model into an operation based connector. This enables many new capabilities: - The ability to read files or fully list directory contents on demand, unlike the old transport, which only provided a polling inbound endpoint. - Top-level support for common file system operations such as copying, moving, renaming, deleting, creating directories, and more. - Support for locking files at the file system level. - Advanced file matching functionality. Furthermore, they were designed to be completely symmetrical. This means that, except for the connection configuration, they look and behave alike and have the exact same feature set. Furthermore, they also match the features and behavior of the File connector. ## Connecting to an FTP or SFTP Server ### Migrating an FTP Connection Mule 3 Example: FTP Inbound Connection with Polling ```xml ``` This example shows a simple Mule 4 FTP configuration. Mule 4 Example: FTP Connection ```xml ``` ### Migrating and SFTP Connection Mule 3 Example: SFTP Inbound Endpoint ```xml ``` Mule 4 Example: SFTP Connection Configuration ```xml ``` The SFTP connection also supports a connection through a proxy. Mule 4 Example: SFTP Connection through a Proxy ```xml ``` ## Migrating an Inbound Endpoint In Mule 3 a `` and `` message sources were used to poll a directory for files. For each file found, a new message was triggered. The message would hold the file’s content in the payload plus a number of file attributes as system properties. To avoid picking the same files over and over, `autoDelete` and `moveTo` parameters were provided, so that the files would leave the polled directory after being picked. Mule 4 offers an improved way of doing that. The `` and `` components (shown as `On New File` in the Studio palette) polls a directory and triggers a new message just like its predecessor did. However it has the following added capabilities: - You can use a `` and `` to only accept files with match a certain criteria - You’re no longer forced to either delete or move the file, although the option to do that is still available. - You can use any of the connector’s operation to change processed files in such a way that they no longer meet the matching criteria. - Watermark is automatically supported, allowing you to optionally filter automatically based on the file’s timestamp. Mule 3 Example: Inbound endpoint ```xml ``` Mule 4 Example: On New File ```xml ``` ## Migrating an Outbound Endpoint The Mule 3 transport uses the `` component to write the current payload to a file. The Mule 4 connector uses the `` operation instead. The most important differences are: - The `` required the content to be written in the message payload at the moment of execution. The `` operation can embed a DataWeave transformation that generates the content to be written. - The Mule 3 transport has the `outputAppend` parameter set at the config level, while the `` operation has a `mode` parameter. Mule 3 Example: Outbound Endpoint ```xml ``` Mule 4 Example: Write Operation ```xml #['Hello $(payload.name)'] ``` To use FTP in the SFTP connector, simply add it to your application using the Studio palette, or add the following dependency in your `pom.xml` file: ```xml org.mule.connectors mule-ftp-connector 1.1.0 mule-plugin org.mule.connectors mule-sftp-connector 1.1.0 mule-plugin ``` ### SFTP Outbound 'addSeqNo' Duplicate Handling In Mule 3, using `duplicateHandling="addSeqNo"` iterates though the file names until an unused index is found. In Mule 4, you need to replace this with a unique index, for example, through an Object Store or UUID. Mule 3 Example: Outbound SFTP Endpoint `addSeqNo` ```xml ``` Mule 4 Example: `sftp:write` with `uuid()` in the `path` ```xml ``` ## Migrating the SFTP tempDir In Mule 3, the SFTP transport allows for configuration of temporary directories to use when reading or writing files. The properties that allow this are: - In the `sftp:connector`: - `tempDirInbound` - `tempDirOutbound` - `useTempFileTimestampSuffix` - In the `sftp:inbound-endpoint`: - `tempDir` - `useTempFileTimestampSuffix` - In the `sftp:outbound-endpoint`: - `tempDir` - `useTempFileTimestampSuffix` These configurations are not allowed in the Mule 4 SFTP connector. However, the connector provides the `sftp:move` operation that you can use to replace this kind of configuration. Mule 3 Example: Inbound SFTP Endpoint `tempDir` ```xml ... ``` Mule 4 Example: `sftp:move` to a Temporary Directory ```xml ... ``` ## Archiving Files to a Local Drive In Mule 4, the `moveToDirectory` attribute on the listener in the SFTP connector only archives to another directory on the SFTP server, not to a local directory. You can archive files to a local drive by using the Write operation (`file:write`) in the File connector. Mule 4 Example: `file:write` to a Local Directory ```xml ``` ## See Also - [FTP Connector](https://docs.mulesoft.com/ftp-connector/latest/) - [SFTP Connector](https://docs.mulesoft.com/sftp-connector/latest/) --- product: Mule Runtime version: 4.3 --- # Migrating to the JMS Connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The JMS transport was completely reshaped and evolved away from the Mule 3 transport model into an operation based connector with a simplified UX and fully DataSense enabled Message information. This means not only that using JMS now provides the same experience regarding connection and configuration that any other connector, but also that producing and consuming messages is simpler based on the structured Message information. Also, the new version of JMS Connector provides support for the much desired JMS 2.0 spec, with all the new capabilities like shared subscriptions. ## Configuring The Connector Moving from a 3.x transport configuration to a JMS Connector configuration in Mule 4 implies basically using the same exact parameters, but declaring them in a more cohesive way. This means for example that parameters that are used for consuming Messages are declared in a 'consumer-config' group, while general authentication parameters are configured in the General group. Also, a separation has been made between the parameters that affect the behavior of the connector (present in the config) from those that affect only how the connection is established (present at connection level): Mule 3 Example: Configuring The Connector ```xml ``` This same configuration is achieved in Mule 4 setting the same parameters in the context where they actually apply, like 'noLocal' or 'durable' affecting only the 'topic-consumer': Mule 4 Example: Configuring The Connector ```xml ``` ## Connecting To A Broker In the JMS Connector for Mule 4, the distinction between a generic JMS connection and the simplified ActiveMQ connection still exists, but with a much more more focused set of parameters that are associated only to the connection. We’ll see first how to configure this simplified connection and then move on to the generic approach. ### Connecting To ActiveMQ Using the transport, the only way to configure ActiveMQ specific parameters was defining the ConfigurationFactory as an spring bean and then passing on each property: .Mule 3 Example: Connecting To ActiveMQ ```xml ``` With the new JMS Connector, this properties can be configured directly in the activemq connection: Mule 4 Example: Connecting To ActiveMQ ```xml ``` If you need to migrate a transport configuration that is using a Connection Factory not yet supported out of the box in the JMS Connector, you can still do use the 'connectionFactory' attribute in the 'activemq-connection' to pass a reference to any Connection Factory bean. ### Using A Different Broker Both Mule 3 JMS transport and Mule 4 JMS Connector allow you to define a generic connection to any Connection Factory that you need. We have two ways of doing this, the first one is creating a Connection Factory using spring beans and then referencing it as the Connection Factory: Mule 3 Example: Generic Connection Using Spring Beans ```xml ``` Mule 4’s version is almost identical: Mule 4 Example: Generic Connection Using Spring Beans ```xml ``` Another way of creating a generic connection is using a Connection Factory that is discovered using JNDI. In this case, the functionality remains the same, but syntax changes from transport to connector: Mule 3 Example: Generic Connection Using JNDI ```xml in in ``` In Mule 4’s version you can do this configuring the JNDI inline: Mule 4 Example: Generic Connection Using Spring Beans ```xml ``` Three main differences arise from this example: - Properties are now declared inline, no need for spring bean utils to be used. - Enforcing the lookup of destinations using JNDI is now configured as a single parameter named 'lookupDestination', which unifies the previous two parameters 'jndiDestinations' and 'forceJndiDestinations'. - Parameters are now present in the context for which they are relevant, like the 'jndiProviderUrl' being part of the 'name-resolver'. ## Sending Messages JMS Transport relied in the payload to contain the body of a JMS Message, and used Mule’s outbound properties to customize the JMS Properties and Headers. With the new Mule 4 approach, the JMS 'publish' operation relies only on its input parameters to completely build the JMS Message to be published. For example, if we wanted to send a high priority JMS Message with only a part of the payload in the body, and associate that Message to a group, we’ll need to: <1>) Use `transform` to set the payload to what the Message body is expected to be. <2>) Convert the resulting stream into a String to send it as a text message. <3>) Set an outbound message property with `priority` as key to set the JMSPriority. <4>) Set an outbound message property with `JMSXGroupID` as key to set the JMSXGroupID. Mule 3 Example: Sending a prioritized Message as part of a Group ```xml (1) (2) (3) (4) ``` The same results can be achieved in Mule 4 using the JMS Connector with the following configuration: Mule 4 Example: Sending a prioritized Message as part of a Group ```xml (2) (3) (1) #[output application/json --- { order_id: payload.id, supplier: payload.warehouse }] (4) ``` Differences to be noted: 1. There’s no need of the `transform` component, since the `body` of the Message is created inline, thus the payload remains unmodified. 2) The `object-to-string` transformer was also removed, since the Connector can handle automatically the transformation output. 3) Priority is set as a parameter of the `publish` operation and doesn’t rely on the user knowing the exact key. 4) Group is set as part of the Message JMSX properties and doesn’t rely on the user knowing the exact header name. As a summary, when publishing a Message in 3.x with the JMS transport, we relied on the MuleMessage payload, and outbound properties to configure the creation of the JMS Message, which meant a deeper knowledge of how the transport worked. In 4.x, the JMS Connector exposes every configurable element as a parameter in the scope were it belongs, thus exposing all the JMS functionality in a clearer way. ## Listening For New Messages The JMS transport `inbound-endpoint` allows you to wait for new Messages on a given topic or queue. The output of this listener will contain the body of the message in the payload, and all the JMS headers and properties as `inboundProperties`. Mule 3 Example: Listening For Messages With Filtering by Selector ```xml (1) (2) (3) (4) ``` In this case, we are listening for high priority Messages and then adapting them to the new format required by version 2 of priority orders: 1. Filter incoming messages by priority. 2) Transform the MuleMessage using the metadata contained in the inboundProperties so the payload matches the new JSON format we need for the new API. 3) Convert the transformed payload to a JSON String. 4) Publish the payload to the proxied queue. Implementing the same in Mule 4 looks like this: Mule 4 Example: Listening For Messages With Filtering by Selector ```xml (1) (2) #[output application/json --- { items: payload, costumer: attributes.properties.userProperties.costumer_id, (3) type: attributes.headers.type }] ``` Now, the flow has fewer components and is not required to modify the Message payload to publish with a different format:
1Listening with a filter is done configuring the 'selector' in the listener.
2Definition of the new message is done inline, so it only creates the JSON for the new Message body.
3We use the message 'attributes' POJO instead of the 'inboundProperties', which now differentiate the 'headers' of the JMS Messsage from the 'properties'.
## Consuming Messages Consuming Messages mid-flow from a given destination was not supported by Mule’s 3 JMS transport, and the way to go was also adding the 'Mule Requester Module' to your application, which would then handle the mid-flow message consume. So, for example, if you wanted to expose your JMS Queue behind a new REST API, your application would be similar to this: Mule 3 Example: Consuming Messages Mid-Flow ```xml ``` Some things to notice here are: - All metadata regarding JMS Message is completely lost, so logging the CorrelationId relies on you knowing the syntax for obtaining the Header. - Dynamic filtering by 'selector' has to be done in the 'resource' url of the requester, so multiple arguments end up with an error prone configuration. - We need both the JMS and Mule Requester configurations. Mule 4 comes out of the box with the capability of consuming messages mid-flow by using thr 'consume' operation. This operation is very similar to the Listener we saw before, with the difference that it can be used anywhere in the flow: Mule 4 Example: Consuming Messages Mid-Flow ```xml ``` Now we only needed a the JMS Connector, configured the 'consume' operation with the 'selector' parameter using the metadata from the listener, and also were able to log the correlationId with metadata support in the Message attributes. ## Handling Topic Subscriptions Topics used as inbound endpoints in 3.x allowed the user to configure if the subscription to the Topic had to be done as a `durable` subscription or not. There were different ways of doing so, and it had the issue of exposing the `durable` configuration for `queues` too, which made no sense. A Topic subscription in 3.x would look like this: Mule 3 Example: Topic Subscriptions ```xml ``` For Mule 4, the subscription mechanism was reviewed, leaving the option of subscriptions scoped down to Topics only, and adding more functionality thanks to the support of JMS 2.0. Same example as before, but in 4.x will be: Mule 4 Example: Topic Subscriptions ```xml ``` But in this case, the `topic-consumer` configuration allows us to also set a `shared` subscription (only if using a JMS 2.0 Connection) that allows the processing of messages from at topic subscription by multiple threads, connections or JVMs: Mule 4 Example: Topic Subscriptions ```xml ``` ## Responding To Incoming Messages When the listener for new JMS Messages receives a Message with the 'JMSReplyTo' header configured, then it is expected that a response is emitted to the reply destination once the processing of the Message is completed. For Mule 3, this means configuring the transport with `` exchange-pattern="request-response"` ``, where the result of the flow will automatically become the payload of the response. Headers of the response Message were configured using the `outbound-properties`, while the body of the Message was taken from the `payload` at the end of the Flow. Mule 3 Example: Responding To Incoming Messages ```xml ``` Mule 4 instead allows you to configure all the parameters associated to the response, directly inline as a part of the `listener` component, leaving behind the need of a transformation when reaching the end of the flow. Mule 4 Example: Responding To Incoming Messages ```xml #['BRIDGED'] ``` ## Doing Request-Reply JMS allows you to use the `JMSReplyTo` header to perform a synchronous communication. This can be done either with a temporary destination that is created on the fly by the client, or using an already existing destination. ### Request Reply With Temporary Destinations In Mule 3, for the first case where the reply destination is a temporary queue that will be discarded once the message arrives, we have the "request-response" exchange-pattern in the outbound endpoint: Mule 3 Example: Doing Request-Reply With Temporary Reply Destination ```xml ``` Instead, in Mule 4 you have a brand new operation called `publish-consume` which aims to solve this specific use case: Mule 4 Example: Doing Request-Reply With Temporary Reply Destination ```xml #[output application/xml --- { data: payload, costumer: attributes.queryParams.costumer_id }] ``` You may see that, again, the building of the Message is where inline of the operation, in the `message` element, and any transformation or configuration that affects the outgoing Message will be done as part of that element. ### Request Reply With Explicit Destinations Doing a request-reply with an explicit `reply-to` destination was a little bit more tricky in 3.x, since a new component was required, the `request-reply` Scope: Mule 3 Example: Doing Request-Reply With Explicit Reply Destination ```xml (1) ``` This scope (1) allowed you to set an inbound and outbound transport to do the request-reply pattern. This way, it would inject the `JMSReplyTo` header automatically in the outgoing Message and then started listening in the inbound endpoint For the case of Mule’s 4 JMS Connector with the new `publish-consume` operation, it requires you to do almost no changes to the flow. If you want an specific destination for the reply to be sent, just configure the `reply-to` header in the Message builder directly, as you would in any other case of either a publish or a response: Mule 4 Example: Doing Request-Reply With Temporary Reply Destination ```xml #[output application/xml --- { data: payload, costumer: attributes.queryParams.costumer_id }] (1) ``` In this example we set the reply destination header (<1>) to a well-known Topic, to illustrate that a known destination may be used by others to do things like event tracking or post-processing triggers. ## Using Transactions Transactions support is quite similar in its configuration when moving from 3.x to 4.x, with the expected change from it being configured in the `inbound-endpoint` and `outbound-endpoint` to the normalized Mule 4 approach for operations transactions: Mule 3 Example: Using Transactions ```xml (1) (2) (3) (4) (5) (6) (7) ``` Things to note are:
1Transaction is initiated by the inbound endpoint with ALWAYS_BEGIN
2We make sure not to loose the original payload
3Payload is transformed so it can be sent through the outbound endpoint
4The outbound endpoint is configured to ALWAYS_JOIN
5We set up the exception strategy to catch all exceptions
6Original payload is restored so the original message is published to the dead.letter
7Finally we send the original message to the dead.letter attempting to join to the current transaction.
You can implement the same scenario in Mule 4 by using the following approach: Mule 4 Example: Using Transactions ```xml (1) (2) #[output application/xml --- payload (3) (4) ```
1Transaction is initiated by the listener with ALWAYS_BEGIN
2Publishing of the payload in XML format is done by the publish operation without modifying the current payload, also joining the transaction with ALWAYS_JOIN
3An error handler that catches any error occurred is used to make sure the Message is not lost
4Since the current payload is still the original Message received, we just publish it to the dead.letter using the JOIN_IF_POSSIBLE transactional action
--- product: Mule Runtime version: 4.4 --- # Migrating to the JMS Connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The JMS transport was completely reshaped and evolved away from the Mule 3 transport model into an operation based connector with a simplified UX and fully DataSense enabled Message information. This means not only that using JMS now provides the same experience regarding connection and configuration that any other connector, but also that producing and consuming messages is simpler based on the structured Message information. Also, the new version of JMS Connector provides support for the much desired JMS 2.0 spec, with all the new capabilities like shared subscriptions. ## Configuring The Connector Moving from a 3.x transport configuration to a JMS Connector configuration in Mule 4 implies basically using the same exact parameters, but declaring them in a more cohesive way. This means for example that parameters that are used for consuming Messages are declared in a 'consumer-config' group, while general authentication parameters are configured in the General group. Also, a separation has been made between the parameters that affect the behavior of the connector (present in the config) from those that affect only how the connection is established (present at connection level): Mule 3 Example: Configuring The Connector ```xml ``` This same configuration is achieved in Mule 4 setting the same parameters in the context where they actually apply, like 'noLocal' or 'durable' affecting only the 'topic-consumer': Mule 4 Example: Configuring The Connector ```xml ``` ## Connecting To A Broker In the JMS Connector for Mule 4, the distinction between a generic JMS connection and the simplified ActiveMQ connection still exists, but with a much more more focused set of parameters that are associated only to the connection. We’ll see first how to configure this simplified connection and then move on to the generic approach. ### Connecting To ActiveMQ Using the transport, the only way to configure ActiveMQ specific parameters was defining the ConfigurationFactory as an spring bean and then passing on each property: .Mule 3 Example: Connecting To ActiveMQ ```xml ``` With the new JMS Connector, this properties can be configured directly in the activemq connection: Mule 4 Example: Connecting To ActiveMQ ```xml ``` If you need to migrate a transport configuration that is using a Connection Factory not yet supported out of the box in the JMS Connector, you can still do use the 'connectionFactory' attribute in the 'activemq-connection' to pass a reference to any Connection Factory bean. ### Using A Different Broker Both Mule 3 JMS transport and Mule 4 JMS Connector allow you to define a generic connection to any Connection Factory that you need. We have two ways of doing this, the first one is creating a Connection Factory using spring beans and then referencing it as the Connection Factory: Mule 3 Example: Generic Connection Using Spring Beans ```xml ``` Mule 4’s version is almost identical: Mule 4 Example: Generic Connection Using Spring Beans ```xml ``` Another way of creating a generic connection is using a Connection Factory that is discovered using JNDI. In this case, the functionality remains the same, but syntax changes from transport to connector: Mule 3 Example: Generic Connection Using JNDI ```xml in in ``` In Mule 4’s version you can do this configuring the JNDI inline: Mule 4 Example: Generic Connection Using Spring Beans ```xml ``` Three main differences arise from this example: - Properties are now declared inline, no need for spring bean utils to be used. - Enforcing the lookup of destinations using JNDI is now configured as a single parameter named 'lookupDestination', which unifies the previous two parameters 'jndiDestinations' and 'forceJndiDestinations'. - Parameters are now present in the context for which they are relevant, like the 'jndiProviderUrl' being part of the 'name-resolver'. ## Sending Messages JMS Transport relied in the payload to contain the body of a JMS Message, and used Mule’s outbound properties to customize the JMS Properties and Headers. With the new Mule 4 approach, the JMS 'publish' operation relies only on its input parameters to completely build the JMS Message to be published. For example, if we wanted to send a high priority JMS Message with only a part of the payload in the body, and associate that Message to a group, we’ll need to: <1>) Use `transform` to set the payload to what the Message body is expected to be. <2>) Convert the resulting stream into a String to send it as a text message. <3>) Set an outbound message property with `priority` as key to set the JMSPriority. <4>) Set an outbound message property with `JMSXGroupID` as key to set the JMSXGroupID. Mule 3 Example: Sending a prioritized Message as part of a Group ```xml (1) (2) (3) (4) ``` The same results can be achieved in Mule 4 using the JMS Connector with the following configuration: Mule 4 Example: Sending a prioritized Message as part of a Group ```xml (2) (3) (1) #[output application/json --- { order_id: payload.id, supplier: payload.warehouse }] (4) ``` Differences to be noted: 1. There’s no need of the `transform` component, since the `body` of the Message is created inline, thus the payload remains unmodified. 2) The `object-to-string` transformer was also removed, since the Connector can handle automatically the transformation output. 3) Priority is set as a parmeter of the `publish` operation and doesn’t rely on the user knowing the exact key. 4) Group is set as part of the Message JMSX properties and doesn’t rely on the user knowing the exact header name. As a summary, when publishing a Message in 3.x with the JMS transport, we relied on the MuleMessage payload, and outbound properties to configure the creation of the JMS Message, which meant a deeper knowledge of how the transport worked. In 4.x, the JMS Connector exposes every configurable element as a parameter in the scope were it belongs, thus exposing all the JMS functionality in a clearer way. ## Listening For New Messages The JMS transport `inbound-endpoint` allows you to wait for new Messages on a given topic or queue. The output of this listener will contain the body of the message in the payload, and all the JMS headers and properties as `inboundProperties`. Mule 3 Example: Listening For Messages With Filtering by Selector ```xml (1) (2) (3) (4) ``` In this case, we are listening for high priority Messages and then adapting them to the new format required by version 2 of priority orders: 1. Filter incoming messages by priority. 2) Transform the MuleMessage using the metadata contained in the inboundProperties so the payload matches the new JSON format we need for the new API. 3) Convert the transformed payload to a JSON String. 4) Publish the payload to the proxied queue. Implementing the same in Mule 4 looks like this: Mule 4 Example: Listening For Messages With Filtering by Selector ```xml (1) (2) #[output application/json --- { items: payload, costumer: attributes.properties.userProperties.costumer_id, (3) type: attributes.headers.type }] ``` Now, the flow has fewer components and is not required to modify the Message payload to publish with a different format:
1Listening with a filter is done configuring the 'selector' in the listener.
2Definition of the new message is done inline, so it only creates the JSON for the new Message body.
3We use the message 'attributes' POJO instead of the 'inboundProperties', which now differentiate the 'headers' of the JMS Messsage from the 'properties'.
## Consuming Messages Consuming Messages mid-flow from a given destination was not supported by Mule’s 3 JMS transport, and the way to go was also adding the 'Mule Requester Module' to your application, which would then handle the mid-flow message consume. So, for example, if you wanted to expose your JMS Queue behind a new REST API, your application would be similar to this: Mule 3 Example: Consuming Messages Mid-Flow ```xml ``` Some things to notice here are: - All metadata regarding JMS Message is completely lost, so logging the CorrelationId relies on you knowing the syntax for obtaining the Header. - Dynamic filtering by 'selector' has to be done in the 'resource' url of the requester, so multiple arguments end up with an error prone configuration. - We need both the JMS and Mule Requester configurations. Mule 4 comes out of the box with the capability of consuming messages mid-flow by using thr 'consume' operation. This operation is very similar to the Listener we saw before, with the difference that it can be used anywhere in the flow: Mule 4 Example: Consuming Messages Mid-Flow ```xml ``` Now we only needed a the JMS Connector, configured the 'consume' operation with the 'selector' parameter using the metadata from the listener, and also were able to log the correlationId with metadata support in the Message attributes. ## Handling Topic Subscriptions Topics used as inbound endpoints in 3.x allowed the user to configure if the subscription to the Topic had to be done as a `durable` subscription or not. There were different ways of doing so, and it had the issue of exposing the `durable` configuration for `queues` too, which made no sense. A Topic subscription in 3.x would look like this: Mule 3 Example: Topic Subscriptions ```xml ``` For Mule 4, the subscription mechanism was reviewed, leaving the option of subscriptions scoped down to Topics only, and adding more functionality thanks to the support of JMS 2.0. Same example as before, but in 4.x will be: Mule 4 Example: Topic Subscriptions ```xml ``` But in this case, the `topic-consumer` configuration allows us to also set a `shared` subscription (only if using a JMS 2.0 Connection) that allows the processing of messages from at topic subscription by multiple threads, connections or JVMs: Mule 4 Example: Topic Subscriptions ```xml ``` ## Responding To Incoming Messages When the listener for new JMS Messages receives a Message with the 'JMSReplyTo' header configured, then it is expected that a response is emitted to the reply destination once the processing of the Message is completed. For Mule 3, this means configuring the transport with `` exchange-pattern="request-response"` ``, where the result of the flow will automatically become the payload of the response. Headers of the response Message were configured using the `outbound-properties`, while the body of the Message was taken from the `payload` at the end of the Flow. Mule 3 Example: Responding To Incoming Messages ```xml ``` Mule 4 instead allows you to configure all the parameters associated to the response, directly inline as a part of the `listener` component, leaving behind the need of a transformation when reaching the end of the flow. Mule 4 Example: Responding To Incoming Messages ```xml #['BRIDGED'] ``` ## Doing Request-Reply JMS allows you to use the `JMSReplyTo` header to perform a synchronous communication. This can be done either with a temporary destination that is created on the fly by the client, or using an already existing destination. ### Request Reply With Temporary Destinations In Mule 3, for the first case where the reply destination is a temporary queue that will be discarded once the message arrives, we have the "request-response" exchange-pattern in the outbound endpoint: Mule 3 Example: Doing Request-Reply With Temporary Reply Destination ```xml ``` Instead, in Mule 4 you have a brand new operation called `publish-consume` which aims to solve this specific use case: Mule 4 Example: Doing Request-Reply With Temporary Reply Destination ```xml #[output application/xml --- { data: payload, costumer: attributes.queryParams.costumer_id }] ``` You may see that, again, the building of the Message is where inline of the operation, in the `message` element, and any transformation or configuration that affects the outgoing Message will be done as part of that element. ### Request Reply With Explicit Destinations Doing a request-reply with an explicit `reply-to` destination was a little bit more tricky in 3.x, since a new component was required, the `request-reply` Scope: Mule 3 Example: Doing Request-Reply With Explicit Reply Destination ```xml (1) ``` This scope (1) allowed you to set an inbound and outbound transport to do the request-reply pattern. This way, it would inject the `JMSReplyTo` header automatically in the outgoing Message and then started listening in the inbound endpoint For the case of Mule’s 4 JMS Connector with the new `publish-consume` operation, it requires you to do almost no changes to the flow. If you want an specific destination for the reply to be sent, just configure the `reply-to` header in the Message builder directly, as you would in any other case of either a publish or a response: Mule 4 Example: Doing Request-Reply With Temporary Reply Destination ```xml #[output application/xml --- { data: payload, costumer: attributes.queryParams.costumer_id }] (1) ``` In this example we set the reply destination header (<1>) to a well-known Topic, to illustrate that a known destination may be used by others to do things like event tracking or post-processing triggers. ## Using Transactions Transactions support is quite similar in its configuration when moving from 3.x to 4.x, with the expected change from it being configured in the `inbound-endpoint` and `outbound-endpoint` to the normalized Mule 4 approach for operations transactions: Mule 3 Example: Using Transactions ```xml (1) (2) (3) (4) (5) (6) (7) ``` Things to note are:
1Transaction is initiated by the inbound endpoint with ALWAYS_BEGIN
2We make sure not to loose the original payload
3Payload is transformed so it can be sent through the outbound endpoint
4The outbound endpoint is configured to ALWAYS_JOIN
5We set up the exception strategy to catch all exceptions
6Original payload is restored so the original message is published to the dead.letter
7Finally we send the original message to the dead.letter attempting to join to the current transaction.
Same scenario can be implemented in Mule 4 with the following approach: Mule 4 Example: Using Transactions ```xml (1) (2) #[output application/xml --- payload (3) (4) ```
1Transaction is initiated by the listener with ALWAYS_BEGIN
2Publishing of the payload in XML format is done by the publish operation without modifying the current payload, also joining the transaction with ALWAYS_JOIN
3An error handler that catches any error occurred is used to make sure the Message is not lost
4Since the current payload is still the original Message received, we just publish it to the dead.letter using the JOIN_IF_POSSIBLE transactional action
--- product: Mule Runtime version: 4.3 --- # Migrating Transformers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 4 does not require `transformers` anymore. Now that DataWeave is the default expression language and the repeatable streams feature is supported, most (if not all) scenarios that required a transformer no longer exist. ## Migrating Type Transformers In Mule 3, the same data can be represented using different types. For instance, a JSON can be stored using a `String`, `InputStream`, `OutputHandler`, or `ByteArray`. In the same way, an XML can be represented with those same types or in a Java DOM document. In Mule 4, every format that is not binary is handled automatically by Mule. So you do not need to be concerned about the type that is carrying the content. ### InputStream to String Transformations In Mule 3, the `` was commonly used so that data held by an `InputStream` could be consumed by more than one processor. Because Mule 4 has the concept of repeatable streams, this is no longer required. ### Object Model Representation for JSON and XML To access the content of an XML or JSON document in Mule 3, a conversion to a Java object representation model was needed so that Java code or MEL could be used later. In Mule 4, the expression language of the runtime completely supports JSON and XML (and many other formats), so this conversion is no longer needed. You simply use a DataWeave expression to access the data. ## Migrating Custom Transformers Most likely, any custom transformers you used to handle supported data formats are no longer needed, so they can be migrated to use the expression language. The DataWeave script can be externalized to a file if the same transformation needs to be occur in several places. For cases where you transform data in ways that DataWeave does not support, you should use the Java module or the Scripting module and use custom code to perform the transformation. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) [Scripting Module](https://docs.mulesoft.com/scripting-module/latest/) [Java Module](https://docs.mulesoft.com/java-module/latest/) [Streaming in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.3/streaming-about) [Why DataWeave is the Main Expression Language in Mule 4 Beta](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/why-dataweave-main-expression-language-mule-4/) --- product: Mule Runtime version: 4.4 --- # Migrating Transformers > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 4 does not require `transformers` anymore. Now that DataWeave is the default expression language and the repeatable streams feature is supported, most (if not all) scenarios that required a transformer no longer exist. ## Migrating Type Transformers In Mule 3, the same data can be represented using different types. For instance, a JSON can be stored using a `String`, `InputStream`, `OutputHandler`, or `ByteArray`. In the same way, an XML can be represented with those same types or in a Java DOM document. In Mule 4, every format that is not binary is handled automatically by Mule. So you do not need to be concerned about the type that is carrying the content. ### InputStream to String Transformations In Mule 3, the `` was commonly used so that data held by an `InputStream` could be consumed by more than one processor. Because Mule 4 has the concept of repeatable streams, this is no longer required. ### Object Model Representation for JSON and XML To access the content of an XML or JSON document in Mule 3, a conversion to a Java object representation model was needed so that Java code or MEL could be used later. In Mule 4, the expression language of the runtime completely supports JSON and XML (and many other formats), so this conversion is no longer needed. You simply use a DataWeave expression to access the data. ## Migrating Custom Transformers Most likely, any custom transformers you used to handle supported data formats are no longer needed, so they can be migrated to use the expression language. The DataWeave script can be externalized to a file if the same transformation needs to be occur in several places. For cases where you transform data in ways that DataWeave does not support, you should use the Java module or the Scripting module and use custom code to perform the transformation. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) [Scripting Module](https://docs.mulesoft.com/scripting-module/latest/) [Java Module](https://docs.mulesoft.com/java-module/latest/) [Streaming in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.4/streaming-about) [Why DataWeave is the Main Expression Language in Mule 4 Beta](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/why-dataweave-main-expression-language-mule-4/) --- product: Mule Runtime version: 4.3 --- # Migrating Transports > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 3 transports have been replaced by connectors, which follow an operation model in Mule 4. Most Mule transports are replaceable by a corresponding connector in Mule 4. Some migration issues are common to all transports. For transport-specific migration documentation, refer to [Migrating Connectors and Modules to Mule 4](https://docs.mulesoft.com/mule-runtime/4.3/migration-connectors) and its child pages, instead. ## Endpoint Addresses In Mule 3, an endpoint could be configured with either transport-specific attributes (for example, an HTTP endpoint could use `host`, `port`, and `path`) or with the generic `address` attribute. Whenever the generic `address` attribute was used, it was possible to reference a property, for example: ```xml ``` The properties configuration for `External.URL` looks something like this: ```text External.URL=http://0.0.0.0:8080/rootPath ``` In Mule 4, the connectors define the connection attributes separately, so any full address property has to be split into its components. ```xml ... ``` The configuration for the properties becomes: ```text External.URL.host=0.0.0.0 External.URL.port=8080 External.URL.path=/rootPath ``` Connector-specific documentation (such as for the HTTP or Email connector) provides detail on the exact properties that the connector requires. ## Service Overrides In Mule 4, service override customizations through custom Java code are not supported in Mule 4. In Mule 3, it is possible to customize the behavior of a transport through a connector’s `service-overrides` element. This element provides a way to reference Java classes with custom code that provides the new functionality. Mule 3 Example: Connector with `service-overrides` ```xml ``` The way to migrate such customizations to Mule 4 depends on what the custom code does, so you might: - Provide the functionality through another Mule feature or component, such as a [DataWeave](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) transformation, a [Java Module](https://docs.mulesoft.com/java-module/latest/), or a [Scripting Module](https://docs.mulesoft.com/scripting-module/latest/)). - Use the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/) to create a connector that provides your customized transport functionality. As a starting point, you can use open-source connectors as dependencies (for example, [https://github.com/mulesoft/mule-http-connector](https://github.com/mulesoft/mule-http-connector)). - Similar to the previous approach, you can fork an open-source connector repository and add your custom code to the fork. MuleSoft welcome Pull Requests for your changes. - Provide a feature request to MuleSoft. You can request that MuleSoft add the functionality that your custom code provided through `service-overrides`. Visit [MuleSoft Support Ideas](https://ideas.salesforce.com/s/search) to submit such requests. ## See Also [Migrating Connectors and Modules to Mule 4](https://docs.mulesoft.com/mule-runtime/4.3/migration-connectors) [Java Integration](https://docs.mulesoft.com/mule-runtime/4.3/intro-java-integration) [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/) --- product: Mule Runtime version: 4.4 --- # Migrating Transports > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 3 transports have been replaced by connectors, which follow an operation model in Mule 4. Most Mule transports are replaceable by a corresponding connector in Mule 4. Some migration issues are common to all transports. For transport-specific migration documentation, refer to [Migrating Connectors and Modules to Mule 4](https://docs.mulesoft.com/mule-runtime/4.4/migration-connectors) and its child pages, instead. ## Endpoint Addresses In Mule 3, an endpoint could be configured with either transport-specific attributes (for example, an HTTP endpoint could use `host`, `port`, and `path`) or with the generic `address` attribute. Whenever the generic `address` attribute was used, it was possible to reference a property, for example: ```xml ``` The properties configuration for `External.URL` looks something like this: ```text External.URL=http://0.0.0.0:8080/rootPath ``` In Mule 4, the connectors define the connection attributes separately, so any full address property has to be split into its components. ```xml ... ``` The configuration for the properties becomes: ```text External.URL.host=0.0.0.0 External.URL.port=8080 External.URL.path=/rootPath ``` Connector-specific documentation (such as for the HTTP or Email connector) provides detail on the exact properties that the connector requires. ## Service Overrides In Mule 4, service override customizations through custom Java code are not supported in Mule 4. In Mule 3, it is possible to customize the behavior of a transport through a connector’s `service-overrides` element. This element provides a way to reference Java classes with custom code that provides the new functionality. Mule 3 Example: Connector with `service-overrides` ```xml ``` The way to migrate such customizations to Mule 4 depends on what the custom code does, so you might: - Provide the functionality through another Mule feature or component, such as a [DataWeave](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) transformation, a [Java Module](https://docs.mulesoft.com/java-module/latest/), or a [Scripting Module](https://docs.mulesoft.com/scripting-module/latest/)). - Use the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/) to create a connector that provides your customized transport functionality. As a starting point, you can use open-source connectors as dependencies (for example, [https://github.com/mulesoft/mule-http-connector](https://github.com/mulesoft/mule-http-connector)). - Similar to the previous approach, you can fork an open-source connector repository and add your custom code to the fork. MuleSoft welcome Pull Requests for your changes. - Provide a feature request to MuleSoft. You can request that MuleSoft add the functionality that your custom code provided through `service-overrides`. Visit [MuleSoft Support Ideas](https://ideas.salesforce.com/s/search) to submit such requests. ## See Also [Migrating Connectors and Modules to Mule 4](https://docs.mulesoft.com/mule-runtime/4.4/migration-connectors) [Java Integration](https://docs.mulesoft.com/mule-runtime/4.4/intro-java-integration) [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/) --- product: Mule Runtime version: 4.3 --- # Migrating Watermarks > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Watermarking is typically used to perform data synchronization, for example, when polling a legacy resource to retrieve new data and to sync it with another destination endpoint. The watermarking technique stores and retrieves the point at which a periodic synchronization resumes the next time it executes. Watermarking is a typically used alongside ObjectStore. For the Mule 3 approach, see this MuleSoft blog: [Data Synchronizing made easy with Watermarks](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/data-synchronizing-made-easy-with-mule-watermarks/). Here’s the Mule 3 watermark example from that blog: Mule 3 Example: Polling Salesforce contacts using watermark ```xml ``` As the Anypoint Platform grew and our use cases became more complicated, limitations started to appear in the Mule 3 approach: - Although the old `` component did allow for setting a custom ObjectStore, there was no easy way to create it. This is a problem we already addressed in this document and know the new ObjectStore connector fixes - The `` element required the `` component (now replaced with ``) to return an iterable payload. Furthermore, you were required to fully iterate over that payload to obtain the new watermark value. Failure to do so resulted in the value being wrongfully updated or not updated at all. - There was no way to update the watermark with a contingency value in case of the flow throwing an error. - How and when the value got updated was not completely clear to non expert users. When we sat down to figure out how to improve this use case, we realized that the real root of the problem was that in reality the shouldn’t be necessary at all. It’s existence was just a consequence of limitations in other components: - The watermark’s artificial iteration was just a way to compensate for the fact that many data sets could only be iterated once, specially when dealing with binary streams or with connectors doing auto paging. This problem is now fixed in Mule 4 thanks to the repeatable streaming feature - The component’s automatic handling of the ObjectStore was just to compensate for UX problems on the old ObjectStore support. If the new connector were to provide easier semantics, it wouldn’t be needed at all. In Mule 4, you can perform the use case described in the Mule 3 blog post above like this: ```xml 2017-09-11T00:00:00.000Z " ++ vars.watermark] ]]> #[max(payload map $.LastModifiedDate)] ``` Let’s break the example down step by step: - First, this flow is generic. It doesn’t require to be triggered in any specific way. It could be invoked from another flow, you could add a `` to it, it doesn’t matter. You can now achieve watermark semantics without forcing any type of trigger. - This configuration starts by defining a custom ObjectStore for the watermark. This is not needed. You could not define an ObjectStore and just use the one that every application has implicit. But just for the sake of the example, we’ll use our own here. - The flow starts with a retrieve operation to get the last watermark value. Notice that: - The retrieve operation specifies a default value. This is so that when the flow runs for the first time and no watermark was calculated yet, you still get a usable value. This avoids the need for a `` → `` kind of pattern. - The Target (`target`) parameter is used to tell the connector not to override the message payload with the watermark, but instead put it in a variable. Because this has no side effect on the message, the flow is now reusable and easier to maintain, since you could add any kind of operation before the retrieve operation, nothing would break. - Then we perform the query, in which we use the watermark to filter the obtained results - Then we do whatever processing is needed. This can be anything from sending to another system, transforming, it doesn’t matter. - And finally, we update the watermark value. There’s a lot to be said about this step too: - The new watermark value should be the maximum updated timestamp. We use a DataWeave expression to obtain that value - Notice that thanks to the repeatable streaming feature, we now don’t care about what the integration logic was. Even if the query operation is auto paged (which it is!), this feature guarantees that we can still iterate the resultset again. - The `failIfPresent` parameter is set to false. Otherwise, the operation would only work the first time and fail if the watermark were already in the object store. By setting it to false, the value will be updated if present - And finally, the `failOnNullValue` parameter was set to false. Why? Because if the query comes back empty, the DW expression which looks for the max value will return null, because there’s no value. By setting this to true, the connector will automatically skip null values saving the user from using a `` router to check the condition ## Automatic Watermark The above is great and more powerful than what we had in Mule 3, but we wanted to make it even simpler. That’s why some connectors already include message sources capable of doing watermarking automatically, without the need for you to take any of the steps above. At the moment of writing this document, the File, Ftp, Sftp, Database and Salesforce connectors have this capability, but we will continue to add support for this in other connectors. Let’s use the file connector to see an example of how this works: Mule 4 Example: Automatic watermark in the file connector ```xml ``` In this example, we get automatic watermarking using the file’s creation time as a filtering criteria. The `watermarkMode` parameter can also be set to `MODIFIED_TIMESTAMP` if we wanted to listen for modified files instead or even to `DISABLED` if we don’t want any watermarking at all. We only recommend to take "the long way" described in the first example when: - Your use case is very custom - You are using a connector which doesn’t support automatic watermarking. In any other case, we recommend automatic watermarking as the best way of dealing with these use cases. ## See Also - [Object Store connector documentation](https://docs.mulesoft.com/object-store-connector/latest/) --- product: Mule Runtime version: 4.4 --- # Migrating Watermarks > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Watermarking is typically used to perform data synchronization, for example, when polling a legacy resource to retrieve new data and to sync it with another destination endpoint. The watermarking technique stores and retrieves the point at which a periodic synchronization resumes the next time it executes. Watermarking is a typically used alongside ObjectStore. For the Mule 3 approach, see this MuleSoft blog: [Data Synchronizing made easy with Watermarks](https://blogs.mulesoft.com/dev-guides/how-to-tutorials/data-synchronizing-made-easy-with-mule-watermarks/). Here’s the Mule 3 watermark example from that blog: Mule 3 Example: Polling Salesforce contacts using watermark ```xml ``` As the Anypoint Platform grew and our use cases became more complicated, limitations started to appear in the Mule 3 approach: - Although the old `` component did allow for setting a custom ObjectStore, there was no easy way to create it. This is a problem we already addressed in this document and know the new ObjectStore connector fixes - The `` element required the `` component (now replaced with ``) to return an iterable payload. Furthermore, you were required to fully iterate over that payload to obtain the new watermark value. Failure to do so resulted in the value being wrongfully updated or not updated at all. - There was no way to update the watermark with a contingency value in case of the flow throwing an error. - How and when the value got updated was not completely clear to non expert users. When we sat down to figure out how to improve this use case, we realized that the real root of the problem was that in reality the shouldn’t be necessary at all. It’s existence was just a consequence of limitations in other components: - The watermark’s artificial iteration was just a way to compensate for the fact that many data sets could only be iterated once, specially when dealing with binary streams or with connectors doing auto paging. This problem is now fixed in Mule 4 thanks to the repeatable streaming feature - The component’s automatic handling of the ObjectStore was just to compensate for UX problems on the old ObjectStore support. If the new connector were to provide easier semantics, it wouldn’t be needed at all. In Mule 4, you can perform the use case described in the Mule 3 blog post above like this: ```xml 2017-09-11T00:00:00.000Z " ++ vars.watermark] ]]> #[max(payload map $.LastModifiedDate)] ``` Let’s break the example down step by step: - First, this flow is generic. It doesn’t require to be triggered in any specific way. It could be invoked from another flow, you could add a `` to it, it doesn’t matter. You can now achieve watermark semantics without forcing any type of trigger. - This configuration starts by defining a custom ObjectStore for the watermark. This is not needed. You could not define an ObjectStore and just use the one that every application has implicit. But just for the sake of the example, we’ll use our own here. - The flow starts with a retrieve operation to get the last watermark value. Notice that: - The retrieve operation specifies a default value. This is so that when the flow runs for the first time and no watermark was calculated yet, you still get a usable value. This avoids the need for a `` → `` kind of pattern. - The Target (`target`) parameter is used to tell the connector not to override the message payload with the watermark, but instead put it in a variable. Because this has no side effect on the message, the flow is now reusable and easier to maintain, since you could add any kind of operation before the retrieve operation, nothing would break. - Then we perform the query, in which we use the watermark to filter the obtained results - Then we do whatever processing is needed. This can be anything from sending to another system, transforming, it doesn’t matter. - And finally, we update the watermark value. There’s a lot to be said about this step too: - The new watermark value should be the maximum updated timestamp. We use a DataWeave expression to obtain that value - Notice that thanks to the repeatable streaming feature, we now don’t care about what the integration logic was. Even if the query operation is auto paged (which it is!), this feature guarantees that we can still iterate the resultset again. - The `failIfPresent` parameter is set to false. Otherwise, the operation would only work the first time and fail if the watermark were already in the object store. By setting it to false, the value will be updated if present - And finally, the `failOnNullValue` parameter was set to false. Why? Because if the query comes back empty, the DW expression which looks for the max value will return null, because there’s no value. By setting this to true, the connector will automatically skip null values saving the user from using a `` router to check the condition ## Automatic Watermark The above is great and more powerful than what we had in Mule 3, but we wanted to make it even simpler. That’s why some connectors already include event sources capable of doing watermarking automatically, without the need for you to take any of the steps above. At the moment of writing this document, the File, Ftp, Sftp, Database and Salesforce connectors have this capability, but we will continue to add support for this in other connectors. Let’s use the file connector to see an example of how this works: Mule 4 Example: Automatic watermark in the file connector ```xml ``` In this example, we get automatic watermarking using the file’s creation time as a filtering criteria. The `watermarkMode` parameter can also be set to `MODIFIED_TIMESTAMP` if we wanted to listen for modified files instead or even to `DISABLED` if we don’t want any watermarking at all. We only recommend to take "the long way" described in the first example when: - Your use case is very custom - You are using a connector which doesn’t support automatic watermarking. In any other case, we recommend automatic watermarking as the best way of dealing with these use cases. ## See Also - [Object Store connector documentation](https://docs.mulesoft.com/object-store-connector/latest/) --- product: Mule Runtime version: 4.3 --- # Migrating WSC > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Here we are going to cover a couple of common cases using the Web Service Consumer how they were done in Mule 3 and how are they made now in the new Mule 4 release. ## Connecting with a web service Mule 4 introduces the concept of connection parameters, separating them from the other config parameters, that’s why you now are going to see a new tag in the configuration. Since all the parameters required for the web service consumer are used to create the connection all of them were moved to the group. ### A Simple web service configuration The parameters are the same ones, the only difference is that we added a new parameter `mtomEnabled` to the configuration that used to live in the operation. In mule 3.x we defined all the elements in the configuration like this. ```xml ``` Now all of the parameters are defined in the connection. ```xml ``` #### Defining a custom http configuration to send the messages It was very common in Mule 3 to define a custom configuration that the web service consumer can use to send the messages through the HTTP protocol with a custom configuration (TLS, different HTTP Authentications types, etc), of course you can still do this in Mule 4. The `connector-ref` configuration parameter was used before to set the connector configuration we wanted to send the messages (this only worked for HTTP and JMS). ```xml ``` To do the same in the new WSC you will need to add a `` parameter the connection and specify the http configuration desired. This will **only** work with HTTP requester configurations and will fail at runtime if not configured properly. ```xml ``` ## Consuming a Web Service In Mule 3 the WSC expected that the payload was an already created XML body, so in most of the cases the WSC component was used after a Transform component. ```xml ... #[ %dw 1.0 output application/xml ns con http://service.soap.service.mule.org/ --- con#echo: { text: "Hello!" } ] ... ``` Now you don’t need that extra component the consume operation enables you to build the body XML directly as an operation parameter using DataWeave, take a look at the example below. ```xml ... #[ %dw 2.0 output application/xml ns con http://service.soap.service.mule.org/ --- con#echo: { text: "Hello!" } ] ... ``` ### Sending Headers The way the WSC works with attachments in Mule 3 is by collecting all the outboundProperties that starts with the `soap.` prefix, for example: if we added a variable `soap.CrazyHeader` when the WSC executes it will get the content of the variable and put the variable content in the SoapHeaders element of the envelope. That’s not a pretty behavior, that’s why in Mule 4, the Headers are just another parameter (and of course you have metadata for those also). Let’s look a sample XML of Mule 3 ```xml ... ``` And now, in Mule 4 ```xml #[ %dw 2.0 output application/xml ns con http://service.soap.service.mule.org/ --- "headers": { con#aHeader: { text: "Hello!" }, con#anotherHeader: "Hello! says another header" }] ``` The headers can be constructed directly inside the operation with a DataWeave script, and since you have metadata for this, is super easy to do. ### Adding Attachments Adding attachments is much more easier now, in Mule 3 when working with **MTOM attachments** the `set-attachment` component was used to create a new outbound attachment and the envelope body should be constructed adding a reference an XOP reference to that added attachment. > [!NOTE] the mtomEnabled parameter was moved from the operation to the connection. ```xml ... #[ %dw 1.0 output application/xml ns con http://service.soap.service.mule.org/ ns xop http://www.w3.org/2004/08/xop/include --- con#echo: { attachment: { xop: "cid:attach" } } ] ... ``` If working with **Soap With Attachments** instead of MTOM, it was responsibility of the mule developer to build the body with the inner attachment encoded in Base64 (DataWeave provided a function to do this) ```xml ... #[ %dw 1.0 output application/xml ns con http://service.soap.service.mule.org/ ns xop http://www.w3.org/2004/08/xop/include --- con#echo: { attachment: { xop: "cid:attach" } } ] ... ``` In Mule 4 it doesn’t matter if it’s MTOM or SWA, the dev always works the same way with attachments, he just creates a new attachment and assigns the content to it (the mimetype used is the one that is associated to content). For example, here we read a JSON file using the file connector and then create a new attachment passing the content returned by the file:read operation in the payload. ```xml ... #[{ attach: payload } ] ... ``` To use the Web Service Consumer, simply add it to your application using the Studio palette or add the following dependency in your `pom.xml` file: ```xml org.mule.connectors mule-wsc-connector 1.1.0 mule-plugin ``` --- product: Mule Runtime version: 4.4 --- # Migrating WSC > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Here we are going to cover a couple of common cases using the Web Service Consumer how they were done in Mule 3 and how are they made now in the new Mule 4 release. > [!NOTE] The Web Service Consumer Connector in Mule 4 does not support the JMS transport feature. ## Connecting with a web service Mule 4 introduces the concept of connection parameters, separating them from the other config parameters, that’s why you now are going to see a new tag in the configuration. Since all the parameters required for the web service consumer are used to create the connection all of them were moved to the group. ### A Simple web service configuration The parameters are the same ones, the only difference is that we added a new parameter `mtomEnabled` to the configuration that used to live in the operation. In mule 3.x we defined all the elements in the configuration like this. ```xml ``` Now all of the parameters are defined in the connection. ```xml ``` #### Defining a custom http configuration to send the messages It was very common in Mule 3 to define a custom configuration that the web service consumer can use to send the messages through the HTTP protocol with a custom configuration (TLS, different HTTP Authentications types, etc), of course you can still do this in Mule 4. The `connector-ref` configuration parameter was used before to set the connector configuration we wanted to send the messages (this only worked for HTTP and JMS). ```xml ``` To do the same in the new WSC you will need to add a `` parameter the connection and specify the http configuration desired. This will **only** work with HTTP requester configurations and will fail at runtime if not configured properly. ```xml ``` ## Consuming a Web Service In Mule 3 the WSC expected that the payload was an already created XML body, so in most of the cases the WSC component was used after a Transform component. ```xml ... #[ %dw 1.0 output application/xml ns con http://service.soap.service.mule.org/ --- con#echo: { text: "Hello!" } ] ... ``` Now you don’t need that extra component the consume operation enables you to build the body XML directly as an operation parameter using DataWeave, take a look at the example below. ```xml ... #[ %dw 2.0 output application/xml ns con http://service.soap.service.mule.org/ --- con#echo: { text: "Hello!" } ] ... ``` ### Sending Headers The way the WSC works with attachments in Mule 3 is by collecting all the outboundProperties that starts with the `soap.` prefix, for example: if we added a variable `soap.CrazyHeader` when the WSC executes it will get the content of the variable and put the variable content in the SoapHeaders element of the envelope. That’s not a pretty behavior, that’s why in Mule 4, the Headers are just another parameter (and of course you have metadata for those also). Let’s look a sample XML of Mule 3 ```xml ... ``` And now, in Mule 4 ```xml #[ %dw 2.0 output application/xml ns con http://service.soap.service.mule.org/ --- "headers": { con#aHeader: { text: "Hello!" }, con#anotherHeader: "Hello! says another header" }] ``` The headers can be constructed directly inside the operation with a DataWeave script, and since you have metadata for this, is super easy to do. ### Adding Attachments Adding attachments is much more easier now, in Mule 3 when working with **MTOM attachments** the `set-attachment` component was used to create a new outbound attachment and the envelope body should be constructed adding a reference an XOP reference to that added attachment. > [!NOTE] the mtomEnabled parameter was moved from the operation to the connection. ```xml ... #[ %dw 1.0 output application/xml ns con http://service.soap.service.mule.org/ ns xop http://www.w3.org/2004/08/xop/include --- con#echo: { attachment: { xop: "cid:attach" } } ] ... ``` If working with **Soap With Attachments** instead of MTOM, it was responsibility of the mule developer to build the body with the inner attachment encoded in Base64 (DataWeave provided a function to do this) ```xml ... #[ %dw 1.0 output application/xml ns con http://service.soap.service.mule.org/ ns xop http://www.w3.org/2004/08/xop/include --- con#echo: { attachment: { xop: "cid:attach" } } ] ... ``` In Mule 4 it doesn’t matter if it’s MTOM or SWA, the dev always works the same way with attachments, he just creates a new attachment and assigns the content to it (the mimetype used is the one that is associated to content). For example, here we read a JSON file using the file connector and then create a new attachment passing the content returned by the file:read operation in the payload. ```xml ... #[{ attach: payload } ] ... ``` To use the Web Service Consumer, simply add it to your application using the Studio palette or add the following dependency in your `pom.xml` file: ```xml org.mule.connectors mule-wsc-connector 1.1.0 mule-plugin ``` --- product: Mule Runtime version: 4.3 --- # Migration to Mule 4 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt For your Mule 3 apps to take advantage of Mule 4, migrate them to Mule 4 through one of the following processes: - A fully manual migration of connectors, modules, transports, expressions, and API gateways to their Mule 4 counterparts. For guidance with a fully manual migration, see [Prepare to Migrate](https://docs.mulesoft.com/mule-runtime/4.3/migration-prep) and review [Manual Migration Process](https://docs.mulesoft.com/mule-runtime/4.3/migration-process). - A partially automated migration with the Mule Migration Assistant (MMA), which is available as an open source project on GitHub. For guidance using MMA to assist in a migration, see the [user documentation (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/migration-intro.adoc#understand-the-mma-migration-process). MuleSoft suggests that you try MMA to determine whether you prefer it to a fully manual migration. Note that you can run MMA on a sample application by following steps in the [Migration Tutorial (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-tutorial.adoc). Important **Mule Migration Assistant (MMA) is subject to the terms and conditions described for [Community](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf) connectors. Additionally, Mule Migration Assistant is distributed under the terms of the [3-Clause BSD License](https://github.com/mulesoft/mule-migration-assistant/blob/master/LICENSE.txt).** A benefit of using MMA is that it automates part of the migration of Mule 3 apps to Mule 4. Though the MMA does not migrate the app entirely, it provides significant help with the following tasks: - Migrating the project structure. - Automatically creating descriptor files, such as `pom.xml` or `mule-artifact.json`. - Automatically performing many adaptations of the app’s code. - Providing guidance on how to manually migrate components and patterns that cannot be migrated automatically. MMA helps with such tasks, but it does not deliver a fully functional app. Some additional steps are required. Those steps include testing and can also include: - Manual migration of unsupported components. - Manual migration of complex MEL expressions to DataWeave that cannot be automatically converted by MMA. - Manual migration of complex DataWeave transformations that cannot be automatically converted by MMA. - Prior migration of the DataMapper with the DataWeave Migration tool, before running the MMA. It is also important to note that the MMA does not support incremental migrations. --- product: Mule Runtime version: 4.4 --- # Migration to Mule 4 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt For your Mule 3 apps to take advantage of Mule 4, migrate them to Mule 4 through one of the following processes: - A fully manual migration of connectors, modules, transports, expressions, and API gateways to their Mule 4 counterparts. For guidance with a fully manual migration, see [Prepare to Migrate](https://docs.mulesoft.com/mule-runtime/4.4/migration-prep) and review [Manual Migration Process](https://docs.mulesoft.com/mule-runtime/4.4/migration-process). - A partially automated migration with the Mule Migration Assistant (MMA), which is available as an open source project on GitHub. For guidance using MMA to assist in a migration, see the [user documentation (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/migration-intro.adoc#understand-the-mma-migration-process). MuleSoft suggests that you try MMA to determine whether you prefer it to a fully manual migration. Note that you can run MMA on a sample application by following steps in the [Migration Tutorial (on GitHub)](https://github.com/mulesoft/mule-migration-assistant/blob/master/docs/user-docs/migration-tutorial.adoc). Important **Mule Migration Assistant (MMA) is subject to the terms and conditions described for [Community](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf) connectors. Additionally, Mule Migration Assistant is distributed under the terms of the [3-Clause BSD License](https://github.com/mulesoft/mule-migration-assistant/blob/master/LICENSE.txt).** A benefit of using MMA is that it automates part of the migration of Mule 3 apps to Mule 4. Though the MMA does not migrate the app entirely, it provides significant help with the following tasks: - Migrating the project structure. - Automatically creating descriptor files, such as `pom.xml` or `mule-artifact.json`. - Automatically performing many adaptations of the app’s code. - Providing guidance on how to manually migrate components and patterns that cannot be migrated automatically. MMA helps with such tasks, but it does not deliver a fully functional app. Some additional steps are required. Those steps include testing and can also include: - Manual migration of unsupported components. - Manual migration of complex MEL expressions to DataWeave that cannot be automatically converted by MMA. - Manual migration of complex DataWeave transformations that cannot be automatically converted by MMA. - Prior migration of the DataMapper with the DataWeave Migration tool, before running the MMA. It is also important to note that the MMA does not support incremental migrations. --- product: Mule Runtime version: 4.11 keywords: anypoint studio, team, shared projects --- # Modularize Configuration Files > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Though it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. This is why MuleSoft recommends that you split monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Splitting configurations into multiple files encourages reuse across teams. Mule offers two options for loading multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. In practice, it’s common to use both approaches simultaneously. Because configuration files are loaded in the same context, you must use unique names for the configuration elements. Mule will not load an application if its configuration files have name conflicts. Here are some suggested ways to determine where to split configuration elements into separate files and which elements to keep together: - Business domains usually form a natural border that you can use to separate configuration elements. - Keep together elements that have been changed for similar reasons. This reduces the risk of impacting unrelated aspects of your application. - Technical elements, such as administrative components, security, and external system configurations determine good separation lines. - Separate a side-by-side connector configuration to facilitate functional testing. (This suggestion does not apply to environment-specific connector configurations, which use properties files.) - Consider reuse across teams and projects when you separate configuration elements. > [!NOTE] By default, Mule treats all XML configuration files as configurations when an application > is packaged and loaded in the side-by-side fashion. ## Imported configuration files Mule has a special `import` configuration component for importing configuration files into each other. This component takes a `file` parameter, which contains the reference to the desired configuration file. The following example shows a main configuration file that imports three other configuration elements: `global-configurations.xml`, `admin-config.xml`, and `audit-flows.xml` ```xml ``` > [!NOTE] The import mechanism requires that the XML files are in the classpath. ## See also - [Develop Mule Applications](https://docs.mulesoft.com/mule-runtime/4.11/mule-app-dev) --- product: Mule Runtime version: 4.12 keywords: anypoint studio, team, shared projects --- # Modularize Configuration Files > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Though it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. This is why MuleSoft recommends that you split monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Splitting configurations into multiple files encourages reuse across teams. Mule offers two options for loading multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. In practice, it’s common to use both approaches simultaneously. Because configuration files are loaded in the same context, you must use unique names for the configuration elements. Mule will not load an application if its configuration files have name conflicts. Here are some suggested ways to determine where to split configuration elements into separate files and which elements to keep together: - Business domains usually form a natural border that you can use to separate configuration elements. - Keep together elements that have been changed for similar reasons. This reduces the risk of impacting unrelated aspects of your application. - Technical elements, such as administrative components, security, and external system configurations determine good separation lines. - Separate a side-by-side connector configuration to facilitate functional testing. (This suggestion does not apply to environment-specific connector configurations, which use properties files.) - Consider reuse across teams and projects when you separate configuration elements. > [!NOTE] By default, Mule treats all XML configuration files as configurations when an application > is packaged and loaded in the side-by-side fashion. ## Imported configuration files Mule has a special `import` configuration component for importing configuration files into each other. This component takes a `file` parameter, which contains the reference to the desired configuration file. The following example shows a main configuration file that imports three other configuration elements: `global-configurations.xml`, `admin-config.xml`, and `audit-flows.xml` ```xml ``` > [!NOTE] The import mechanism requires that the XML files are in the classpath. ## See also - [Develop Mule Applications](https://docs.mulesoft.com/mule-runtime/4.12/mule-app-dev) --- product: Mule Runtime version: 4.3 keywords: anypoint studio, team, shared projects --- # Modularize Configuration Files > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Though it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. This is why MuleSoft recommends that you split monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Splitting configurations into multiple files encourages reuse across teams. Mule offers two options for loading multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. In practice, it’s common to use both approaches simultaneously. Because configuration files are loaded in the same context, you must use unique names for the configuration elements. Mule will not load an application if its configuration files have name conflicts. Here are some suggested ways to determine where to split configuration elements into separate files and which elements to keep together: - Business domains usually form a natural border that you can use to separate configuration elements. - Keep together elements that have been changed for similar reasons. This reduces the risk of impacting unrelated aspects of your application. - Technical elements, such as administrative components, security, and external system configurations determine good separation lines. - Separate a side-by-side connector configuration to facilitate functional testing. (This suggestion does not apply to environment-specific connector configurations, which use properties files.) - Consider reuse across teams and projects when you separate configuration elements. > [!NOTE] By default, Mule treats all XML configuration files as configurations when an application > is packaged and loaded in the side-by-side fashion. ## Imported configuration files Mule has a special `import` configuration component for importing configuration files into each other. This component takes a `file` parameter, which contains the reference to the desired configuration file. The following example shows a main configuration file that imports three other configuration elements: `global-configurations.xml`, `admin-config.xml`, and `audit-flows.xml` ```xml ``` > [!NOTE] The import mechanism requires that the XML files are in the classpath. ## See also - [Introduction to Mule 4: Packaging Applications](https://docs.mulesoft.com/mule-runtime/4.3/intro-packaging) --- product: Mule Runtime version: 4.4 keywords: anypoint studio, team, shared projects --- # Modularize Configuration Files > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Though it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. This is why MuleSoft recommends that you split monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Splitting configurations into multiple files encourages reuse across teams. Mule offers two options for loading multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. In practice, it’s common to use both approaches simultaneously. Because configuration files are loaded in the same context, you must use unique names for the configuration elements. Mule will not load an application if its configuration files have name conflicts. Here are some suggested ways to determine where to split configuration elements into separate files and which elements to keep together: - Business domains usually form a natural border that you can use to separate configuration elements. - Keep together elements that have been changed for similar reasons. This reduces the risk of impacting unrelated aspects of your application. - Technical elements, such as administrative components, security, and external system configurations determine good separation lines. - Separate a side-by-side connector configuration to facilitate functional testing. (This suggestion does not apply to environment-specific connector configurations, which use properties files.) - Consider reuse across teams and projects when you separate configuration elements. > [!NOTE] By default, Mule treats all XML configuration files as configurations when an application > is packaged and loaded in the side-by-side fashion. ## Imported configuration files Mule has a special `import` configuration component for importing configuration files into each other. This component takes a `file` parameter, which contains the reference to the desired configuration file. The following example shows a main configuration file that imports three other configuration elements: `global-configurations.xml`, `admin-config.xml`, and `audit-flows.xml` ```xml ``` > [!NOTE] The import mechanism requires that the XML files are in the classpath. ## See also - [Introduction to Mule 4: Packaging Applications](https://docs.mulesoft.com/mule-runtime/4.4/intro-packaging) --- product: Mule Runtime version: 4.6 keywords: anypoint studio, team, shared projects --- # Modularize Configuration Files > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Though it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. This is why MuleSoft recommends that you split monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Splitting configurations into multiple files encourages reuse across teams. Mule offers two options for loading multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. In practice, it’s common to use both approaches simultaneously. Because configuration files are loaded in the same context, you must use unique names for the configuration elements. Mule will not load an application if its configuration files have name conflicts. Here are some suggested ways to determine where to split configuration elements into separate files and which elements to keep together: - Business domains usually form a natural border that you can use to separate configuration elements. - Keep together elements that have been changed for similar reasons. This reduces the risk of impacting unrelated aspects of your application. - Technical elements, such as administrative components, security, and external system configurations determine good separation lines. - Separate a side-by-side connector configuration to facilitate functional testing. (This suggestion does not apply to environment-specific connector configurations, which use properties files.) - Consider reuse across teams and projects when you separate configuration elements. > [!NOTE] By default, Mule treats all XML configuration files as configurations when an application > is packaged and loaded in the side-by-side fashion. ## Imported configuration files Mule has a special `import` configuration component for importing configuration files into each other. This component takes a `file` parameter, which contains the reference to the desired configuration file. The following example shows a main configuration file that imports three other configuration elements: `global-configurations.xml`, `admin-config.xml`, and `audit-flows.xml` ```xml ``` > [!NOTE] The import mechanism requires that the XML files are in the classpath. ## See also - [Develop Mule Applications](https://docs.mulesoft.com/mule-runtime/4.6/mule-app-dev) --- product: Mule Runtime version: 4.9 keywords: anypoint studio, team, shared projects --- # Modularize Configuration Files > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Though it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. This is why MuleSoft recommends that you split monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Splitting configurations into multiple files encourages reuse across teams. Mule offers two options for loading multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. In practice, it’s common to use both approaches simultaneously. Because configuration files are loaded in the same context, you must use unique names for the configuration elements. Mule will not load an application if its configuration files have name conflicts. Here are some suggested ways to determine where to split configuration elements into separate files and which elements to keep together: - Business domains usually form a natural border that you can use to separate configuration elements. - Keep together elements that have been changed for similar reasons. This reduces the risk of impacting unrelated aspects of your application. - Technical elements, such as administrative components, security, and external system configurations determine good separation lines. - Separate a side-by-side connector configuration to facilitate functional testing. (This suggestion does not apply to environment-specific connector configurations, which use properties files.) - Consider reuse across teams and projects when you separate configuration elements. > [!NOTE] By default, Mule treats all XML configuration files as configurations when an application > is packaged and loaded in the side-by-side fashion. ## Imported configuration files Mule has a special `import` configuration component for importing configuration files into each other. This component takes a `file` parameter, which contains the reference to the desired configuration file. The following example shows a main configuration file that imports three other configuration elements: `global-configurations.xml`, `admin-config.xml`, and `audit-flows.xml` ```xml ``` > [!NOTE] The import mechanism requires that the XML files are in the classpath. ## See also - [Develop Mule Applications](https://docs.mulesoft.com/mule-runtime/4.9/mule-app-dev) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: anypoint studio, team, shared projects --- # Modularize Configuration Files > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Though it might seem convenient to keep your Mule configurations in one file, a very large XML file quickly becomes unmanageable. This is why MuleSoft recommends that you split monolithic configurations into several files, and leverage Mule’s capacity to load multiple configuration files at application start-up time. Splitting configurations into multiple files encourages reuse across teams. Mule offers two options for loading multiple configuration files: - Side-by-side: Provide a list of independent configuration files to load. - Imported: Have one configuration file import several others, which in turn, can import other files. In practice, it’s common to use both approaches simultaneously. Because configuration files are loaded in the same context, you must use unique names for the configuration elements. Mule will not load an application if its configuration files have name conflicts. Here are some suggested ways to determine where to split configuration elements into separate files and which elements to keep together: - Business domains usually form a natural border that you can use to separate configuration elements. - Keep together elements that have been changed for similar reasons. This reduces the risk of impacting unrelated aspects of your application. - Technical elements, such as administrative components, security, and external system configurations determine good separation lines. - Separate a side-by-side connector configuration to facilitate functional testing. (This suggestion does not apply to environment-specific connector configurations, which use properties files.) - Consider reuse across teams and projects when you separate configuration elements. > [!NOTE] By default, Mule treats all XML configuration files as configurations when an application > is packaged and loaded in the side-by-side fashion. ## Imported configuration files Mule has a special `import` configuration component for importing configuration files into each other. This component takes a `file` parameter, which contains the reference to the desired configuration file. The following example shows a main configuration file that imports three other configuration elements: `global-configurations.xml`, `admin-config.xml`, and `audit-flows.xml` ```xml ``` > [!NOTE] The import mechanism requires that the XML files are in the classpath. ## See also - [Develop Mule Applications](https://docs.mulesoft.com/mule-runtime/latest/mule-app-dev) --- product: Mule Runtime version: 4.11 --- # Move Transformation to Separate Files (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the DataWeave code from a Transform Message component is expressed inline within your Mule XML file. You can instead keep each in a separate file ( `.dwl` ) and have your XML reference them. These files are packaged with your Mule application when built. To export the DataWeave code to a `.dwl` file: 1. Click the **Edit Current Target** button. ![An edit icon in the Transform Message component](/mulesoft/current/en-us/mule-runtime/4.11/_images/dw-multiple-outputs-edit.png) 2. Select the **File** radio button. ![A target output payload with an option to choose a source code](/mulesoft/current/en-us/mule-runtime/4.11/_images/dataweave-externalfile2.png) - Type a name for your `.dwl` file. - Click **OK**. A file is created under the `src/main/resources` folder in your project containing your DataWeave code. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.11/dataweave) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.11/transform-component-about) --- product: Mule Runtime version: 4.12 --- # Move Transformation to Separate Files (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the DataWeave code from a Transform Message component is expressed inline within your Mule XML file. You can instead keep each in a separate file ( `.dwl` ) and have your XML reference them. These files are packaged with your Mule application when built. To export the DataWeave code to a `.dwl` file: 1. Click the **Edit Current Target** button. ![An edit icon in the Transform Message component](/mulesoft/current/en-us/mule-runtime/4.12/_images/dw-multiple-outputs-edit.png) 2. Select the **File** radio button. ![A target output payload with an option to choose a source code](/mulesoft/current/en-us/mule-runtime/4.12/_images/dataweave-externalfile2.png) - Type a name for your `.dwl` file. - Click **OK**. A file is created under the `src/main/resources` folder in your project containing your DataWeave code. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.12/dataweave) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.12/transform-component-about) --- product: Mule Runtime version: 4.3 --- # Move Transformation to Separate Files (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the DataWeave code from a Transform Message component is expressed inline within your Mule XML file. You can instead keep each in a separate file ( `.dwl` ) and have your XML reference them. These files are packaged with your Mule application when built. To export the DataWeave code to a `.dwl` file: 1. Click the **Edit Current Target** button. ![edit target](/mulesoft/current/en-us/mule-runtime/4.3/_images/dw-multiple-outputs-edit.png) 2. Select the **File** radio button. ![external file 2](/mulesoft/current/en-us/mule-runtime/4.3/_images/dataweave-externalfile2.png) - Type a name for your `.dwl` file. - Click **OK**. A file is created under the `src/main/resources` folder in your project containing your DataWeave code. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.3/dataweave) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.3/transform-component-about) --- product: Mule Runtime version: 4.4 --- # Move Transformation to Separate Files (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the DataWeave code from a Transform Message component is expressed inline within your Mule XML file. You can instead keep each in a separate file ( `.dwl` ) and have your XML reference them. These files are packaged with your Mule application when built. To export the DataWeave code to a `.dwl` file: 1. Click the **Edit Current Target** button. ![edit target](/mulesoft/current/en-us/mule-runtime/4.4/_images/dw-multiple-outputs-edit.png) 2. Select the **File** radio button. ![external file 2](/mulesoft/current/en-us/mule-runtime/4.4/_images/dataweave-externalfile2.png) - Type a name for your `.dwl` file. - Click **OK**. A file is created under the `src/main/resources` folder in your project containing your DataWeave code. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.4/dataweave) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.4/transform-component-about) --- product: Mule Runtime version: 4.6 --- # Move Transformation to Separate Files (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the DataWeave code from a Transform Message component is expressed inline within your Mule XML file. You can instead keep each in a separate file ( `.dwl` ) and have your XML reference them. These files are packaged with your Mule application when built. To export the DataWeave code to a `.dwl` file: 1. Click the **Edit Current Target** button. ![edit target](/mulesoft/current/en-us/mule-runtime/4.6/_images/dw-multiple-outputs-edit.png) 2. Select the **File** radio button. ![external file 2](/mulesoft/current/en-us/mule-runtime/4.6/_images/dataweave-externalfile2.png) - Type a name for your `.dwl` file. - Click **OK**. A file is created under the `src/main/resources` folder in your project containing your DataWeave code. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.6/dataweave) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.6/transform-component-about) --- product: Mule Runtime version: 4.9 --- # Move Transformation to Separate Files (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the DataWeave code from a Transform Message component is expressed inline within your Mule XML file. You can instead keep each in a separate file ( `.dwl` ) and have your XML reference them. These files are packaged with your Mule application when built. To export the DataWeave code to a `.dwl` file: 1. Click the **Edit Current Target** button. ![An edit icon in the Transform Message component](/mulesoft/current/en-us/mule-runtime/4.9/_images/dw-multiple-outputs-edit.png) 2. Select the **File** radio button. ![A target output payload with an option to choose a source code](/mulesoft/current/en-us/mule-runtime/4.9/_images/dataweave-externalfile2.png) - Type a name for your `.dwl` file. - Click **OK**. A file is created under the `src/main/resources` folder in your project containing your DataWeave code. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/4.9/dataweave) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/4.9/transform-component-about) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Move Transformation to Separate Files (Anypoint Studio) > For the full documentation index, see: https://docs.mulesoft.com/llms.txt By default, the DataWeave code from a Transform Message component is expressed inline within your Mule XML file. You can instead keep each in a separate file ( `.dwl` ) and have your XML reference them. These files are packaged with your Mule application when built. To export the DataWeave code to a `.dwl` file: 1. Click the **Edit Current Target** button. ![An edit icon in the Transform Message component](/mulesoft/current/en-us/mule-runtime/latest/_images/dw-multiple-outputs-edit.png) 2. Select the **File** radio button. ![A target output payload with an option to choose a source code](/mulesoft/current/en-us/mule-runtime/latest/_images/dataweave-externalfile2.png) - Type a name for your `.dwl` file. - Click **OK**. A file is created under the `src/main/resources` folder in your project containing your DataWeave code. ## See Also [DataWeave Language](https://docs.mulesoft.com/mule-runtime/latest/dataweave) [Transform Message Component](https://docs.mulesoft.com/mule-runtime/latest/transform-component-about) --- product: Mule Runtime version: 4.3 --- # Mule 3 to Mule 4 Cheat Sheet > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you move from Mule 3 to Mule 4, we built this index to help you find the Mule 4 equivalent of the most common Mule 3 use cases. **IMPORTANT:** Keep in mind that this index is only intended to act as a quick entry to the most common migration scenarios. It doesn’t contain the entire migration guide. For the full set of migration articles, please visit our Mule [Mule 4 for Mule 3 Users](https://docs.mulesoft.com/mule-runtime/4.3/index-migration) page. - [Configuration Properties](https://docs.mulesoft.com/mule-runtime/4.3/configuring-properties): There’s a new way of handling configuration properties in Mule 4 - [Using Secure Properties](https://docs.mulesoft.com/mule-runtime/4.3/migration-secure-properties-placeholder): Secure placeholders are now a Runtime feature and no longer part of the Security Module - [Using the HTTP Connector](https://docs.mulesoft.com/mule-runtime/4.3/migration-connectors-http): The new HTTP connector has some differences with Mule 3, especially when it comes to handling multipart and form requests. - [From MEL to DataWeave](https://docs.mulesoft.com/mule-runtime/4.3/migration-mel): DataWeave 2.0 is now the expression language. Here’s how to adapt your MEL expressions to DataWeave. - [From DataWeave 1.0 to DataWeave 2.0](https://docs.mulesoft.com/mule-runtime/4.3/migration-dataweave): A new version of DataWeave is available in Mule 4 - Where are the explicit transformers?: Transformers like `` or `` are no longer necessary. Mule handles this automatically under the covers - [Define a custom Object Store](https://docs.mulesoft.com/object-store-connector/latest/object-store-to-define-a-new-os): Custom Object Stores are now defined through the new connector - [Use watermarks](https://docs.mulesoft.com/mule-runtime/4.3/migration-patterns-watermark): Watermarks have been simplified. You can also do it manually now allowing for more complex use cases. - [Accessing the Mule Message](https://docs.mulesoft.com/mule-runtime/4.3/migration-message-properties): The Mule Message has a new structure and it’s accessed differently. Here’s a quick overview. - Using Java: Interoperability with Java is now done through the [Java module](https://docs.mulesoft.com/java-module/latest/). Optionally you can also try the [Scripting module](https://docs.mulesoft.com/mule-runtime/4.3/migration-module-scripting) or the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/) - [Using Spring](https://docs.mulesoft.com/mule-runtime/4.3/migration-module-spring): Instead of defining Spring beans directly in your application, you can now use the [Spring Module](https://docs.mulesoft.com/spring-module/latest/). - [Using reconnection strategies](https://docs.mulesoft.com/mule-runtime/4.3/migration-patterns-reconnection-strategies): There are some small but important differences around reconnection in Mule 4. - [Classloading isolation](https://docs.mulesoft.com/mule-runtime/4.3/about-classloading-isolation): Classloading isolation changes the way resources and classes are shared. Read this article to learn more. - [Core Components Migration](https://docs.mulesoft.com/mule-runtime/4.3/migration-core): A comprehensive list of the changes that were made to the core language elements - [Using the new connectors](https://docs.mulesoft.com/mule-runtime/4.3/migration-connectors): A comprehensive list of the changes that were made to the main connectors. - [Using the Security Module (AES)](https://docs.mulesoft.com/mule-runtime/4.3/migration-aes): Anypoint Enterprise Security module was split into different modules explained here. - [Migrating Gateways](https://docs.mulesoft.com/mule-runtime/4.3/migration-api-gateways): This section covers the migration of API Gateway related features. - [Migrating ApiKit apps](https://docs.mulesoft.com/mule-runtime/4.3/migration-example-complex): Covers the necessary steps to successfully migrate APIkit-based applications. - Migrating custom components: You can use the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/) to create your own reusable components - [Transport service overrides](https://docs.mulesoft.com/mule-runtime/4.3/migration-transports): Covers how to migrate from generic transports. - [on-premises::mule-high-availability-ha-clusters.adoc#configure-the-performance-profile](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#configure-the-performance-profile): At a container level, change the property from `mule.clusterPartitioningMode=OPTIMIZE_PERFORMANCE` to `mule.cluster.storeprofile=performance`. At an individual application level, you can configure the store profile for a specific Mule application. --- product: Mule Runtime version: 4.4 --- # Mule 3 to Mule 4 Cheat Sheet > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To help you move from Mule 3 to Mule 4, we built this index to help you find the Mule 4 equivalent of the most common Mule 3 use cases. **IMPORTANT:** Keep in mind that this index is only intended to act as a quick entry to the most common migration scenarios. It doesn’t contain the entire migration guide. For the full set of migration articles, please visit our Mule [Mule 4 for Mule 3 Users](https://docs.mulesoft.com/mule-runtime/4.4/index-migration) page. - [Configuration Properties](https://docs.mulesoft.com/mule-runtime/4.4/configuring-properties): There’s a new way of handling configuration properties in Mule 4 - [Using Secure Properties](https://docs.mulesoft.com/mule-runtime/4.4/migration-secure-properties-placeholder): Secure placeholders are now a Runtime feature and no longer part of the Security Module - [Using the HTTP Connector](https://docs.mulesoft.com/mule-runtime/4.4/migration-connectors-http): The new HTTP connector has some differences with Mule 3, especially when it comes to handling multipart and form requests. - [From MEL to DataWeave](https://docs.mulesoft.com/mule-runtime/4.4/migration-mel): DataWeave 2.0 is now the expression language. Here’s how to adapt your MEL expressions to DataWeave. - [From DataWeave 1.0 to DataWeave 2.0](https://docs.mulesoft.com/mule-runtime/4.4/migration-dataweave): A new version of DataWeave is available in Mule 4 - Where are the explicit transformers?: Transformers like `` or `` are no longer necessary. Mule handles this automatically under the covers - [Define a custom Object Store](https://docs.mulesoft.com/object-store-connector/latest/object-store-to-define-a-new-os): Custom Object Stores are now defined through the new connector - [Use watermarks](https://docs.mulesoft.com/mule-runtime/4.4/migration-patterns-watermark): Watermarks have been simplified. You can also do it manually now allowing for more complex use cases. - [Accessing the Mule Message](https://docs.mulesoft.com/mule-runtime/4.4/migration-message-properties): The Mule Message has a new structure and it’s accessed differently. Here’s a quick overview. - Using Java: Interoperability with Java is now done through the [Java module](https://docs.mulesoft.com/java-module/latest/). Optionally you can also try the [Scripting module](https://docs.mulesoft.com/mule-runtime/4.4/migration-module-scripting) or the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/) - [Using Spring](https://docs.mulesoft.com/mule-runtime/4.4/migration-module-spring): Instead of defining Spring beans directly in your application, you can now use the [Spring Module](https://docs.mulesoft.com/spring-module/latest/). - [Using reconnection strategies](https://docs.mulesoft.com/mule-runtime/4.4/migration-patterns-reconnection-strategies): There are some small but important differences around reconnection in Mule 4. - [Classloading isolation](https://docs.mulesoft.com/mule-runtime/4.4/about-classloading-isolation): Classloading isolation changes the way resources and classes are shared. Read this article to learn more. - [Core Components Migration](https://docs.mulesoft.com/mule-runtime/4.4/migration-core): A comprehensive list of the changes that were made to the core language elements - [Using the new connectors](https://docs.mulesoft.com/mule-runtime/4.4/migration-connectors): A comprehensive list of the changes that were made to the main connectors. - [Using the Security Module (AES)](https://docs.mulesoft.com/mule-runtime/4.4/migration-aes): Anypoint Enterprise Security module was split into different modules explained here. - [Migrating Gateways](https://docs.mulesoft.com/mule-runtime/4.4/migration-api-gateways): This section covers the migration of API Gateway related features. - [Migrating ApiKit apps](https://docs.mulesoft.com/mule-runtime/4.4/migration-example-complex): Covers the necessary steps to successfully migrate APIkit-based applications. - Migrating custom components: You can use the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/) to create your own reusable components - [Transport service overrides](https://docs.mulesoft.com/mule-runtime/4.4/migration-transports): Covers how to migrate from generic transports. - [on-premises::mule-high-availability-ha-clusters.adoc#configure-the-performance-profile](https://docs.mulesoft.com/on-premises/latest/mule-high-availability-ha-clusters#configure-the-performance-profile): At a container level, change the property from `mule.clusterPartitioningMode=OPTIMIZE_PERFORMANCE` to `mule.cluster.storeprofile=performance`. At an individual application level, you can configure the store profile for a specific Mule application. --- product: Mule Runtime version: 4.3 --- # Mule 4 for Mule 3 Users > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 4 improvements make it easier to learn, develop, and manage than Mule 3. Benefits include: - Easier and faster app development - Seamless access and data mapping - Simplified connectivity - Auto-tuned and highly performant runtime - Seamless upgrades of Mule runtime engine and connector versions - Up to 50% fewer steps and concepts to learn than Mule 3 If you are currently running Mule 3 applications, read this documentation to get an overview of the Mule 4 capabilities and to learn the differences between Mule 3 and Mule 4, to know when to migrate to Mule 4, and to understand what is required to migrate apps to Mule 4. To understand the options for migrating your apps from Mule 3 to Mule 4, review [Migration to Mule 4](https://docs.mulesoft.com/mule-runtime/4.3/migration-intro). --- product: Mule Runtime version: 4.4 --- # Mule 4 for Mule 3 Users > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 4 improvements make it easier to learn, develop, and manage than Mule 3. Benefits include: - Easier and faster app development - Seamless access and data mapping - Simplified connectivity - Auto-tuned and highly performant runtime - Seamless upgrades of Mule runtime engine and connector versions - Up to 50% fewer steps and concepts to learn than Mule 3 If you are currently running Mule 3 applications, read this documentation to get an overview of the Mule 4 capabilities and to learn the differences between Mule 3 and Mule 4, to know when to migrate to Mule 4, and to understand what is required to migrate apps to Mule 4. To understand the options for migrating your apps from Mule 3 to Mule 4, review [Migration to Mule 4](https://docs.mulesoft.com/mule-runtime/4.4/migration-intro). --- product: Mule Runtime version: 4.3 --- # Mule 4 Programming Model > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 4 changes the programming paradigm used in previous versions. In Mule 3, the main data component of the flow is the message. All transport provided by the runtime is mainly on the content of message payload. For instance, an `http:outbound-endpoint` is only able to send an HTTP body as the message’s payload content in Mule 3. This behavior led users to add other components before the endpoint simply to properly configure the payload with the proper content. Mule 3 ```xml ``` Mule 4 simplifies these use cases by allowing for the customization of all input parameters of the operations (`http:request`). Mule 4 ```xml ``` As the example above shows, you can now define the body to be sent by the `http:request` operation within the `body` parameter. This not only reduces the number of components that you need to add to your flow, but it also makes it more readable and prevents affecting the data context just for the purpose of the content required by the `http:request` operation. When creating a flow in a Mule app, you might need to store data in a variable so that any component in the flow can use it. Non-void operations (such as the Read operation to the File connector) can store the message data that they return in a variable. Once defined, variables created with the Target (`target`) parameter are available for use within the flow, and you can access them like you access any other variable. You often define variables through these parameters: - Target (`target`): Name of the variable in which to store message data. Names can only include numbers, characters, and underscores. For example, hyphens are not allowed in the name. - Target Value (`targetValue`): Value of the data to store in the target variable. By default, the value is the message payload (`payload`). The field accepts any value that a variable accepts: any supported data type, DataWeave expressions, the keywords `payload`, `attributes`, and `message`, but _not_ the keyword `vars`. It is important to understand that setting a target variable changes the typical course of the message through the flow. Normally, an operation outputs a different message than it receives as input. However, when you set a variable from an operation, the operation outputs to the _next_ component in the flow the same message that it received as input. For example, assume you have a flow consisting of component A, followed by component B with a target value of `myMessage`, and then component C. In this case, component C will receive the same message that B received from A. Here, a Read operation stores the payload of `readme.txt` in `myVar`: ```xml ``` Note that the target variable `myVar` stores the payload by default. You only need to specify a Target Value (`targetValue`) if you want to store something other than the full payload. Here, the entire message is stored in `myVar`: ```xml ``` This way the variable `myVar` will not only contain the content of the file but also all the related metadata. - Expression to access the file content: `#[myVar.payload]` - Expression to access the file metadata: `#[myVar.attributes]` Here, only the file size is stored in `myVar`: ```xml ``` The scenarios describe some cases where you might use target variables. ## Scenario: Setting a Target Variable from within an Operation Assume that you want to log the entire message (payload and attributes) returned by a Database connector operation, such as Insert. Instead of using a Set Variable component after the operation, you can instead capture the message data by adding a target variable directly to the operation: ```xml INSERT INTO PLANET(POSITION, NAME, DESCRIPTION) VALUES (777, 'Pluto', :description) #[{{'description' : payload}}] ``` - Target Variable for the Insert operation: `result` - Target Value: `message` in Design Center, `#[message]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `Payload is: #[vars.result.payload] and attributes are: #[vars.result.attributes]` Assume that you want to log the name of the first entry in a PLANET database. You can define a target variable like this one through the Select operation of the Database connector: ```xml select * from PLANET order by ID ``` - Target Variable for the Select operation: `planetName` - Target Value: `payload[0].name` in Design Center, `#[payload[0].name]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `'Planet name is: ' ++ vars.planetName` ## Scenario: Using the Stored Value as Input to an Operation Assume that you want to access all planets discovered after a given planet was discovered. You might create a target variable called `discoveryDate` within a select operation to capture the a planet’s discovery date. ```xml select discoveryDate from PLANET where name = :name #[{'name' : 'pluto'}] ``` - Target Variable for the Retrieve operation: `discoveryDate` Then you can use the Input Parameter of another operation in your flow (such as the Select operation to the Database connector) to make the variable available for use in your query, for example: ```xml select * from PLANET where discoveryDate > :discoveryDate #[{'discoveryDate' : vars.discoveryDate}] ``` - Input Parameter definition for the Select operation: - Key: `discoveryDate` - Value: `vars.discoveryDate` in Design Center, `#[vars.discoveryDate]` in Anypoint Studio. ## Scenario: Bypassing the Normal Message Flow Assume that you want to insert a number of records into a database that are located in the messages’s payload, then pass those same records on for further processing by the next component in your flow. Though you want to use the Bulk Insert operation to the Database connector to insert the records, the operation returns a success message which would replace the current payload thus making the records inaccessible. So, to pass on the records to the next component instead of replacing the payload with the bulk insert result, you can store the success message in a target variable, for example: - Target Variable: `bulkInsertResult` Then the next operation in your flow can process the records located in the payload. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-event) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-variables) --- product: Mule Runtime version: 4.4 --- # Mule 4 Programming Model > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule 4 changes the programming paradigm used in previous versions. In Mule 3, the main data component of the flow is the message. All transport provided by the runtime is mainly on the content of message payload. For instance, an `http:outbound-endpoint` is only able to send an HTTP body as the message’s payload content in Mule 3. This behavior led users to add other components before the endpoint simply to properly configure the payload with the proper content. Mule 3 ```xml ``` Mule 4 simplifies these use cases by allowing for the customization of all input parameters of the operations (`http:request`). Mule 4 ```xml ``` As the example above shows, you can now define the body to be sent by the `http:request` operation within the `body` parameter. This not only reduces the number of components that you need to add to your flow, but it also makes it more readable and prevents affecting the data context just for the purpose of the content required by the `http:request` operation. When creating a flow in a Mule app, you might need to store data in a variable so that any component in the flow can use it. Non-void operations (such as the Read operation to the File connector) can store the message data that they return in a variable. Once defined, variables created with the Target (`target`) parameter are available for use within the flow, and you can access them like you access any other variable. You often define variables through these parameters: - Target (`target`): Name of the variable in which to store message data. Names can only include numbers, characters, and underscores. For example, hyphens are not allowed in the name. - Target Value (`targetValue`): Value of the data to store in the target variable. By default, the value is the message payload (`payload`). The field accepts any value that a variable accepts: any supported data type, DataWeave expressions, the keywords `payload`, `attributes`, and `message`, but _not_ the keyword `vars`. It is important to understand that setting a target variable changes the typical course of the message through the flow. Normally, an operation outputs a different message than it receives as input. However, when you set a variable from an operation, the operation outputs to the _next_ component in the flow the same message that it received as input. For example, assume you have a flow consisting of component A, followed by component B with a target value of `myMessage`, and then component C. In this case, component C will receive the same message that B received from A. Here, a Read operation stores the payload of `readme.txt` in `myVar`: ```xml ``` Note that the target variable `myVar` stores the payload by default. You only need to specify a Target Value (`targetValue`) if you want to store something other than the full payload. Here, the entire message is stored in `myVar`: ```xml ``` This way the variable `myVar` will not only contain the content of the file but also all the related metadata. - Expression to access the file content: `#[myVar.payload]` - Expression to access the file metadata: `#[myVar.attributes]` Here, only the file size is stored in `myVar`: ```xml ``` The scenarios describe some cases where you might use target variables. ## Scenario: Setting a Target Variable from within an Operation Assume that you want to log the entire message (payload and attributes) returned by a Database connector operation, such as Insert. Instead of using a Set Variable component after the operation, you can instead capture the message data by adding a target variable directly to the operation: ```xml INSERT INTO PLANET(POSITION, NAME, DESCRIPTION) VALUES (777, 'Pluto', :description) #[{{'description' : payload}}] ``` - Target Variable for the Insert operation: `result` - Target Value: `message` in Design Center, `#[message]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `Payload is: #[vars.result.payload] and attributes are: #[vars.result.attributes]` Assume that you want to log the name of the first entry in a PLANET database. You can define a target variable like this one through the Select operation of the Database connector: ```xml select * from PLANET order by ID ``` - Target Variable for the Select operation: `planetName` - Target Value: `payload[0].name` in Design Center, `#[payload[0].name]` in Anypoint Studio. Then you might retrieve the result from the Logger like this: ```xml ``` - Message: `'Planet name is: ' ++ vars.planetName` ## Scenario: Using the Stored Value as Input to an Operation Assume that you want to access all planets discovered after a given planet was discovered. You might create a target variable called `discoveryDate` within a select operation to capture the a planet’s discovery date. ```xml select discoveryDate from PLANET where name = :name #[{'name' : 'pluto'}] ``` - Target Variable for the Retrieve operation: `discoveryDate` Then you can use the Input Parameter of another operation in your flow (such as the Select operation to the Database connector) to make the variable available for use in your query, for example: ```xml select * from PLANET where discoveryDate > :discoveryDate #[{'discoveryDate' : vars.discoveryDate}] ``` - Input Parameter definition for the Select operation: - Key: `discoveryDate` - Value: `vars.discoveryDate` in Design Center, `#[vars.discoveryDate]` in Anypoint Studio. ## Scenario: Bypassing the Normal Message Flow Assume that you want to insert a number of records into a database that are located in the messages’s payload, then pass those same records on for further processing by the next component in your flow. Though you want to use the Bulk Insert operation to the Database connector to insert the records, the operation returns a success message which would replace the current payload thus making the records inaccessible. So, to pass on the records to the next component instead of replacing the payload with the bulk insert result, you can store the success message in a target variable, for example: - Target Variable: `bulkInsertResult` Then the next operation in your flow can process the records located in the payload. ## See Also - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-event) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-variables) --- product: Mule Runtime version: 4.3 --- # Mule Application Development > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You create Mule applications to perform system integrations. Typically, the application reads data from internal and external sources, processes and transforms data to the required formats or structures, and writes that output to the systems and servers where you store or use the transformed data. Mule applications are configured to run in Mule runtime engine (Mule). A request to a Mule application triggers Mule to encode the request and data in a Mule event and to pass it to either single or multiple threads. ## Getting Started with Mule Application Development To get started with Mule application development, you can follow the steps in these tutorials: - [Create a "Hello World" Mule app](https://docs.mulesoft.com/mule-runtime/4.3/mule-app-dev-hellomule) Build a Mule application that interacts with a user in a simple HTTP request-response flow. - [Create a Mule app that uses the Database Connector and DataWeave](https://docs.mulesoft.com/mule-runtime/4.3/mule-app-tutorial) Build a Mule application that retrieves data from a database and transforms the to a new structure. ## Building Blocks of a Mule Application Mule applications use connectors, modules, and components to read, write, and process data. - [Connectors and Modules](https://docs.mulesoft.com/connectors/) Anypoint connectors provide components, such as listeners, that interact with external API endpoints and act on data in the Mule application. Modules, such as the Validation, Java, Spring, and OAuth, provide modules that act on data in a Mule application without providing a direct connection to an endpoint. - [Core Components](https://docs.mulesoft.com/mule-runtime/4.3/about-components) Core components support flow control, error handling, logging, batch, and other programmatic operations on data that flows through your application. ## DataWeave Language DataWeave is the primary language used for formulating expressions in Mule. Connectors, modules, and components support the use of DataWeave to access, manipulate, and transform data structures and output formats, and to extract data that is processed within the Mule application. At runtime, Mule evaluates DataWeave expressions while executing a flow to: - Extract data needed to process the current message - Set or manipulate a value in the message ## Mule Flows Understanding basic flow architecture is key to understanding a Mule application. Essentially, every Mule flow contains a series of Mule components that receive or process messages: ![Simple Flow in Design Center](/mulesoft/current/en-us/mule-runtime/4.3/_images/flow-example.png) Figure 1. Simple Flow in Design Center At the simplest level, flows are sequences of processors. A message that enters a flow can pass through a variety of processors. In a typical flow, a Mule application receives a message through a source (such as an HTTP Listener component), transforms that message into a new format, and processes any business logic before writing the processed message to an external system in a format that the system can read. To separate processing into more manageable units, Mule applications often contain multiple, interrelated flows instead of just a single flow. One flow can call another flow as a direct reference. For more information about this topic, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.3/about-flows) and [Mule Components](https://docs.mulesoft.com/mule-runtime/4.3/mule-components). ### Sources A source component (or trigger) is the first component in a flow. It receives a triggering event, creates a corresponding Mule event, and forwards that event for processing by the next component in the flow. External clients can trigger processing in a Mule flow through several communication protocols and methods, such as JMS, HTTP, FTP, JDBC, or File. Mule translates these communication protocols and methods into a standard message format, which passes through the flow’s processors. Sources in Mule can connect to specific external sources, either through a standard protocol or a third-party API. It is also possible to set a Scheduler component. Some schedulers can poll for specific changes to external resources, such as new files or table rows in an external resource. Examples of listeners and connector operations that can trigger a flow include: - HTTP, JMS, and VM listeners in their associated connectors - On Table Row operation in the Database connector - On New or Updated File operation in the File and FTP connectors - Scheduler Note that you can also create your own source using the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ### Processors After a flow is triggered through the source component, subsequent components process the data as it travels through the flow. By default, each processor that receives a Mule event returns a new Mule message, typically with a set of attributes and the message payload that the processor returns. The processor forwards the new message as output to the next processor in the flow. Processors available to Mule applications include: - Components from modules and connectors Examples include operations that read from and write to an external resource and that validate data in the Mule application. Some operations can make client requests to external resources and services (including external databases and systems, such as Salesforce, Workday, ServiceNow, and many others) and to other Mule applications. Others can run your custom code, support OAuth configurations, and manage communication through asynchronous queues, for example. Many other operations are available. - Core components Core components can route data, perform data transformations, handle errors that might occur when processing the event, and perform other tasks in a Mule application. Transformers (such as the Transform Message, Set Variable, and others) are key to exchanging data between nodes. Transformers enable Mule to convert message data in the Mule event to a format that another application or service can read. Mule also enables content enrichment of messages (through [Target Variables](https://docs.mulesoft.com/mule-runtime/4.3/target-variables)) so that you can retrieve additional data and attach it to the message. Note that you can also create your own event processors using the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## Security You can provide security to your Mule applications by encrypting properties, configuring secure communications over TLS, setting up authentication over OAuth 2.0, and providing cryptographic and other capabilities, such as FIPS compliance. - [Security](https://docs.mulesoft.com/mule-runtime/4.3/securing) ## Development Environments You can develop a Mule application using [Anypoint Studio](https://docs.mulesoft.com/studio/) (an Eclipse-based IDE), or, if you are an advanced developer, in your own IDE. For example, in Studio, you build and design a Mule application in a project that contains one or more XML-based files. A Mule project supports all the dependencies required for development. The [Package Explorer](https://docs.mulesoft.com/studio/#package-explorer) view in Studio provides access to the project folders and files that make up a Mule project. Studio provides a design-time environment in which you can also build, run, and test your Mule application. ## Mule Versioning The Mule version you use determines what your Mule application, domain, or policy can do and what features and products are compatible with Mule. For example, [Core components](https://docs.mulesoft.com/mule-runtime/4.3/about-components), which process the Mule event as it travels through flows in a Mule application, are part of a Core module that is bundled with and shares the same version as Mule. [Modules, connectors](https://docs.mulesoft.com/connectors/), the DataWeave language, and several MuleSoft products have their own versioning system but are compatible with specific versions of Mule. For example, DataWeave 2.0 and Studio 7.x are compatible Mule 4.x runtime engines, while DataWeave 1.0 and Studio 6.x are compatible with Mule 3.x runtime engines. You need to make sure the connector or module you use in a Mule application is compatible with your Mule version. ## See Also - [Mule Message](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-message) - [Variables in Mule Applications](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-variables) - [Mule Configuration](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-configuration) - [APIKit](https://docs.mulesoft.com/apikit/latest/) --- product: Mule Runtime version: 4.4 --- # Mule Application Development > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You create Mule applications to perform system integrations. Typically, the application reads data from internal and external sources, processes and transforms data to the required formats or structures, and writes that output to the systems and servers where you store or use the transformed data. Mule applications are configured to run in Mule runtime engine (Mule). A request to a Mule application triggers Mule to encode the request and data in a Mule event and to pass it to either single or multiple threads. ## Getting Started with Mule Application Development To get started with Mule application development, you can follow the steps in these tutorials: - [Create a "Hello World" Mule app](https://docs.mulesoft.com/mule-runtime/4.4/mule-app-dev-hellomule) Build a Mule application that interacts with a user in a simple HTTP request-response flow. - [Create a Mule app that uses the Database Connector and DataWeave](https://docs.mulesoft.com/mule-runtime/4.4/mule-app-tutorial) Build a Mule application that retrieves data from a database and transforms it to a new structure. ## Building Blocks of a Mule Application Mule applications use connectors, modules, and components to read, write, and process data. - [Connectors and Modules](https://docs.mulesoft.com/connectors/) Anypoint connectors provide components, such as listeners, that interact with external API endpoints and act on data in the Mule application. Modules, such as the Validation, Java, Spring, and OAuth, provide modules that act on data in a Mule application without providing a direct connection to an endpoint. - [Core Components](https://docs.mulesoft.com/mule-runtime/4.4/about-components) Core components support flow control, error handling, logging, batch, and other programmatic operations on data that flows through your application. ## DataWeave Language DataWeave is the primary language used for formulating expressions in Mule. Connectors, modules, and components support the use of DataWeave to access, manipulate, and transform data structures and output formats, and to extract data that is processed within the Mule application. At runtime, Mule evaluates DataWeave expressions while executing a flow to: - Extract data needed to process the current message - Set or manipulate a value in the message ## Mule Flows Understanding basic flow architecture is key to understanding a Mule application. Essentially, every Mule flow contains a series of Mule components that receive or process messages: ![Simple Flow in Design Center](/mulesoft/current/en-us/mule-runtime/4.4/_images/flow-example.png) Figure 1. Simple Flow in Design Center At the simplest level, flows are sequences of processors. A message that enters a flow can pass through a variety of processors. In a typical flow, a Mule application receives a message through a source (such as an HTTP Listener component), transforms that message into a new format, and processes any business logic before writing the processed message to an external system in a format that the system can read. To separate processing into more manageable units, Mule applications often contain multiple, interrelated flows instead of just a single flow. One flow can call another flow as a direct reference. For more information about this topic, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.4/about-flows) and [Mule Components](https://docs.mulesoft.com/mule-runtime/4.4/mule-components). ### Sources A source component (or trigger) is the first component in a flow. It receives a triggering event, creates a corresponding Mule event, and forwards that event for processing by the next component in the flow. External clients can trigger processing in a Mule flow through several communication protocols and methods, such as JMS, HTTP, FTP, JDBC, or File. Mule translates these communication protocols and methods into a standard message format, which passes through the flow’s processors. Sources in Mule can connect to specific external sources, either through a standard protocol or a third-party API. It is also possible to set a Scheduler component. Some schedulers can poll for specific changes to external resources, such as new files or table rows in an external resource. Examples of listeners and connector operations that can trigger a flow include: - HTTP, JMS, and VM listeners in their associated connectors - On Table Row operation in the Database connector - On New or Updated File operation in the File and FTP connectors - Scheduler Note that you can also create your own source using the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ### Processors After a flow is triggered through the source component, subsequent components process the data as it travels through the flow. By default, each processor that receives a Mule event returns a new Mule message, typically with a set of attributes and the message payload that the processor returns. The processor forwards the new message as output to the next processor in the flow. Processors available to Mule applications include: - Components from modules and connectors Examples include operations that read from and write to an external resource and that validate data in the Mule application. Some operations can make client requests to external resources and services (including external databases and systems, such as Salesforce, Workday, ServiceNow, and many others) and to other Mule applications. Others can run your custom code, support OAuth configurations, and manage communication through asynchronous queues, for example. Many other operations are available. - Core components Core components can route data, perform data transformations, handle errors that might occur when processing the event, and perform other tasks in a Mule application. Transformers (such as the Transform Message, Set Variable, and others) are key to exchanging data between nodes. Transformers enable Mule to convert message data in the Mule event to a format that another application or service can read. Mule also enables content enrichment of messages (through [Target Variables](https://docs.mulesoft.com/mule-runtime/4.4/target-variables)) so that you can retrieve additional data and attach it to the message. Note that you can also create your own event processors using the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## Security You can provide security to your Mule applications by encrypting properties, configuring secure communications over TLS, setting up authentication over OAuth 2.0, and providing cryptographic and other capabilities, such as FIPS compliance. - [Security](https://docs.mulesoft.com/mule-runtime/4.4/securing) ## Development Environments You can develop a Mule application using [Anypoint Studio](https://docs.mulesoft.com/studio/) (an Eclipse-based IDE), or, if you are an advanced developer, in your own IDE. For example, in Studio, you build and design a Mule application in a project that contains one or more XML-based files. A Mule project supports all the dependencies required for development. The [Package Explorer](https://docs.mulesoft.com/studio/#package-explorer) view in Studio provides access to the project folders and files that make up a Mule project. Studio provides a design-time environment in which you can also build, run, and test your Mule application. ## Mule Versioning The Mule version you use determines what your Mule application, domain, or policy can do and what features and products are compatible with Mule. For example, [Core components](https://docs.mulesoft.com/mule-runtime/4.4/about-components), which process the Mule event as it travels through flows in a Mule application, are part of a Core module that is bundled with and shares the same version as Mule. [Modules, connectors](https://docs.mulesoft.com/connectors/), the DataWeave language, and several MuleSoft products have their own versioning system but are compatible with specific versions of Mule. For example, DataWeave 2.0 and Studio 7.x are compatible Mule 4.x runtime engines, while DataWeave 1.0 and Studio 6.x are compatible with Mule 3.x runtime engines. You need to make sure the connector or module you use in a Mule application is compatible with your Mule version. ## See Also - [Mule Message](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-message) - [Variables in Mule Applications](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-variables) - [Mule Configuration](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-configuration) - [APIKit](https://docs.mulesoft.com/apikit/latest/) --- product: Mule Runtime version: 4.6 --- # Mule Application Development > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You create Mule applications to perform system integrations. Typically, the application reads data from internal and external sources, processes and transforms data to the required formats or structures, and writes that output to the systems and servers where you store or use the transformed data. Mule applications are configured to run in Mule runtime engine (Mule). A request to a Mule application triggers Mule to encode the request and data in a Mule event and to pass it to either single or multiple threads. ## Getting Started with Mule Application Development To get started with Mule application development, you can follow the steps in these tutorials: - [Create a "Hello World" Mule app](https://docs.mulesoft.com/mule-runtime/4.6/mule-app-dev-hellomule) Build a Mule application that interacts with a user in a simple HTTP request-response flow. - [Create a Mule app that uses the Database Connector and DataWeave](https://docs.mulesoft.com/mule-runtime/4.6/mule-app-tutorial) Build a Mule application that retrieves data from a database and transforms it to a new structure. ## Building Blocks of a Mule Application Mule applications use connectors, modules, and components to read, write, and process data. - [Connectors and Modules](https://docs.mulesoft.com/connectors/) Anypoint connectors provide components, such as listeners, that interact with external API endpoints and act on data in the Mule application. Modules, such as the Validation, Java, Spring, and OAuth, provide modules that act on data in a Mule application without providing a direct connection to an endpoint. - [Core Components](https://docs.mulesoft.com/mule-runtime/4.6/about-components) Core components support flow control, error handling, logging, batch, and other programmatic operations on data that flows through your application. ## DataWeave Language DataWeave is the primary language used for formulating expressions in Mule. Connectors, modules, and components support the use of DataWeave to access, manipulate, and transform data structures and output formats, and to extract data that is processed within the Mule application. At runtime, Mule evaluates DataWeave expressions while executing a flow to: - Extract data needed to process the current message - Set or manipulate a value in the message ## Mule Flows Understanding basic flow architecture is key to understanding a Mule application. Essentially, every Mule flow contains a series of Mule components that receive or process messages: ![Simple Flow in Design Center](/mulesoft/current/en-us/mule-runtime/4.6/_images/flow-example.png) Figure 1. Simple Flow in Design Center At the simplest level, flows are sequences of processors. A message that enters a flow can pass through a variety of processors. In a typical flow, a Mule application receives a message through a source (such as an HTTP Listener component), transforms that message into a new format, and processes any business logic before writing the processed message to an external system in a format that the system can read. To separate processing into more manageable units, Mule applications often contain multiple, interrelated flows instead of just a single flow. One flow can call another flow as a direct reference. For more information about this topic, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.6/about-flows) and [Mule Components](https://docs.mulesoft.com/mule-runtime/4.6/mule-components). ### Sources A source component (or trigger) is the first component in a flow. It receives a triggering event, creates a corresponding Mule event, and forwards that event for processing by the next component in the flow. External clients can trigger processing in a Mule flow through several communication protocols and methods, such as JMS, HTTP, FTP, JDBC, or File. Mule translates these communication protocols and methods into a standard message format, which passes through the flow’s processors. Sources in Mule can connect to specific external sources, either through a standard protocol or a third-party API. It is also possible to set a Scheduler component. Some schedulers can poll for specific changes to external resources, such as new files or table rows in an external resource. Examples of listeners and connector operations that can trigger a flow include: - HTTP, JMS, and VM listeners in their associated connectors - On Table Row operation in the Database connector - On New or Updated File operation in the File and FTP connectors - Scheduler Note that you can also create your own source using the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ### Processors After a flow is triggered through the source component, subsequent components process the data as it travels through the flow. By default, each processor that receives a Mule event returns a new Mule message, typically with a set of attributes and the message payload that the processor returns. The processor forwards the new message as output to the next processor in the flow. Processors available to Mule applications include: - Components from modules and connectors Examples include operations that read from and write to an external resource and that validate data in the Mule application. Some operations can make client requests to external resources and services (including external databases and systems, such as Salesforce, Workday, ServiceNow, and many others) and to other Mule applications. Others can run your custom code, support OAuth configurations, and manage communication through asynchronous queues, for example. Many other operations are available. - Core components Core components can route data, perform data transformations, handle errors that might occur when processing the event, and perform other tasks in a Mule application. Transformers (such as the Transform Message, Set Variable, and others) are key to exchanging data between nodes. Transformers enable Mule to convert message data in the Mule event to a format that another application or service can read. Mule also enables content enrichment of messages (through [Target Variables](https://docs.mulesoft.com/mule-runtime/4.6/target-variables)) so that you can retrieve additional data and attach it to the message. Note that you can also create your own event processors using the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## Security You can provide security to your Mule applications by encrypting properties, configuring secure communications over TLS, setting up authentication over OAuth 2.0, and providing cryptographic and other capabilities, such as FIPS compliance. - [Security](https://docs.mulesoft.com/mule-runtime/4.6/securing) ## Development Environments You can develop a Mule application using [Anypoint Studio](https://docs.mulesoft.com/studio/) (an Eclipse-based IDE), or, if you are an advanced developer, in your own IDE. For example, in Studio, you build and design a Mule application in a project that contains one or more XML-based files. A Mule project supports all the dependencies required for development. The [Package Explorer](https://docs.mulesoft.com/studio/#package-explorer) view in Studio provides access to the project folders and files that make up a Mule project. Studio provides a design-time environment in which you can also build, run, and test your Mule application. ## Mule Versioning The Mule version you use determines what your Mule application, domain, or policy can do and what features and products are compatible with Mule. For example, [Core components](https://docs.mulesoft.com/mule-runtime/4.6/about-components), which process the Mule event as it travels through flows in a Mule application, are part of a Core module that is bundled with and shares the same version as Mule. [Modules, connectors](https://docs.mulesoft.com/connectors/), the DataWeave language, and several MuleSoft products have their own versioning system but are compatible with specific versions of Mule. For example, DataWeave 2.0 and Studio 7.x are compatible with Mule 4.x runtime engines. Make sure the connector or module you use in a Mule application is compatible with your Mule version. ## See Also - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-message) - [Variables in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-variables) - [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-configuration) - [APIkit Overview](https://docs.mulesoft.com/apikit/latest/) --- product: Mule Runtime version: 4.9 --- # Mule Application Development > For the full documentation index, see: https://docs.mulesoft.com/llms.txt You create Mule applications to perform system integrations. Typically, the application reads data from internal and external sources, processes and transforms data to the required formats or structures, and writes that output to the systems and servers where you store or use the transformed data. Mule applications are configured to run in Mule runtime engine (Mule). A request to a Mule application triggers Mule to encode the request and data in a Mule event and to pass it to either single or multiple threads. ## Getting Started with Mule Application Development To get started with Mule application development, you can follow the steps in these tutorials: - [Create a "Hello World" Mule app](https://docs.mulesoft.com/mule-runtime/4.9/mule-app-dev-hellomule) Build a Mule application that interacts with a user in a simple HTTP request-response flow. - [Create a Mule app that uses the Database Connector and DataWeave](https://docs.mulesoft.com/mule-runtime/4.9/mule-app-tutorial) Build a Mule application that retrieves data from a database and transforms it to a new structure. ## Building Blocks of a Mule Application Mule applications use connectors, modules, and components to read, write, and process data. - [Connectors and Modules](https://docs.mulesoft.com/connectors/) Anypoint connectors provide components, such as listeners, that interact with external API endpoints and act on data in the Mule application. Modules, such as the Validation, Java, Spring, and OAuth, provide modules that act on data in a Mule application without providing a direct connection to an endpoint. - [Core Components](https://docs.mulesoft.com/mule-runtime/4.9/about-components) Core components support flow control, error handling, logging, batch, and other programmatic operations on data that flows through your application. ## DataWeave Language DataWeave is the primary language used for formulating expressions in Mule. Connectors, modules, and components support the use of DataWeave to access, manipulate, and transform data structures and output formats, and to extract data that is processed within the Mule application. At runtime, Mule evaluates DataWeave expressions while executing a flow to: - Extract data needed to process the current message - Set or manipulate a value in the message ## Mule Flows Understanding basic flow architecture is key to understanding a Mule application. Essentially, every Mule flow contains a series of Mule components that receive or process messages: ![A flow including an HTTP Listener, data transformation, database connection, and logging process](/mulesoft/current/en-us/mule-runtime/4.9/_images/flow-example.png) Figure 1. Simple Flow in Design Center At the simplest level, flows are sequences of processors. A message that enters a flow can pass through a variety of processors. In a typical flow, a Mule application receives a message through a source (such as an HTTP Listener component), transforms that message into a new format, and processes any business logic before writing the processed message to an external system in a format that the system can read. To separate processing into more manageable units, Mule applications often contain multiple, interrelated flows instead of just a single flow. One flow can call another flow as a direct reference. For more information about this topic, see [Flows and Subflows](https://docs.mulesoft.com/mule-runtime/4.9/about-flows) and [Mule Components](https://docs.mulesoft.com/mule-runtime/4.9/mule-components). ### Sources A source component (or trigger) is the first component in a flow. It receives a triggering event, creates a corresponding Mule event, and forwards that event for processing by the next component in the flow. External clients can trigger processing in a Mule flow through several communication protocols and methods, such as JMS, HTTP, FTP, JDBC, or File. Mule translates these communication protocols and methods into a standard message format, which passes through the flow’s processors. Sources in Mule can connect to specific external sources, either through a standard protocol or a third-party API. It is also possible to set a Scheduler component. Some schedulers can poll for specific changes to external resources, such as new files or table rows in an external resource. Examples of listeners and connector operations that can trigger a flow include: - HTTP, JMS, and VM listeners in their associated connectors - On Table Row operation in the Database connector - On New or Updated File operation in the File and FTP connectors - Scheduler Note that you can also create your own source using the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ### Processors After a flow is triggered through the source component, subsequent components process the data as it travels through the flow. By default, each processor that receives a Mule event returns a new Mule message, typically with a set of attributes and the message payload that the processor returns. The processor forwards the new message as output to the next processor in the flow. Processors available to Mule applications include: - Components from modules and connectors Examples include operations that read from and write to an external resource and that validate data in the Mule application. Some operations can make client requests to external resources and services (including external databases and systems, such as Salesforce, Workday, ServiceNow, and many others) and to other Mule applications. Others can run your custom code, support OAuth configurations, and manage communication through asynchronous queues, for example. Many other operations are available. - Core components Core components can route data, perform data transformations, handle errors that might occur when processing the event, and perform other tasks in a Mule application. Transformers (such as the Transform Message, Set Variable, and others) are key to exchanging data between nodes. Transformers enable Mule to convert message data in the Mule event to a format that another application or service can read. Mule also enables content enrichment of messages (through [Target Variables](https://docs.mulesoft.com/mule-runtime/4.9/target-variables)) so that you can retrieve additional data and attach it to the message. Note that you can also create your own event processors using the [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## Security You can provide security to your Mule applications by encrypting properties, configuring secure communications over TLS, setting up authentication over OAuth 2.0, and providing cryptographic and other capabilities, such as FIPS compliance. - [Security](https://docs.mulesoft.com/mule-runtime/4.9/securing) ## Development Environments You can develop a Mule application using [Anypoint Studio](https://docs.mulesoft.com/studio/) (an Eclipse-based IDE), or, if you are an advanced developer, in your own IDE. For example, in Studio, you build and design a Mule application in a project that contains one or more XML-based files. A Mule project supports all the dependencies required for development. The [Package Explorer](https://docs.mulesoft.com/studio/#package-explorer) view in Studio provides access to the project folders and files that make up a Mule project. Studio provides a design-time environment in which you can also build, run, and test your Mule application. ## Mule Versioning The Mule version you use determines what your Mule application, domain, or policy can do and what features and products are compatible with Mule. For example, [Core components](https://docs.mulesoft.com/mule-runtime/4.9/about-components), which process the Mule event as it travels through flows in a Mule application, are part of a Core module that is bundled with and shares the same version as Mule. [Modules, connectors](https://docs.mulesoft.com/connectors/), the DataWeave language, and several MuleSoft products have their own versioning system but are compatible with specific versions of Mule. For example, DataWeave 2.0 and Studio 7.x are compatible with Mule 4.x runtime engines. Make sure the connector or module you use in a Mule application is compatible with your Mule version. ## See Also - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-message) - [Variables in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-variables) - [Mule Configuration File](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-configuration) - [APIkit Overview](https://docs.mulesoft.com/apikit/latest/) --- product: Mule Runtime version: 4.11 --- # Mule Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The main building blocks of Mule applications are components. Components execute business logic on the messages that flow through your Mule applications. There are a couple types of component: Core components and the components that belong to connectors and modules. ## Core Components These are individual components that are part of the core of the functionality of Mule Runtime. Here is a sampling of the features that core components let you add to your apps: - Asynchronous processing of parts of a flow or subflow - Batch processing of messages - Initiating subflows - Logging - Setting payloads - Transforming messages with the DataWeave language - Creating Try scopes in your flows so that you can catch and respond to errors For example, the Choice router is a component that dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. ![The Core components for Mule applications listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/about-mule-apps-core-components.png) Figure 1. A List of the Core Components in Anypoint Studio For component documentation, see [Core Components](https://docs.mulesoft.com/mule-runtime/4.11/about-components). ## Connectors Connectors group together components that were created to facilitate the integration of MuleSoft applications with any external resources, such as third-party APIs or standard integration protocols. They enable connectivity to SaaS and on-premises applications, systems, and services. For example, the Salesforce Connector provides components that let you use the Salesforce platform APIs to perform a large number of different operations. ![The Salesforce connector and its operations listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/about-mule-apps-salesforce-connector.png) Figure 2. The Salesforce connector and its operations listed in Anypoint Studio ## Modules Modules group together components that were created to add flexibility to your applications by allowing you to aggregate values compress data, use Java features, use extra features for processing JSON, and more. The features that modules offer are more at the level of traditional application coding. For example, the XML module provides components that can process and extract data from an XML document. ![The XML module and its components listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.11/_images/about-mule-apps-xml-module.png) Figure 3. The XML module and its components listed in Anypoint Studio ## See Also - [Connectors and Modules (for Mule 4)](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.12 --- # Mule Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The main building blocks of Mule applications are components. Components execute business logic on the messages that flow through your Mule applications. There are a couple types of component: Core components and the components that belong to connectors and modules. ## Core Components These are individual components that are part of the core of the functionality of Mule Runtime. Here is a sampling of the features that core components let you add to your apps: - Asynchronous processing of parts of a flow or subflow - Batch processing of messages - Initiating subflows - Logging - Setting payloads - Transforming messages with the DataWeave language - Creating Try scopes in your flows so that you can catch and respond to errors For example, the Choice router is a component that dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. ![The Core components for Mule applications listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/about-mule-apps-core-components.png) Figure 1. A List of the Core Components in Anypoint Studio For component documentation, see [Core Components](https://docs.mulesoft.com/mule-runtime/4.12/about-components). ## Connectors Connectors group together components that were created to facilitate the integration of MuleSoft applications with any external resources, such as third-party APIs or standard integration protocols. They enable connectivity to SaaS and on-premises applications, systems, and services. For example, the Salesforce Connector provides components that let you use the Salesforce platform APIs to perform a large number of different operations. ![The Salesforce connector and its operations listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/about-mule-apps-salesforce-connector.png) Figure 2. The Salesforce connector and its operations listed in Anypoint Studio ## Modules Modules group together components that were created to add flexibility to your applications by allowing you to aggregate values compress data, use Java features, use extra features for processing JSON, and more. The features that modules offer are more at the level of traditional application coding. For example, the XML module provides components that can process and extract data from an XML document. ![The XML module and its components listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.12/_images/about-mule-apps-xml-module.png) Figure 3. The XML module and its components listed in Anypoint Studio ## See Also - [Connectors and Modules (for Mule 4)](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.3 --- # Mule Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The main building blocks of Mule applications are components. Components execute business logic on the messages that flow through your Mule applications. There are a couple types of component: Core components and the components that belong to connectors and modules. ## Core Components These are individual components that are part of the core of the functionality of Mule Runtime. Here is a sampling of the features that core components let you add to your apps: - Asynchronous processing of parts of a flow or subflow - Batch processing of messages - Initiating subflows - Logging - Setting payloads - Transforming messages with the DataWeave language - Creating Try scopes in your flows so that you can catch and respond to errors For example, the Choice router is a component that dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. ![A list of the Core components in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.3/_images/about-mule-apps-core-components.png) Figure 1. A List of the Core Components in Anypoint Studio For component documentation, see [Core Components](https://docs.mulesoft.com/mule-runtime/4.3/about-components). ## Connectors Connectors group together components that were created to facilitate the integration of MuleSoft applications with any external resources, such as third-party APIs or standard integration protocols. They enable connectivity to SaaS and on-premises applications, systems, and services. For example, the Salesforce Connector provides components that let you use the Salesforce platform APIs to perform a large number of different operations. ![The Salesforce connector and its operations listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.3/_images/about-mule-apps-salesforce-connector.png) Figure 2. The Salesforce connector and its operations listed in Anypoint Studio ## Modules Modules group together components that were created to add flexibility to your applications by allowing you to aggregate values compress data, use Java features, use extra features for processing JSON, and more. The features that modules offer are more at the level of traditional application coding. For example, the XML module provides components that can process and extract data from an XML document. ![The XML module and its components, as listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.3/_images/about-mule-apps-xml-module.png) Figure 3. The XML module and its components listed in Anypoint Studio ## See Also - [Connectors and Modules (for Mule 4)](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.4 --- # Mule Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The main building blocks of Mule applications are components. Components execute business logic on the messages that flow through your Mule applications. There are a couple types of component: Core components and the components that belong to connectors and modules. ## Core Components These are individual components that are part of the core of the functionality of Mule Runtime. Here is a sampling of the features that core components let you add to your apps: - Asynchronous processing of parts of a flow or subflow - Batch processing of messages - Initiating subflows - Logging - Setting payloads - Transforming messages with the DataWeave language - Creating Try scopes in your flows so that you can catch and respond to errors For example, the Choice router is a component that dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. ![A list of the Core components in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.4/_images/about-mule-apps-core-components.png) Figure 1. A List of the Core Components in Anypoint Studio For component documentation, see [Core Components](https://docs.mulesoft.com/mule-runtime/4.4/about-components). ## Connectors Connectors group together components that were created to facilitate the integration of MuleSoft applications with any external resources, such as third-party APIs or standard integration protocols. They enable connectivity to SaaS and on-premises applications, systems, and services. For example, the Salesforce Connector provides components that let you use the Salesforce platform APIs to perform a large number of different operations. ![The Salesforce connector and its operations listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.4/_images/about-mule-apps-salesforce-connector.png) Figure 2. The Salesforce connector and its operations listed in Anypoint Studio ## Modules Modules group together components that were created to add flexibility to your applications by allowing you to aggregate values compress data, use Java features, use extra features for processing JSON, and more. The features that modules offer are more at the level of traditional application coding. For example, the XML module provides components that can process and extract data from an XML document. ![The XML module and its components, as listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.4/_images/about-mule-apps-xml-module.png) Figure 3. The XML module and its components listed in Anypoint Studio ## See Also - [Connectors and Modules (for Mule 4)](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.6 --- # Mule Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The main building blocks of Mule applications are components. Components execute business logic on the messages that flow through your Mule applications. There are a couple types of component: Core components and the components that belong to connectors and modules. ## Core Components These are individual components that are part of the core of the functionality of Mule Runtime. Here is a sampling of the features that core components let you add to your apps: - Asynchronous processing of parts of a flow or subflow - Batch processing of messages - Initiating subflows - Logging - Setting payloads - Transforming messages with the DataWeave language - Creating Try scopes in your flows so that you can catch and respond to errors For example, the Choice router is a component that dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. ![A list of the Core components in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.6/_images/about-mule-apps-core-components.png) Figure 1. A List of the Core Components in Anypoint Studio For component documentation, see [Core Components](https://docs.mulesoft.com/mule-runtime/4.6/about-components). ## Connectors Connectors group together components that were created to facilitate the integration of MuleSoft applications with any external resources, such as third-party APIs or standard integration protocols. They enable connectivity to SaaS and on-premises applications, systems, and services. For example, the Salesforce Connector provides components that let you use the Salesforce platform APIs to perform a large number of different operations. ![The Salesforce connector and its operations listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.6/_images/about-mule-apps-salesforce-connector.png) Figure 2. The Salesforce connector and its operations listed in Anypoint Studio ## Modules Modules group together components that were created to add flexibility to your applications by allowing you to aggregate values compress data, use Java features, use extra features for processing JSON, and more. The features that modules offer are more at the level of traditional application coding. For example, the XML module provides components that can process and extract data from an XML document. ![The XML module and its components, as listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.6/_images/about-mule-apps-xml-module.png) Figure 3. The XML module and its components listed in Anypoint Studio ## See Also - [Connectors and Modules (for Mule 4)](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.9 --- # Mule Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The main building blocks of Mule applications are components. Components execute business logic on the messages that flow through your Mule applications. There are a couple types of component: Core components and the components that belong to connectors and modules. ## Core Components These are individual components that are part of the core of the functionality of Mule Runtime. Here is a sampling of the features that core components let you add to your apps: - Asynchronous processing of parts of a flow or subflow - Batch processing of messages - Initiating subflows - Logging - Setting payloads - Transforming messages with the DataWeave language - Creating Try scopes in your flows so that you can catch and respond to errors For example, the Choice router is a component that dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. ![The Core components for Mule applications listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/about-mule-apps-core-components.png) Figure 1. A List of the Core Components in Anypoint Studio For component documentation, see [Core Components](https://docs.mulesoft.com/mule-runtime/4.9/about-components). ## Connectors Connectors group together components that were created to facilitate the integration of MuleSoft applications with any external resources, such as third-party APIs or standard integration protocols. They enable connectivity to SaaS and on-premises applications, systems, and services. For example, the Salesforce Connector provides components that let you use the Salesforce platform APIs to perform a large number of different operations. ![The Salesforce connector and its operations listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/about-mule-apps-salesforce-connector.png) Figure 2. The Salesforce connector and its operations listed in Anypoint Studio ## Modules Modules group together components that were created to add flexibility to your applications by allowing you to aggregate values compress data, use Java features, use extra features for processing JSON, and more. The features that modules offer are more at the level of traditional application coding. For example, the XML module provides components that can process and extract data from an XML document. ![The XML module and its components listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/4.9/_images/about-mule-apps-xml-module.png) Figure 3. The XML module and its components listed in Anypoint Studio ## See Also - [Connectors and Modules (for Mule 4)](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Mule Components > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The main building blocks of Mule applications are components. Components execute business logic on the messages that flow through your Mule applications. There are a couple types of component: Core components and the components that belong to connectors and modules. ## Core Components These are individual components that are part of the core of the functionality of Mule Runtime. Here is a sampling of the features that core components let you add to your apps: - Asynchronous processing of parts of a flow or subflow - Batch processing of messages - Initiating subflows - Logging - Setting payloads - Transforming messages with the DataWeave language - Creating Try scopes in your flows so that you can catch and respond to errors For example, the Choice router is a component that dynamically routes messages through a flow according to a set of DataWeave expressions that evaluate message content. Each expression is associated with a different routing option. The effect is to add conditional processing to a flow, similar to an `if`/`then`/`else` code block in most programming languages. ![The Core components for Mule applications listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/about-mule-apps-core-components.png) Figure 1. A List of the Core Components in Anypoint Studio For component documentation, see [Core Components](https://docs.mulesoft.com/mule-runtime/latest/about-components). ## Connectors Connectors group together components that were created to facilitate the integration of MuleSoft applications with any external resources, such as third-party APIs or standard integration protocols. They enable connectivity to SaaS and on-premises applications, systems, and services. For example, the Salesforce Connector provides components that let you use the Salesforce platform APIs to perform a large number of different operations. ![The Salesforce connector and its operations listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/about-mule-apps-salesforce-connector.png) Figure 2. The Salesforce connector and its operations listed in Anypoint Studio ## Modules Modules group together components that were created to add flexibility to your applications by allowing you to aggregate values compress data, use Java features, use extra features for processing JSON, and more. The features that modules offer are more at the level of traditional application coding. For example, the XML module provides components that can process and extract data from an XML document. ![The XML module and its components listed in Anypoint Studio](/mulesoft/current/en-us/mule-runtime/latest/_images/about-mule-apps-xml-module.png) Figure 3. The XML module and its components listed in Anypoint Studio ## See Also - [Connectors and Modules (for Mule 4)](https://docs.mulesoft.com/connectors/) --- product: Mule Runtime version: 4.11 keywords: configuration, deploy, mule --- # Mule Configuration File > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications, domains, and policies are configured through an XML domain-specific language (DSL). This XML file specifies the resources that compose the artifact, including dependencies needed to run the Mule application. Although you can write the XML file manually, it is more common to use the graphical user interfaces in Anypoint Design Center or Anypoint Studio to structure and define the behavior of your Mule app. While you use either of these GUIs, the underlying XML is provided for you. In Studio, the XML is also available for viewing and editing. ## Overview A Mule configuration file is a tree. Each of the elements sets up a configuration object within Mule, for example: - [Mule Global Configuration](https://docs.mulesoft.com/mule-runtime/4.11/global-settings-configuration) Global settings, such as the default transaction time-out, that apply to the entire Mule configuration. - [Properties](https://docs.mulesoft.com/mule-runtime/4.11/configuring-properties) Configuration Properties, message properties, and system properties. - [Flows](https://docs.mulesoft.com/mule-runtime/4.11/about-flows) Combine components to define a message flow. - [Sources (Endpoints)](https://docs.mulesoft.com/mule-runtime/4.11/about-components#_endpoints) Trigger a flow. Sources are sometimes called Endpoints in Studio. - [Connectors and Modules Configurations](https://docs.mulesoft.com/connectors/) Declare configurations for any connectors and modules components used. - [Routers](https://docs.mulesoft.com/mule-runtime/4.11/about-components#_flow_control_routers) Control the flow execution. - [Operations](https://docs.mulesoft.com/mule-sdk/latest/operations) Apply specific actions within a flow. ## XML Schema [Schemas](https://www.w3.org/TR/xmlschema-1/#xsi_schemaLocation) define the configurable attributes of these resources that are referenced in the XML Configuration file. This is how a Mule artifact both validate and define its functional components and their configuration. XML schemas are used to validate functional components in a Mule artifact. They are specified in the header. ```xml ``` > [!NOTE] Mule domains feature the `mule-domain` tag instead of `mule`. Be sure to specify all the necessary schema files. This can be time-consuming when setting up the configuration file by hand, but importing schema files provides the following time-saving benefits: - Auto-completion and context-specific help in Anypoint Studio - Design-time configuration validation - Typed properties Schemas in Mule 4 are autogenerated dynamically according to the artifact dependencies. The HTTP schema, for example, will only be available if the HTTP connector is part of the artifacts dependencies. Therefore, to specify the schemas you will also need to have the correct dependencies declared. In the example above which requires the JMS and File schemas you would need the following dependencies in the artifact’s `pom.xml` file, for example: ```xml ... org.mule.connectors mule-jms-connector 1.3.2 mule-plugin org.mule.connectors mule-file-connector 1.2.1 mule-plugin ... ``` > [!NOTE] Anypoint Studio will add the required schemas and dependencies as components are > introduced. ## Namespaces Each Mule module or connector has its XML schema, including Mule core for its community and enterprise versions. When you import a schema, it has its namespace. To use the standard Mule elements, import the Mule Kernel (CE) and Mule runtime engine (EE) namespaces: - `http://www.mulesoft.org/schema/mule/core` `http://www.mulesoft.org/schema/mule/core/current/mule.xsd` - `http://www.mulesoft.org/schema/mule/ee/core` `http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd` ### Default Namespace Typically, you set the Mule core schema as the default namespace for your configuration file. This means that any XML element without a prefix will come from the Mule core schema. To set the default namespace schema, specify `xmlns` immediately followed by the URL of the Mule schema, without the colon or namespace prefix you set in the previous example (e.g., `xmlns` instead of `xmlns:jms`): ```xml ...config... ``` ## Merging Configuration Files If you have multiple configuration files, you can import them into one configuration file so that you only have to specify one configuration. This is useful to extract connector configurations or other global elements. For example: ```xml ... ``` These imports can also be dynamic when combined with properties: ```xml (1) ... ```
1The env property in the example cannot be set by a global property. To define the env value, you can configure either a system property or an environment property.
Because of the hierarchy in which Mule runtime engine loads the properties, you cannot make imports depend on an application or a global configuration property. See the [properties hierarchy](https://docs.mulesoft.com/mule-runtime/4.11/configuring-properties#properties-hierarchy) page for more information. ## Declaring Multiple Configurations You can also keep your files separate as long as you declare them as part of your application configurations. This is useful when each configuration file is relatively unrelated to the others. Configurations are declared on the application descriptor file, `mule-artifact.json`, within the `configs` section. For example, four configuration files are declared here: ```json { "configs": [ "http-api.xml", "jms-messaging-api.xml", "monitoring-tools.xml", "core-functionality.xml" ], "redeploymentEnabled": true, "name": "retail-api", "minMuleVersion": "4.1.1", "requiredProduct": "MULE_EE", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [] } }, "bundleDescriptorLoader": { "id": "mule", "attributes": {} } } ``` > [!NOTE] Anypoint Studio will handle the application descriptor automatically. ## Full Application Example Following is an example of a simple Mule configuration file for an application: ```xml #[payload] ``` ## Full Policy Example ```xml ``` ## Full Domain Example ```xml ``` ## See Also - [Mule Domains](https://docs.mulesoft.com/mule-runtime/4.11/shared-resources) - [Mule Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started) - [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.11/configuring-properties) - [Packaging Applications](https://docs.mulesoft.com/mule-runtime/4.11/mule-app-dev) --- product: Mule Runtime version: 4.12 keywords: configuration, deploy, mule --- # Mule Configuration File > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications, domains, and policies are configured through an XML domain-specific language (DSL). This XML file specifies the resources that compose the artifact, including dependencies needed to run the Mule application. Although you can write the XML file manually, it is more common to use the graphical user interfaces in Anypoint Design Center or Anypoint Studio to structure and define the behavior of your Mule app. While you use either of these GUIs, the underlying XML is provided for you. In Studio, the XML is also available for viewing and editing. ## Overview A Mule configuration file is a tree. Each of the elements sets up a configuration object within Mule, for example: - [Mule Global Configuration](https://docs.mulesoft.com/mule-runtime/4.12/global-settings-configuration) Global settings, such as the default transaction time-out, that apply to the entire Mule configuration. - [Properties](https://docs.mulesoft.com/mule-runtime/4.12/configuring-properties) Configuration Properties, message properties, and system properties. - [Flows](https://docs.mulesoft.com/mule-runtime/4.12/about-flows) Combine components to define a message flow. - [Sources (Endpoints)](https://docs.mulesoft.com/mule-runtime/4.12/about-components#_endpoints) Trigger a flow. Sources are sometimes called Endpoints in Studio. - [Connectors and Modules Configurations](https://docs.mulesoft.com/connectors/) Declare configurations for any connectors and modules components used. - [Routers](https://docs.mulesoft.com/mule-runtime/4.12/about-components#_flow_control_routers) Control the flow execution. - [Operations](https://docs.mulesoft.com/mule-sdk/latest/operations) Apply specific actions within a flow. ## XML Schema [Schemas](https://www.w3.org/TR/xmlschema-1/#xsi_schemaLocation) define the configurable attributes of these resources that are referenced in the XML Configuration file. This is how a Mule artifact both validate and define its functional components and their configuration. XML schemas are used to validate functional components in a Mule artifact. They are specified in the header. ```xml ``` > [!NOTE] Mule domains feature the `mule-domain` tag instead of `mule`. Be sure to specify all the necessary schema files. This can be time-consuming when setting up the configuration file by hand, but importing schema files provides the following time-saving benefits: - Auto-completion and context-specific help in Anypoint Studio - Design-time configuration validation - Typed properties Schemas in Mule 4 are autogenerated dynamically according to the artifact dependencies. The HTTP schema, for example, will only be available if the HTTP connector is part of the artifacts dependencies. Therefore, to specify the schemas you will also need to have the correct dependencies declared. In the example above which requires the JMS and File schemas you would need the following dependencies in the artifact’s `pom.xml` file, for example: ```xml ... org.mule.connectors mule-jms-connector 1.3.2 mule-plugin org.mule.connectors mule-file-connector 1.2.1 mule-plugin ... ``` > [!NOTE] Anypoint Studio will add the required schemas and dependencies as components are > introduced. ## Namespaces Each Mule module or connector has its XML schema, including Mule core for its community and enterprise versions. When you import a schema, it has its namespace. To use the standard Mule elements, import the Mule Kernel (CE) and Mule runtime engine (EE) namespaces: - `http://www.mulesoft.org/schema/mule/core` `http://www.mulesoft.org/schema/mule/core/current/mule.xsd` - `http://www.mulesoft.org/schema/mule/ee/core` `http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd` ### Default Namespace Typically, you set the Mule core schema as the default namespace for your configuration file. This means that any XML element without a prefix will come from the Mule core schema. To set the default namespace schema, specify `xmlns` immediately followed by the URL of the Mule schema, without the colon or namespace prefix you set in the previous example (e.g., `xmlns` instead of `xmlns:jms`): ```xml ...config... ``` ## Merging Configuration Files If you have multiple configuration files, you can import them into one configuration file so that you only have to specify one configuration. This is useful to extract connector configurations or other global elements. For example: ```xml ... ``` These imports can also be dynamic when combined with properties: ```xml (1) ... ```
1The env property in the example cannot be set by a global property. To define the env value, you can configure either a system property or an environment property.
Because of the hierarchy in which Mule runtime engine loads the properties, you cannot make imports depend on an application or a global configuration property. See the [properties hierarchy](https://docs.mulesoft.com/mule-runtime/4.12/configuring-properties#properties-hierarchy) page for more information. ## Declaring Multiple Configurations You can also keep your files separate as long as you declare them as part of your application configurations. This is useful when each configuration file is relatively unrelated to the others. Configurations are declared on the application descriptor file, `mule-artifact.json`, within the `configs` section. For example, four configuration files are declared here: ```json { "configs": [ "http-api.xml", "jms-messaging-api.xml", "monitoring-tools.xml", "core-functionality.xml" ], "redeploymentEnabled": true, "name": "retail-api", "minMuleVersion": "4.9.0", "requiredProduct": "MULE_EE", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [] } }, "bundleDescriptorLoader": { "id": "mule", "attributes": {} } } ``` > [!NOTE] Anypoint Studio will handle the application descriptor automatically. > [!NOTE] For the meaning of each field in the preceding example, including `minMuleVersion`, see > [Application Descriptor Reference (mule-artifact.json)](https://docs.mulesoft.com/mule-runtime/4.12/mule-artifact-json). For how > `minMuleVersion` affects feature flags and compatibility checks, see > [Understanding minMuleVersion](https://docs.mulesoft.com/mule-runtime/4.12/feature-flagging#_understanding_minmuleversion). ## Full Application Example Following is an example of a simple Mule configuration file for an application: ```xml #[payload] ``` ## Full Policy Example ```xml ``` ## Full Domain Example ```xml ``` ## See Also - [Mule Domains](https://docs.mulesoft.com/mule-runtime/4.12/shared-resources) - [Mule Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started) - [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.12/configuring-properties) - [Packaging Applications](https://docs.mulesoft.com/mule-runtime/4.12/mule-app-dev) --- product: Mule Runtime version: 4.3 keywords: configuration, deploy, mule --- # Mule Configuration File > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications, domains, and policies are configured through an XML domain-specific language (DSL). This XML file specifies the resources that compose the artifact, including dependencies needed to run the Mule application. Although you can write the XML file manually, it is more common to use the graphical user interfaces in Anypoint Design Center or Anypoint Studio to structure and define the behavior of your Mule app. While you use either of these GUIs, the underlying XML is provided for you. In Studio, the XML is also available for viewing and editing. ## Overview A Mule configuration file is a tree. Each of the elements sets up a configuration object within Mule, for example: - [Mule Global Configuration](https://docs.mulesoft.com/mule-runtime/4.3/global-settings-configuration) Global settings, such as the default transaction time-out, that apply to the entire Mule configuration. - [Properties](https://docs.mulesoft.com/mule-runtime/4.3/configuring-properties) Configuration Properties, message properties, and system properties. - [Flows](https://docs.mulesoft.com/mule-runtime/4.3/about-flows) Combine components to define a message flow. - [Sources (Endpoints)](https://docs.mulesoft.com/mule-runtime/4.3/about-components#_endpoints) Trigger a flow. Sources are sometimes called Endpoints in Studio. - [Connectors and Modules Configurations](https://docs.mulesoft.com/connectors/) Declare configurations for any connectors and modules components used. - [Routers](https://docs.mulesoft.com/mule-runtime/4.3/about-components#_flow_control_routers) Control the flow execution. - [Operations](https://docs.mulesoft.com/mule-sdk/latest/operations) Apply specific actions within a flow. ## XML Schema [Schemas](https://www.w3.org/TR/xmlschema-1/#xsi_schemaLocation) define the configurable attributes of these resources that are referenced in the XML Configuration file. This is how a Mule artifact both validate and define its functional components and their configuration. XML schemas are used to validate functional components in a Mule artifact. They are specified in the header. ```xml ``` > [!NOTE] Mule domains feature the `mule-domain` tag instead of `mule`. Be sure to specify all the necessary schema files. This can be time-consuming when setting up the configuration file by hand, but importing schema files provides the following time-saving benefits: - Auto-completion and context-specific help in Anypoint Studio - Design-time configuration validation - Typed properties Schemas in Mule 4 are autogenerated dynamically according to the artifact dependencies. The HTTP schema, for example, will only be available if the HTTP connector is part of the artifacts dependencies. Therefore, to specify the schemas you will also need to have the correct dependencies declared. In the example above which requires the JMS and File schemas you would need the following dependencies in the artifact’s `pom.xml` file, for example: ```xml ... org.mule.connectors mule-jms-connector 1.3.2 mule-plugin org.mule.connectors mule-file-connector 1.2.1 mule-plugin ... ``` > [!NOTE] Anypoint Studio will add the required schemas and dependencies as components are > introduced. ## Namespaces Each Mule module or connector has its XML schema, including Mule core for its community and enterprise versions. When you import a schema, it has its namespace. To use the standard Mule elements, import the Mule Kernel (CE) and Mule runtime engine (EE) namespaces: - `http://www.mulesoft.org/schema/mule/core` `http://www.mulesoft.org/schema/mule/core/current/mule.xsd` - `http://www.mulesoft.org/schema/mule/ee/core` `http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd` ### Default Namespace Typically, you set the Mule core schema as the default namespace for your configuration file. This means that any XML element without a prefix will come from the Mule core schema. To set the default namespace schema, specify `xmlns` immediately followed by the URL of the Mule schema, without the colon or namespace prefix you set in the previous example (e.g., `xmlns` instead of `xmlns:jms`): ```xml ...config... ``` ## Merging Configuration Files If you have multiple configuration files, you can import them into one configuration file so that you only have to specify one configuration. This is useful to extract connector configurations or other global elements. For example: ```xml ... ``` These imports can also be dynamic when combined with properties: ```xml (1) ... ```
1The env property in the example cannot be set by a global property. To define the env value, you can configure either a system property or an environment property.
Because of the hierarchy in which Mule runtime engine loads the properties, you cannot make imports depend on an application or a global configuration property. See the [properties hierarchy](https://docs.mulesoft.com/mule-runtime/4.3/configuring-properties#properties-hierarchy) page for more information. ## Declaring Multiple Configurations You can also keep your files separate as long as you declare them as part of your application configurations. This is useful when each configuration file is relatively unrelated to the others. Configurations are declared on the application descriptor file, `mule-artifact.json`, within the `configs` section. For example, four configuration files are declared here: ```json { "configs": [ "http-api.xml", "jms-messaging-api.xml", "monitoring-tools.xml", "core-functionality.xml" ], "redeploymentEnabled": true, "name": "retail-api", "minMuleVersion": "4.1.1", "requiredProduct": "MULE_EE", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [] } }, "bundleDescriptorLoader": { "id": "mule", "attributes": {} } } ``` > [!NOTE] Anypoint Studio will handle the application descriptor automatically. ## Full Application Example Following is an example of a simple Mule configuration file for an application: ```xml #[payload] ``` ## Full Policy Example ```xml ``` ## Full Domain Example ```xml ``` ## See Also - [Mule Domains](https://docs.mulesoft.com/mule-runtime/4.3/shared-resources) - [Mule Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started) - [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.3/configuring-properties) - [Packaging Applications](https://docs.mulesoft.com/mule-runtime/4.3/intro-packaging) --- product: Mule Runtime version: 4.4 keywords: configuration, deploy, mule --- # Mule Configuration File > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications, domains, and policies are configured through an XML domain-specific language (DSL). This XML file specifies the resources that compose the artifact, including dependencies needed to run the Mule application. Although you can write the XML file manually, it is more common to use the graphical user interfaces in Anypoint Design Center or Anypoint Studio to structure and define the behavior of your Mule app. While you use either of these GUIs, the underlying XML is provided for you. In Studio, the XML is also available for viewing and editing. ## Overview A Mule configuration file is a tree. Each of the elements sets up a configuration object within Mule, for example: - [Mule Global Configuration](https://docs.mulesoft.com/mule-runtime/4.4/global-settings-configuration) Global settings, such as the default transaction time-out, that apply to the entire Mule configuration. - [Properties](https://docs.mulesoft.com/mule-runtime/4.4/configuring-properties) Configuration Properties, message properties, and system properties. - [Flows](https://docs.mulesoft.com/mule-runtime/4.4/about-flows) Combine components to define a message flow. - [Sources (Endpoints)](https://docs.mulesoft.com/mule-runtime/4.4/about-components#_endpoints) Trigger a flow. Sources are sometimes called Endpoints in Studio. - [Connectors and Modules Configurations](https://docs.mulesoft.com/connectors/) Declare configurations for any connectors and modules components used. - [Routers](https://docs.mulesoft.com/mule-runtime/4.4/about-components#_flow_control_routers) Control the flow execution. - [Operations](https://docs.mulesoft.com/mule-sdk/latest/operations) Apply specific actions within a flow. ## XML Schema [Schemas](https://www.w3.org/TR/xmlschema-1/#xsi_schemaLocation) define the configurable attributes of these resources that are referenced in the XML Configuration file. This is how a Mule artifact both validate and define its functional components and their configuration. XML schemas are used to validate functional components in a Mule artifact. They are specified in the header. ```xml ``` > [!NOTE] Mule domains feature the `mule-domain` tag instead of `mule`. Be sure to specify all the necessary schema files. This can be time-consuming when setting up the configuration file by hand, but importing schema files provides the following time-saving benefits: - Auto-completion and context-specific help in Anypoint Studio - Design-time configuration validation - Typed properties Schemas in Mule 4 are autogenerated dynamically according to the artifact dependencies. The HTTP schema, for example, will only be available if the HTTP connector is part of the artifacts dependencies. Therefore, to specify the schemas you will also need to have the correct dependencies declared. In the example above which requires the JMS and File schemas you would need the following dependencies in the artifact’s `pom.xml` file, for example: ```xml ... org.mule.connectors mule-jms-connector 1.3.2 mule-plugin org.mule.connectors mule-file-connector 1.2.1 mule-plugin ... ``` > [!NOTE] Anypoint Studio will add the required schemas and dependencies as components are > introduced. ## Namespaces Each Mule module or connector has its XML schema, including Mule core for its community and enterprise versions. When you import a schema, it has its namespace. To use the standard Mule elements, import the Mule Kernel (CE) and Mule runtime engine (EE) namespaces: - `http://www.mulesoft.org/schema/mule/core` `http://www.mulesoft.org/schema/mule/core/current/mule.xsd` - `http://www.mulesoft.org/schema/mule/ee/core` `http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd` ### Default Namespace Typically, you set the Mule core schema as the default namespace for your configuration file. This means that any XML element without a prefix will come from the Mule core schema. To set the default namespace schema, specify `xmlns` immediately followed by the URL of the Mule schema, without the colon or namespace prefix you set in the previous example (e.g., `xmlns` instead of `xmlns:jms`): ```xml ...config... ``` ## Merging Configuration Files If you have multiple configuration files, you can import them into one configuration file so that you only have to specify one configuration. This is useful to extract connector configurations or other global elements. For example: ```xml ... ``` These imports can also be dynamic when combined with properties: ```xml (1) ... ```
1The env property in the example cannot be set by a global property. To define the env value, you can configure either a system property or an environment property.
Because of the hierarchy in which Mule runtime engine loads the properties, you cannot make imports depend on an application or a global configuration property. See the [properties hierarchy](https://docs.mulesoft.com/mule-runtime/4.4/configuring-properties#properties-hierarchy) page for more information. ## Declaring Multiple Configurations You can also keep your files separate as long as you declare them as part of your application configurations. This is useful when each configuration file is relatively unrelated to the others. Configurations are declared on the application descriptor file, `mule-artifact.json`, within the `configs` section. For example, four configuration files are declared here: ```json { "configs": [ "http-api.xml", "jms-messaging-api.xml", "monitoring-tools.xml", "core-functionality.xml" ], "redeploymentEnabled": true, "name": "retail-api", "minMuleVersion": "4.1.1", "requiredProduct": "MULE_EE", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [] } }, "bundleDescriptorLoader": { "id": "mule", "attributes": {} } } ``` > [!NOTE] Anypoint Studio will handle the application descriptor automatically. ## Full Application Example Following is an example of a simple Mule configuration file for an application: ```xml #[payload] ``` ## Full Policy Example ```xml ``` ## Full Domain Example ```xml ``` ## See Also - [Mule Domains](https://docs.mulesoft.com/mule-runtime/4.4/shared-resources) - [Mule Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started) - [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.4/configuring-properties) - [Packaging Applications](https://docs.mulesoft.com/mule-runtime/4.4/intro-packaging) --- product: Mule Runtime version: 4.6 keywords: configuration, deploy, mule --- # Mule Configuration File > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications, domains, and policies are configured through an XML domain-specific language (DSL). This XML file specifies the resources that compose the artifact, including dependencies needed to run the Mule application. Although you can write the XML file manually, it is more common to use the graphical user interfaces in Anypoint Design Center or Anypoint Studio to structure and define the behavior of your Mule app. While you use either of these GUIs, the underlying XML is provided for you. In Studio, the XML is also available for viewing and editing. ## Overview A Mule configuration file is a tree. Each of the elements sets up a configuration object within Mule, for example: - [Mule Global Configuration](https://docs.mulesoft.com/mule-runtime/4.6/global-settings-configuration) Global settings, such as the default transaction time-out, that apply to the entire Mule configuration. - [Properties](https://docs.mulesoft.com/mule-runtime/4.6/configuring-properties) Configuration Properties, message properties, and system properties. - [Flows](https://docs.mulesoft.com/mule-runtime/4.6/about-flows) Combine components to define a message flow. - [Sources (Endpoints)](https://docs.mulesoft.com/mule-runtime/4.6/about-components#_endpoints) Trigger a flow. Sources are sometimes called Endpoints in Studio. - [Connectors and Modules Configurations](https://docs.mulesoft.com/connectors/) Declare configurations for any connectors and modules components used. - [Routers](https://docs.mulesoft.com/mule-runtime/4.6/about-components#_flow_control_routers) Control the flow execution. - [Operations](https://docs.mulesoft.com/mule-sdk/latest/operations) Apply specific actions within a flow. ## XML Schema [Schemas](https://www.w3.org/TR/xmlschema-1/#xsi_schemaLocation) define the configurable attributes of these resources that are referenced in the XML Configuration file. This is how a Mule artifact both validate and define its functional components and their configuration. XML schemas are used to validate functional components in a Mule artifact. They are specified in the header. ```xml ``` > [!NOTE] Mule domains feature the `mule-domain` tag instead of `mule`. Be sure to specify all the necessary schema files. This can be time-consuming when setting up the configuration file by hand, but importing schema files provides the following time-saving benefits: - Auto-completion and context-specific help in Anypoint Studio - Design-time configuration validation - Typed properties Schemas in Mule 4 are autogenerated dynamically according to the artifact dependencies. The HTTP schema, for example, will only be available if the HTTP connector is part of the artifacts dependencies. Therefore, to specify the schemas you will also need to have the correct dependencies declared. In the example above which requires the JMS and File schemas you would need the following dependencies in the artifact’s `pom.xml` file, for example: ```xml ... org.mule.connectors mule-jms-connector 1.3.2 mule-plugin org.mule.connectors mule-file-connector 1.2.1 mule-plugin ... ``` > [!NOTE] Anypoint Studio will add the required schemas and dependencies as components are > introduced. ## Namespaces Each Mule module or connector has its XML schema, including Mule core for its community and enterprise versions. When you import a schema, it has its namespace. To use the standard Mule elements, import the Mule Kernel (CE) and Mule runtime engine (EE) namespaces: - `http://www.mulesoft.org/schema/mule/core` `http://www.mulesoft.org/schema/mule/core/current/mule.xsd` - `http://www.mulesoft.org/schema/mule/ee/core` `http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd` ### Default Namespace Typically, you set the Mule core schema as the default namespace for your configuration file. This means that any XML element without a prefix will come from the Mule core schema. To set the default namespace schema, specify `xmlns` immediately followed by the URL of the Mule schema, without the colon or namespace prefix you set in the previous example (e.g., `xmlns` instead of `xmlns:jms`): ```xml ...config... ``` ## Merging Configuration Files If you have multiple configuration files, you can import them into one configuration file so that you only have to specify one configuration. This is useful to extract connector configurations or other global elements. For example: ```xml ... ``` These imports can also be dynamic when combined with properties: ```xml (1) ... ```
1The env property in the example cannot be set by a global property. To define the env value, you can configure either a system property or an environment property.
Because of the hierarchy in which Mule runtime engine loads the properties, you cannot make imports depend on an application or a global configuration property. See the [properties hierarchy](https://docs.mulesoft.com/mule-runtime/4.6/configuring-properties#properties-hierarchy) page for more information. ## Declaring Multiple Configurations You can also keep your files separate as long as you declare them as part of your application configurations. This is useful when each configuration file is relatively unrelated to the others. Configurations are declared on the application descriptor file, `mule-artifact.json`, within the `configs` section. For example, four configuration files are declared here: ```json { "configs": [ "http-api.xml", "jms-messaging-api.xml", "monitoring-tools.xml", "core-functionality.xml" ], "redeploymentEnabled": true, "name": "retail-api", "minMuleVersion": "4.1.1", "requiredProduct": "MULE_EE", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [] } }, "bundleDescriptorLoader": { "id": "mule", "attributes": {} } } ``` > [!NOTE] Anypoint Studio will handle the application descriptor automatically. ## Full Application Example Following is an example of a simple Mule configuration file for an application: ```xml #[payload] ``` ## Full Policy Example ```xml ``` ## Full Domain Example ```xml ``` ## See Also - [Mule Domains](https://docs.mulesoft.com/mule-runtime/4.6/shared-resources) - [Mule Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started) - [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.6/configuring-properties) - [Packaging Applications](https://docs.mulesoft.com/mule-runtime/4.6/mule-app-dev) --- product: Mule Runtime version: 4.9 keywords: configuration, deploy, mule --- # Mule Configuration File > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications, domains, and policies are configured through an XML domain-specific language (DSL). This XML file specifies the resources that compose the artifact, including dependencies needed to run the Mule application. Although you can write the XML file manually, it is more common to use the graphical user interfaces in Anypoint Design Center or Anypoint Studio to structure and define the behavior of your Mule app. While you use either of these GUIs, the underlying XML is provided for you. In Studio, the XML is also available for viewing and editing. ## Overview A Mule configuration file is a tree. Each of the elements sets up a configuration object within Mule, for example: - [Mule Global Configuration](https://docs.mulesoft.com/mule-runtime/4.9/global-settings-configuration) Global settings, such as the default transaction time-out, that apply to the entire Mule configuration. - [Properties](https://docs.mulesoft.com/mule-runtime/4.9/configuring-properties) Configuration Properties, message properties, and system properties. - [Flows](https://docs.mulesoft.com/mule-runtime/4.9/about-flows) Combine components to define a message flow. - [Sources (Endpoints)](https://docs.mulesoft.com/mule-runtime/4.9/about-components#_endpoints) Trigger a flow. Sources are sometimes called Endpoints in Studio. - [Connectors and Modules Configurations](https://docs.mulesoft.com/connectors/) Declare configurations for any connectors and modules components used. - [Routers](https://docs.mulesoft.com/mule-runtime/4.9/about-components#_flow_control_routers) Control the flow execution. - [Operations](https://docs.mulesoft.com/mule-sdk/latest/operations) Apply specific actions within a flow. ## XML Schema [Schemas](https://www.w3.org/TR/xmlschema-1/#xsi_schemaLocation) define the configurable attributes of these resources that are referenced in the XML Configuration file. This is how a Mule artifact both validate and define its functional components and their configuration. XML schemas are used to validate functional components in a Mule artifact. They are specified in the header. ```xml ``` > [!NOTE] Mule domains feature the `mule-domain` tag instead of `mule`. Be sure to specify all the necessary schema files. This can be time-consuming when setting up the configuration file by hand, but importing schema files provides the following time-saving benefits: - Auto-completion and context-specific help in Anypoint Studio - Design-time configuration validation - Typed properties Schemas in Mule 4 are autogenerated dynamically according to the artifact dependencies. The HTTP schema, for example, will only be available if the HTTP connector is part of the artifacts dependencies. Therefore, to specify the schemas you will also need to have the correct dependencies declared. In the example above which requires the JMS and File schemas you would need the following dependencies in the artifact’s `pom.xml` file, for example: ```xml ... org.mule.connectors mule-jms-connector 1.3.2 mule-plugin org.mule.connectors mule-file-connector 1.2.1 mule-plugin ... ``` > [!NOTE] Anypoint Studio will add the required schemas and dependencies as components are > introduced. ## Namespaces Each Mule module or connector has its XML schema, including Mule core for its community and enterprise versions. When you import a schema, it has its namespace. To use the standard Mule elements, import the Mule Kernel (CE) and Mule runtime engine (EE) namespaces: - `http://www.mulesoft.org/schema/mule/core` `http://www.mulesoft.org/schema/mule/core/current/mule.xsd` - `http://www.mulesoft.org/schema/mule/ee/core` `http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd` ### Default Namespace Typically, you set the Mule core schema as the default namespace for your configuration file. This means that any XML element without a prefix will come from the Mule core schema. To set the default namespace schema, specify `xmlns` immediately followed by the URL of the Mule schema, without the colon or namespace prefix you set in the previous example (e.g., `xmlns` instead of `xmlns:jms`): ```xml ...config... ``` ## Merging Configuration Files If you have multiple configuration files, you can import them into one configuration file so that you only have to specify one configuration. This is useful to extract connector configurations or other global elements. For example: ```xml ... ``` These imports can also be dynamic when combined with properties: ```xml (1) ... ```
1The env property in the example cannot be set by a global property. To define the env value, you can configure either a system property or an environment property.
Because of the hierarchy in which Mule runtime engine loads the properties, you cannot make imports depend on an application or a global configuration property. See the [properties hierarchy](https://docs.mulesoft.com/mule-runtime/4.9/configuring-properties#properties-hierarchy) page for more information. ## Declaring Multiple Configurations You can also keep your files separate as long as you declare them as part of your application configurations. This is useful when each configuration file is relatively unrelated to the others. Configurations are declared on the application descriptor file, `mule-artifact.json`, within the `configs` section. For example, four configuration files are declared here: ```json { "configs": [ "http-api.xml", "jms-messaging-api.xml", "monitoring-tools.xml", "core-functionality.xml" ], "redeploymentEnabled": true, "name": "retail-api", "minMuleVersion": "4.9.0", "requiredProduct": "MULE_EE", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [] } }, "bundleDescriptorLoader": { "id": "mule", "attributes": {} } } ``` > [!NOTE] Anypoint Studio will handle the application descriptor automatically. > [!NOTE] For the meaning of each field in the preceding example, including `minMuleVersion`, see > [Application Descriptor Reference (mule-artifact.json)](https://docs.mulesoft.com/mule-runtime/4.9/mule-artifact-json). For how > `minMuleVersion` affects feature flags and compatibility checks, see > [Understanding minMuleVersion](https://docs.mulesoft.com/mule-runtime/4.9/feature-flagging#_understanding_minmuleversion). ## Full Application Example Following is an example of a simple Mule configuration file for an application: ```xml #[payload] ``` ## Full Policy Example ```xml ``` ## Full Domain Example ```xml ``` ## See Also - [Mule Domains](https://docs.mulesoft.com/mule-runtime/4.9/shared-resources) - [Mule Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started) - [Configuring Properties](https://docs.mulesoft.com/mule-runtime/4.9/configuring-properties) - [Packaging Applications](https://docs.mulesoft.com/mule-runtime/4.9/mule-app-dev) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: configuration, deploy, mule --- # Mule Configuration File > For the full documentation index, see: https://docs.mulesoft.com/llms.txt All Mule applications, domains, and policies are configured through an XML domain-specific language (DSL). This XML file specifies the resources that compose the artifact, including dependencies needed to run the Mule application. Although you can write the XML file manually, it is more common to use the graphical user interfaces in Anypoint Design Center or Anypoint Studio to structure and define the behavior of your Mule app. While you use either of these GUIs, the underlying XML is provided for you. In Studio, the XML is also available for viewing and editing. ## Overview A Mule configuration file is a tree. Each of the elements sets up a configuration object within Mule, for example: - [Mule Global Configuration](https://docs.mulesoft.com/mule-runtime/latest/global-settings-configuration) Global settings, such as the default transaction time-out, that apply to the entire Mule configuration. - [Properties](https://docs.mulesoft.com/mule-runtime/latest/configuring-properties) Configuration Properties, message properties, and system properties. - [Flows](https://docs.mulesoft.com/mule-runtime/latest/about-flows) Combine components to define a message flow. - [Sources (Endpoints)](https://docs.mulesoft.com/mule-runtime/latest/about-components#_endpoints) Trigger a flow. Sources are sometimes called Endpoints in Studio. - [Connectors and Modules Configurations](https://docs.mulesoft.com/connectors/) Declare configurations for any connectors and modules components used. - [Routers](https://docs.mulesoft.com/mule-runtime/latest/about-components#_flow_control_routers) Control the flow execution. - [Operations](https://docs.mulesoft.com/mule-sdk/latest/operations) Apply specific actions within a flow. ## XML Schema [Schemas](https://www.w3.org/TR/xmlschema-1/#xsi_schemaLocation) define the configurable attributes of these resources that are referenced in the XML Configuration file. This is how a Mule artifact both validate and define its functional components and their configuration. XML schemas are used to validate functional components in a Mule artifact. They are specified in the header. ```xml ``` > [!NOTE] Mule domains feature the `mule-domain` tag instead of `mule`. Be sure to specify all the necessary schema files. This can be time-consuming when setting up the configuration file by hand, but importing schema files provides the following time-saving benefits: - Auto-completion and context-specific help in Anypoint Studio - Design-time configuration validation - Typed properties Schemas in Mule 4 are autogenerated dynamically according to the artifact dependencies. The HTTP schema, for example, will only be available if the HTTP connector is part of the artifacts dependencies. Therefore, to specify the schemas you will also need to have the correct dependencies declared. In the example above which requires the JMS and File schemas you would need the following dependencies in the artifact’s `pom.xml` file, for example: ```xml ... org.mule.connectors mule-jms-connector 1.3.2 mule-plugin org.mule.connectors mule-file-connector 1.2.1 mule-plugin ... ``` > [!NOTE] Anypoint Studio will add the required schemas and dependencies as components are > introduced. ## Namespaces Each Mule module or connector has its XML schema, including Mule core for its community and enterprise versions. When you import a schema, it has its namespace. To use the standard Mule elements, import the Mule Kernel (CE) and Mule runtime engine (EE) namespaces: - `http://www.mulesoft.org/schema/mule/core` `http://www.mulesoft.org/schema/mule/core/current/mule.xsd` - `http://www.mulesoft.org/schema/mule/ee/core` `http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd` ### Default Namespace Typically, you set the Mule core schema as the default namespace for your configuration file. This means that any XML element without a prefix will come from the Mule core schema. To set the default namespace schema, specify `xmlns` immediately followed by the URL of the Mule schema, without the colon or namespace prefix you set in the previous example (e.g., `xmlns` instead of `xmlns:jms`): ```xml ...config... ``` ## Merging Configuration Files If you have multiple configuration files, you can import them into one configuration file so that you only have to specify one configuration. This is useful to extract connector configurations or other global elements. For example: ```xml ... ``` These imports can also be dynamic when combined with properties: ```xml (1) ... ```
1The env property in the example cannot be set by a global property. To define the env value, you can configure either a system property or an environment property.
Because of the hierarchy in which Mule runtime engine loads the properties, you cannot make imports depend on an application or a global configuration property. See the [properties hierarchy](https://docs.mulesoft.com/mule-runtime/latest/configuring-properties#properties-hierarchy) page for more information. ## Declaring Multiple Configurations You can also keep your files separate as long as you declare them as part of your application configurations. This is useful when each configuration file is relatively unrelated to the others. Configurations are declared on the application descriptor file, `mule-artifact.json`, within the `configs` section. For example, four configuration files are declared here: ```json { "configs": [ "http-api.xml", "jms-messaging-api.xml", "monitoring-tools.xml", "core-functionality.xml" ], "redeploymentEnabled": true, "name": "retail-api", "minMuleVersion": "4.9.0", "requiredProduct": "MULE_EE", "classLoaderModelLoaderDescriptor": { "id": "mule", "attributes": { "exportedResources": [] } }, "bundleDescriptorLoader": { "id": "mule", "attributes": {} } } ``` > [!NOTE] Anypoint Studio will handle the application descriptor automatically. > [!NOTE] For the meaning of each field in the preceding example, including `minMuleVersion`, see > [Application Descriptor Reference (mule-artifact.json)](https://docs.mulesoft.com/mule-runtime/latest/mule-artifact-json). For how > `minMuleVersion` affects feature flags and compatibility checks, see > [Understanding minMuleVersion](https://docs.mulesoft.com/mule-runtime/latest/feature-flagging#_understanding_minmuleversion). ## Full Application Example Following is an example of a simple Mule configuration file for an application: ```xml #[payload] ``` ## Full Policy Example ```xml ``` ## Full Domain Example ```xml ``` ## See Also - [Mule Domains](https://docs.mulesoft.com/mule-runtime/latest/shared-resources) - [Mule Custom Policies](https://docs.mulesoft.com/mule-gateway/policies-custom-getting-started) - [Configuring Properties](https://docs.mulesoft.com/mule-runtime/latest/configuring-properties) - [Packaging Applications](https://docs.mulesoft.com/mule-runtime/latest/mule-app-dev) --- product: Mule Runtime version: 4.11 --- # Mule Data Types > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine uses a typed data structure called `TypedValue` that centralizes data access across different components. This data structure provides access to both the actual data and its data type. The data type consists of two values, the MIME type and the encoding of the data. ## Input Data Mule stores all variables and the payload using the `TypedValue` data structure. Also, operations like `List` from the Anypoint Platform File Connector return their results as `TypedValue` instances, enabling DataWeave to list different types of files (JSON, XML, CSV, and so on) to read. ## Output Data DataWeave always outputs a `TypedValue` instance. DataWeave decides what writer to use based on the data type of the `TypedValue` instance. However, you can manually specify the data type in a DataWeave script by using the `output` directive. If the script that Mule is executing is assigned to a message processing field, Mule informs DataWeave which type of data to expect type based on the metadata of that field. For example, if the data type is a Plain Old Java Object (Pojo), then DataWeave knows not only which class to instantiate but also that it must use the Java writer to generate the output. ## How DataWeave Uses Mule Data Types DataWeave uses the data type contained in the `TypedValue` instance to determine which reader to use, based on the MIME type, and how to configure that reader (encoding, reader properties), based on the MIME type properties. When DataWeave cannot determine the data type, it follows this procedure: 1. Verifies which input types the script is using. If all inputs are compatible or of the same data type, DataWeave uses that data type. For example, if the script contains ``, in which `vars.myBar` is of type XML and `payload` is of type JSON, DataWeave throws an error. In some cases, specifically when working with XML, an expression in a Set payload operation fails because it generates an invalid XML structure. 2. If no input is used, DataWeave uses the Java writer. For example, when DataWeave reads the script ` --- product: Mule Runtime version: 4.12 --- # Mule Data Types > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine uses a typed data structure called `TypedValue` that centralizes data access across different components. This data structure provides access to both the actual data and its data type. The data type consists of two values, the MIME type and the encoding of the data. ## Input Data Mule stores all variables and the payload using the `TypedValue` data structure. Also, operations like `List` from the Anypoint Platform File Connector return their results as `TypedValue` instances, enabling DataWeave to list different types of files (JSON, XML, CSV, and so on) to read. ## Output Data DataWeave always outputs a `TypedValue` instance. DataWeave decides what writer to use based on the data type of the `TypedValue` instance. However, you can manually specify the data type in a DataWeave script by using the `output` directive. If the script that Mule is executing is assigned to a message processing field, Mule informs DataWeave which type of data to expect type based on the metadata of that field. For example, if the data type is a Plain Old Java Object (Pojo), then DataWeave knows not only which class to instantiate but also that it must use the Java writer to generate the output. ## How DataWeave Uses Mule Data Types DataWeave uses the data type contained in the `TypedValue` instance to determine which reader to use, based on the MIME type, and how to configure that reader (encoding, reader properties), based on the MIME type properties. When DataWeave cannot determine the data type, it follows this procedure: 1. Verifies which input types the script is using. If all inputs are compatible or of the same data type, DataWeave uses that data type. For example, if the script contains ``, in which `vars.myBar` is of type XML and `payload` is of type JSON, DataWeave throws an error. In some cases, specifically when working with XML, an expression in a Set payload operation fails because it generates an invalid XML structure. 2. If no input is used, DataWeave uses the Java writer. For example, when DataWeave reads the script ` --- product: Mule Runtime version: 4.4 --- # Mule Data Types > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine uses a typed data structure called `TypedValue` that centralizes data access across different components. This data structure provides access to both the actual data and its data type. The data type consists of two values, the MIME type and the encoding of the data. ## Input Data Mule stores all variables and the payload using the `TypedValue` data structure. Also, operations like `List` from the Anypoint Platform File Connector return their results as `TypedValue` instances, enabling DataWeave to list different types of files (JSON, XML, CSV, and so on) to read. ## Output Data DataWeave always outputs a `TypedValue` instance. DataWeave decides what writer to use based on the data type of the `TypedValue` instance. However, you can manually specify the data type in a DataWeave script by using the `output` directive. If the script that Mule is executing is assigned to a message processing field, Mule informs DataWeave which type of data to expect type based on the metadata of that field. For example, if the data type is a Plain Old Java Object (Pojo), then DataWeave knows not only which class to instantiate but also that it must use the Java writer to generate the output. ## How DataWeave Uses Mule Data Types DataWeave uses the data type contained in the `TypedValue` instance to determine which reader to use, based on the MIME type, and how to configure that reader (encoding, reader properties), based on the MIME type properties. When DataWeave cannot determine the data type, it follows this procedure: 1. Verifies which input types the script is using. If all inputs are compatible or of the same data type, DataWeave uses that data type. For example, if the script contains ``, in which `vars.myBar` is of type XML and `payload` is of type JSON, DataWeave throws an error. In some cases, specifically when working with XML, an expression in a Set payload operation fails because it generates an invalid XML structure. 2. If no input is used, DataWeave uses the Java writer. For example, when DataWeave reads the script ` --- product: Mule Runtime version: 4.6 --- # Mule Data Types > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine uses a typed data structure called `TypedValue` that centralizes data access across different components. This data structure provides access to both the actual data and its data type. The data type consists of two values, the MIME type and the encoding of the data. ## Input Data Mule stores all variables and the payload using the `TypedValue` data structure. Also, operations like `List` from the Anypoint Platform File Connector return their results as `TypedValue` instances, enabling DataWeave to list different types of files (JSON, XML, CSV, and so on) to read. ## Output Data DataWeave always outputs a `TypedValue` instance. DataWeave decides what writer to use based on the data type of the `TypedValue` instance. However, you can manually specify the data type in a DataWeave script by using the `output` directive. If the script that Mule is executing is assigned to a message processing field, Mule informs DataWeave which type of data to expect type based on the metadata of that field. For example, if the data type is a Plain Old Java Object (Pojo), then DataWeave knows not only which class to instantiate but also that it must use the Java writer to generate the output. ## How DataWeave Uses Mule Data Types DataWeave uses the data type contained in the `TypedValue` instance to determine which reader to use, based on the MIME type, and how to configure that reader (encoding, reader properties), based on the MIME type properties. When DataWeave cannot determine the data type, it follows this procedure: 1. Verifies which input types the script is using. If all inputs are compatible or of the same data type, DataWeave uses that data type. For example, if the script contains ``, in which `vars.myBar` is of type XML and `payload` is of type JSON, DataWeave throws an error. In some cases, specifically when working with XML, an expression in a Set payload operation fails because it generates an invalid XML structure. 2. If no input is used, DataWeave uses the Java writer. For example, when DataWeave reads the script ` --- product: Mule Runtime version: 4.9 --- # Mule Data Types > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine uses a typed data structure called `TypedValue` that centralizes data access across different components. This data structure provides access to both the actual data and its data type. The data type consists of two values, the MIME type and the encoding of the data. ## Input Data Mule stores all variables and the payload using the `TypedValue` data structure. Also, operations like `List` from the Anypoint Platform File Connector return their results as `TypedValue` instances, enabling DataWeave to list different types of files (JSON, XML, CSV, and so on) to read. ## Output Data DataWeave always outputs a `TypedValue` instance. DataWeave decides what writer to use based on the data type of the `TypedValue` instance. However, you can manually specify the data type in a DataWeave script by using the `output` directive. If the script that Mule is executing is assigned to a message processing field, Mule informs DataWeave which type of data to expect type based on the metadata of that field. For example, if the data type is a Plain Old Java Object (Pojo), then DataWeave knows not only which class to instantiate but also that it must use the Java writer to generate the output. ## How DataWeave Uses Mule Data Types DataWeave uses the data type contained in the `TypedValue` instance to determine which reader to use, based on the MIME type, and how to configure that reader (encoding, reader properties), based on the MIME type properties. When DataWeave cannot determine the data type, it follows this procedure: 1. Verifies which input types the script is using. If all inputs are compatible or of the same data type, DataWeave uses that data type. For example, if the script contains ``, in which `vars.myBar` is of type XML and `payload` is of type JSON, DataWeave throws an error. In some cases, specifically when working with XML, an expression in a Set payload operation fails because it generates an invalid XML structure. 2. If no input is used, DataWeave uses the Java writer. For example, when DataWeave reads the script ` --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Mule Data Types > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine uses a typed data structure called `TypedValue` that centralizes data access across different components. This data structure provides access to both the actual data and its data type. The data type consists of two values, the MIME type and the encoding of the data. ## Input Data Mule stores all variables and the payload using the `TypedValue` data structure. Also, operations like `List` from the Anypoint Platform File Connector return their results as `TypedValue` instances, enabling DataWeave to list different types of files (JSON, XML, CSV, and so on) to read. ## Output Data DataWeave always outputs a `TypedValue` instance. DataWeave decides what writer to use based on the data type of the `TypedValue` instance. However, you can manually specify the data type in a DataWeave script by using the `output` directive. If the script that Mule is executing is assigned to a message processing field, Mule informs DataWeave which type of data to expect type based on the metadata of that field. For example, if the data type is a Plain Old Java Object (Pojo), then DataWeave knows not only which class to instantiate but also that it must use the Java writer to generate the output. ## How DataWeave Uses Mule Data Types DataWeave uses the data type contained in the `TypedValue` instance to determine which reader to use, based on the MIME type, and how to configure that reader (encoding, reader properties), based on the MIME type properties. When DataWeave cannot determine the data type, it follows this procedure: 1. Verifies which input types the script is using. If all inputs are compatible or of the same data type, DataWeave uses that data type. For example, if the script contains ``, in which `vars.myBar` is of type XML and `payload` is of type JSON, DataWeave throws an error. In some cases, specifically when working with XML, an expression in a Set payload operation fails because it generates an invalid XML structure. 2. If no input is used, DataWeave uses the Java writer. For example, when DataWeave reads the script ` --- product: Mule Runtime version: 4.11 --- # Mule Errors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule execution failures result in an error. When a Mule app is running, both the Mule runtime engine and the module and connector operations configured in the app can throw errors that are represented by a Mule error object, which is associated with a Mule event. You can handle error objects with On-Error components and find information about them in the logs. Mule errors are grouped into [error types](#error_types) that follow a hierarchical order and use a naming convention that helps you identify the source of the error and handle the error at the level you choose. You can also create custom error types that you map to these errors. The mappings can help you further differentiate and group errors that you need to handle in your app. To inspect and use values of Mule errors in your error handling configurations, you can also use [selector expressions](#selector_expressions). Mule errors include expression (`EXPRESSION`) and stream-related errors (`STREAM_MAXIMUM_SIZE_EXCEEDED`), while the operations can throw many different types of errors. Examples include `HTTP:NOT_FOUND` (a 404 error) and `HTTP:CONNECTIVITY` errors from the HTTP listener in the HTTP connector. `DB:BAD_SYNTAX` and `DB:QUERY_EXPRESSION` are errors that the Select operation in the Database connector can throw. The reference documentation for modules and connectors (for example, the [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) and [Database Connector](https://docs.mulesoft.com/db-connector/latest/database-documentation) references) lists Mule errors. ## Selector Expressions for Mule Errors Mule errors are complex data types with several fields, such as a description and type. When logging and handling Mule errors, can select the values from any number of the error fields.
FieldDescriptionSelector Expression

Description

A description of the problem.

#[error.description]

Detailed Description

A description of the problem, which can be the same or more extensive than the description.

#[error.detailedDescription]

Type

A type, used to characterize the problem and allow for routing within an error handler.

#[error.errorType]

Cause

The underlying Java Throwable that resulted in the failure.

#[error.cause]

Message

An optional Mule message about the problem.

#[error.errorMessage]

Child Errors

An optional collection of inner errors, used by elements like Scatter-Gather to provide aggregated route errors.

#[error.childErrors]

> [!IMPORTANT] In most cases, the `error.cause` selector returns a `Throwable` instance that is part > of the Mule API. Do not access the error’s internal structure to define error handling logic. The > other selectors expose all the necessary information to handle errors. Also, serializing the > `error.cause` might result in redundant information. ### HTTP Request Error Example For example, when an HTTP request fails with an `HTTP:NOT_FOUND` error (for a 404 status code), the values for each part of the Error Message are: - `#[error.description]` returns: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404). ``` - `#[error.detailedDescription]` returns `HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404).` - `#[error.errorType]` returns `HTTP:NOT_FOUND` - `#[error.cause]` returns `org.mule.extension.http.api.request.validator.ResponseValidatorTypedException`. If you print the return instance of `ResponseValidatorTypedException`, Mule prints the result of `toString`. When the error has an associated known HTTP status code (such as 404), the string representation of the `ResponseValidatorTypedException` instance is a human-readable description of the error. - `#[error.errorMessage]` returns: ```txt org.mule.runtime.core.internal.message.DefaultMessageBuilder$MessageImplementation { payload=org.mule.runtime.core.internal.streaming.bytes.ManagedCursorStreamProvider@223d8f75 mediaType=application/json; charset=UTF-8 attributes=org.mule.extension.http.api.HttpResponseAttributes { Status Code=404 Reason Phrase=Not Found Headers=[ date=Sat, 03 Aug 2019 04:28:29 GMT content-type=application/json; charset=utf-8 content-length=2 connection=keep-alive set-cookie=__cfduid=de19ed0b495b5b58e74fa0ee31a700d651564806509; expires=Sun, 02-Aug-20 04:28:29 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 pragma=no-cache expires=Sat, 03 Aug 2019 08:28:29 GMT x-content-type-options=nosniff etag=W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8" via=1.1 vegur cf-cache-status=HIT age=96 server=cloudflare cf-ray=50058b8add0a92fe-SJC ] } attributesMediaType=*/* } ``` The `errorMessage` element becomes available when a connector or component exposes the message that it has interpreted as an error. For example, when an HTTP request receives a status code that Mule treats as an error, the process fails and also populates the `errorMessage` with information about the error. You can then gain access to error message attributes (metadata) and to the payload itself with `#[error.errorMessage.payload]` for the payload and `#[error.errorMessage.attributes]` for the metadata. In the case of an HTTP request that returns an error, you can then use `#[error.errorMessage.attributes.statusCode]` to select the value of the status code (such as `404`). To see message attributes in Studio, see [DataSense](https://docs.mulesoft.com/studio/datasense-concept). - `#[error.childErrors]` returns: `[]` ## Mule Error Types Mule errors have a namespace (such as `HTTP:` and `FILE:`) and identifier (such as `NOT_FOUND`), and they belong to a hierarchy of error types. The naming convention enables you to distinguish errors according to their domain. For example, instead of throwing `NOT_FOUND`, the HTTP connector can throw `HTTP:NOT_FOUND`, and the File connector can throw `FILE:NOT_FOUND` errors. Unlike connectors, Mule runtime errors have an implicit `MULE` namespace, so `MULE:EXPRESSION` and `EXPRESSION` are interpreted the same way. Error types can have a parent type. For example, the parent of `HTTP:UNAUTHORIZED` is `MULE:CLIENT_SECURITY`, and the parent of `MULE:CLIENT_SECURITY` is `MULE:SECURITY`. This hierarchy implies that each error type is a specification of more global error type. For example, an `HTTP:UNAUTHORIZED` error type is a type of client security error (`MULE:CLIENT_SECURITY`), which is a type of a more broad security issue (`MULE:SECURITY`). The hierarchies enable you to route errors in a general or more specific way. For example, an error handler for `MULE:SECURITY` catches `HTTP:UNAUTHORIZED` errors and OAuth errors. The follow figure shows the core runtime hierarchy: ![A hierarchy of error types showing categories including ANY and CRITICAL](/mulesoft/current/en-us/mule-runtime/4.11/_images/error-hierarchy.png) All errors belong to one of these two main types: `ANY` or `CRITICAL`. Each type under `ANY` is matched by its parent and can be handled, while error types under `CRITICAL` are so severe that cannot be handled and are only logged. `CRITICAL` errors include `FATAL_JVM_ERROR` and `OVERLOAD`. Whenever there is no clear reason for a failure, a component can use the `UNKNOWN` type. You handle this error through the `ANY` type to define unclear errors, without changing the existing behavior of the app. For connectors, each connector defines its error type hierarchy considering the core runtime hierarchy, though `CONNECTIVITY` and `RETRY_EXHAUSTED` types are always present because they are common to all connectors. Error Types: - `ANY`: error type that matches all error types that occur in a Flow and can be handled. This type does not include errors that occur on the source. - `TRANSFORMATION`: indicates an error occurred while transforming a value. This involves Mule Runtime internal transformations and not DataWeave transformations. - `EXPRESSION`: indicates an error occurred while evaluating a DataWeave expression. - `VALIDATION`: indicates a validation error occurred. - `DUPLICATE_MESSAGE`: indicates a validation error regarding a message being processed twice. For example, using the [Idempotent message validator](https://docs.mulesoft.com/mule-runtime/4.11/idempotent-message-validator). - `REDELIVERY_EXHAUSTED`: indicates that max attempts to reprocess a message from a source have been exhausted. - `CONNECTIVITY`: indicates that there was a problem establishing a connection. This could occur while using a connector, for example, an HTTP requester. - `RETRY_EXHAUSTED`: indicates that retries of a certain execution block have been exhausted. For example, for a given operation, or using [Until Successful Scope](https://docs.mulesoft.com/mule-runtime/4.11/until-successful-scope). - `ROUTING`: indicates an error occurred while routing a message. For example, using the [Round Robin router](https://docs.mulesoft.com/mule-runtime/4.11/round-robin). - `COMPOSITE_ROUTING`: indicates that one or more errors occurred while routing a message. For example, using a [Scatter Gather Router](https://docs.mulesoft.com/mule-runtime/4.11/scatter-gather-concept). - `SECURITY`: indicates a security error occurred, like invalid credentials being received or an expired token being used. - `CLIENT_SECURITY`: indicates an external entity (e.g., calling an external endpoint) produced a security error. - `SERVER_SECURITY`: indicates a security error enforced by the Mule runtime. - `NOT_PERMITTED`: indicates a security restriction enforced by a filter. For example, using [the Authorization Filter of the Mule Spring Module](https://docs.mulesoft.com/spring-module/latest/#_to_validate_authentication_using_the_spring_authorization_filter). - `STREAM_MAXIMUM_SIZE_EXCEEDED`: indicates the maximum size allowed for a stream has been exceeded. For more insight, see [Streaming in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.11/streaming-about). - `TIMEOUT`: indicates timeout occurred while processing a message. - `UNKNOWN`: indicates an unknown or unexpected error occurred. This cannot be handled directly, only by handling `ANY`, to ensure backward compatibility in case more error types are added in future runtime versions. - `SOURCE`: indicates that an error occurred in the source of the flow. These errors cannot be handled. - `SOURCE_ERROR_RESPONSE_GENERATE`: indicates that an error occurred in the source of the flow generating the parameters of an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_ERROR_RESPONSE_SEND`: indicates that an error occurred in the source of the flow sending an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_RESPONSE`: indicates that an error occurred in the source of a flow while processing a successful response. These errors can only be propagated since the source has already executed the successful path. These errors cannot be handled. - `SOURCE_RESPONSE_GENERATE`: indicates an error occurred in the source of the flow while generating the parameters of a successful response. - `SOURCE_RESPONSE_SEND`: indicates an error occurred in the source of the flow while sending a successful response. - `CRITICAL`: indicates a severe error occurred. These errors cannot be handled. - `OVERLOAD`: indicates a problem of overloading occurred and the execution was rejected. - `FLOW_BACK_PRESSURE`: indicates a problem of overloading occurred at the source level. For example, using an HTTP listener as a source. - `FATAL_JVM_ERROR`: indicates that a fatal error occurred, such as stack overflow. ### What Happens After a FATAL\_JVM\_ERROR When the JVM throws a `VirtualMachineError` (for example, `OutOfMemoryError` or `StackOverflowError`), Mule runtime wraps it as a `MULE:FATAL` error and raises a `FATAL_ERROR_RAISED` alert. Because these errors are in the `CRITICAL` hierarchy, On-Error components (`on-error-continue`, `on-error-propagate`) can’t handle them. After a `VirtualMachineError` occurs, the Mule runtime instance, its internal components, or the underlying JVM can remain in an invalid state. Memory can be corrupted, threads can enter undefined states, and further message processing is unreliable. > [!IMPORTANT] The only safe recovery action after a `VirtualMachineError` occurs is to restart the > Mule runtime instance. Don’t assume that the application can continue processing correctly after > encountering one of these errors. #### Common Causes
ErrorCommon Causes

OutOfMemoryError

Unbounded in-memory caching, unconsumed streams that accumulate buffers, processing very large payloads without streaming, or memory leaks in custom Java code.

StackOverflowError

Extremely long flows that create deeply nested Reactor operator stacks, or unbounded recursion in custom Java components or DataWeave expressions. Recursive flow references (a flow calling itself through flow-ref) are protected by Mule runtime internal nesting limit, which raises an EventContextDeepNestingException before a JVM stack overflow occurs.

#### Monitoring and Recovery - Monitor application logs for messages containing `VirtualMachineError`, `OutOfMemoryError`, or `StackOverflowError`. - In managed deployment targets (CloudHub, Runtime Fabric), configure health checks and automatic restarts so that affected instances are replaced quickly. - For on-premises deployments, configure your process supervisor (systemd, Tanuki wrapper) to restart the Mule process if it becomes unresponsive. - After a restart, investigate the root cause by using heap dumps (for `OutOfMemoryError`) or thread dumps (for `StackOverflowError`) captured before the failure occurs. For design patterns that help prevent these errors, see [Avoid Recursive Flow References](https://docs.mulesoft.com/mule-runtime/4.11/tuning-app-design#avoid-recursive-flow-references) and [Consume Streams Promptly](https://docs.mulesoft.com/mule-runtime/4.11/streaming-about#consume-streams-promptly). ## Custom Error Types To use custom error types, you need to define them either when mapping or when [raising](https://docs.mulesoft.com/mule-runtime/4.11/raise-error-component-reference) the errors. These errors require a specific custom namespace to distinguish them from other existing types within an application. This means that an app that uses HTTP and Database connector operations cannot use the HTTP and DB namespaces for custom error types. You need to define namespaces that are related to the particular Mule app name or context and avoid using existing connector namespaces. For example, a customer aggregation API might use the `CUSTOMER` namespace for its custom error types, and an order-processing API might use the `ORDER` namespace. ## Error Mappings In each operation of your flow, you can map the possible error types to a custom error type of your choosing. You can use these custom error types to differentiate where an error occurred in your flow. For example, if your flow has two HTTP Request operations that reach out to different REST services, a connectivity failure on either produces the same error. By mapping each error to different custom error types, you can differentiate the error handling of each operation failure and quickly identify the source of the error in the Mule app logs. In the following example, you can see how mappings allow granular error handling by defining two custom error types: `APP:CUSTOMER_API` and `APP:ORDER_API`. Example XML Configuration for Mappings: ```xml ``` ## See Also - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.11/on-error-scope-concept) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/4.11/logging-and-debugging) --- product: Mule Runtime version: 4.12 --- # Mule Errors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule execution failures result in an error. When a Mule app is running, both the Mule runtime engine and the module and connector operations configured in the app can throw errors that are represented by a Mule error object, which is associated with a Mule event. You can handle error objects with On-Error components and find information about them in the logs. Mule errors are grouped into [error types](#error_types) that follow a hierarchical order and use a naming convention that helps you identify the source of the error and handle the error at the level you choose. You can also create custom error types that you map to these errors. The mappings can help you further differentiate and group errors that you need to handle in your app. To inspect and use values of Mule errors in your error handling configurations, you can also use [selector expressions](#selector_expressions). Mule errors include expression (`EXPRESSION`) and stream-related errors (`STREAM_MAXIMUM_SIZE_EXCEEDED`), while the operations can throw many different types of errors. Examples include `HTTP:NOT_FOUND` (a 404 error) and `HTTP:CONNECTIVITY` errors from the HTTP listener in the HTTP connector. `DB:BAD_SYNTAX` and `DB:QUERY_EXPRESSION` are errors that the Select operation in the Database connector can throw. The reference documentation for modules and connectors (for example, the [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) and [Database Connector](https://docs.mulesoft.com/db-connector/latest/database-documentation) references) lists Mule errors. ## Selector Expressions for Mule Errors Mule errors are complex data types with several fields, such as a description and type. When logging and handling Mule errors, can select the values from any number of the error fields.
FieldDescriptionSelector Expression

Description

A description of the problem.

#[error.description]

Detailed Description

A description of the problem, which can be the same or more extensive than the description.

#[error.detailedDescription]

Type

A type, used to characterize the problem and allow for routing within an error handler.

#[error.errorType]

Cause

The underlying Java Throwable that resulted in the failure.

#[error.cause]

Message

An optional Mule message about the problem.

#[error.errorMessage]

Child Errors

An optional collection of inner errors, used by elements like Scatter-Gather to provide aggregated route errors.

#[error.childErrors]

> [!IMPORTANT] In most cases, the `error.cause` selector returns a `Throwable` instance that is part > of the Mule API. Do not access the error’s internal structure to define error handling logic. The > other selectors expose all the necessary information to handle errors. Also, serializing the > `error.cause` might result in redundant information. ### HTTP Request Error Example For example, when an HTTP request fails with an `HTTP:NOT_FOUND` error (for a 404 status code), the values for each part of the Error Message are: - `#[error.description]` returns: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404). ``` - `#[error.detailedDescription]` returns `HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404).` - `#[error.errorType]` returns `HTTP:NOT_FOUND` - `#[error.cause]` returns `org.mule.extension.http.api.request.validator.ResponseValidatorTypedException`. If you print the return instance of `ResponseValidatorTypedException`, Mule prints the result of `toString`. When the error has an associated known HTTP status code (such as 404), the string representation of the `ResponseValidatorTypedException` instance is a human-readable description of the error. - `#[error.errorMessage]` returns: ```txt org.mule.runtime.core.internal.message.DefaultMessageBuilder$MessageImplementation { payload=org.mule.runtime.core.internal.streaming.bytes.ManagedCursorStreamProvider@223d8f75 mediaType=application/json; charset=UTF-8 attributes=org.mule.extension.http.api.HttpResponseAttributes { Status Code=404 Reason Phrase=Not Found Headers=[ date=Sat, 03 Aug 2019 04:28:29 GMT content-type=application/json; charset=utf-8 content-length=2 connection=keep-alive set-cookie=__cfduid=de19ed0b495b5b58e74fa0ee31a700d651564806509; expires=Sun, 02-Aug-20 04:28:29 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 pragma=no-cache expires=Sat, 03 Aug 2019 08:28:29 GMT x-content-type-options=nosniff etag=W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8" via=1.1 vegur cf-cache-status=HIT age=96 server=cloudflare cf-ray=50058b8add0a92fe-SJC ] } attributesMediaType=*/* } ``` The `errorMessage` element becomes available when a connector or component exposes the message that it has interpreted as an error. For example, when an HTTP request receives a status code that Mule treats as an error, the process fails and also populates the `errorMessage` with information about the error. You can then gain access to error message attributes (metadata) and to the payload itself with `#[error.errorMessage.payload]` for the payload and `#[error.errorMessage.attributes]` for the metadata. In the case of an HTTP request that returns an error, you can then use `#[error.errorMessage.attributes.statusCode]` to select the value of the status code (such as `404`). To see message attributes in Studio, see [DataSense](https://docs.mulesoft.com/studio/datasense-concept). - `#[error.childErrors]` returns: `[]` ## Mule Error Types Mule errors have a namespace (such as `HTTP:` and `FILE:`) and identifier (such as `NOT_FOUND`), and they belong to a hierarchy of error types. The naming convention enables you to distinguish errors according to their domain. For example, instead of throwing `NOT_FOUND`, the HTTP connector can throw `HTTP:NOT_FOUND`, and the File connector can throw `FILE:NOT_FOUND` errors. Unlike connectors, Mule runtime errors have an implicit `MULE` namespace, so `MULE:EXPRESSION` and `EXPRESSION` are interpreted the same way. Error types can have a parent type. For example, the parent of `HTTP:UNAUTHORIZED` is `MULE:CLIENT_SECURITY`, and the parent of `MULE:CLIENT_SECURITY` is `MULE:SECURITY`. This hierarchy implies that each error type is a specification of more global error type. For example, an `HTTP:UNAUTHORIZED` error type is a type of client security error (`MULE:CLIENT_SECURITY`), which is a type of a more broad security issue (`MULE:SECURITY`). The hierarchies enable you to route errors in a general or more specific way. For example, an error handler for `MULE:SECURITY` catches `HTTP:UNAUTHORIZED` errors and OAuth errors. The follow figure shows the core runtime hierarchy: ![A hierarchy of error types showing categories including ANY and CRITICAL](/mulesoft/current/en-us/mule-runtime/4.12/_images/error-hierarchy.png) All errors belong to one of these two main types: `ANY` or `CRITICAL`. Each type under `ANY` is matched by its parent and can be handled, while error types under `CRITICAL` are so severe that cannot be handled and are only logged. `CRITICAL` errors include `FATAL_JVM_ERROR` and `OVERLOAD`. Whenever there is no clear reason for a failure, a component can use the `UNKNOWN` type. You handle this error through the `ANY` type to define unclear errors, without changing the existing behavior of the app. For connectors, each connector defines its error type hierarchy considering the core runtime hierarchy, though `CONNECTIVITY` and `RETRY_EXHAUSTED` types are always present because they are common to all connectors. Error Types: - `ANY`: error type that matches all error types that occur in a Flow and can be handled. This type does not include errors that occur on the source. - `TRANSFORMATION`: indicates an error occurred while transforming a value. This involves Mule runtime internal transformations and not DataWeave transformations. - `EXPRESSION`: indicates an error occurred while evaluating a DataWeave expression. - `VALIDATION`: indicates a validation error occurred. - `DUPLICATE_MESSAGE`: indicates a validation error regarding a message being processed twice. For example, using the [Idempotent message validator](https://docs.mulesoft.com/mule-runtime/4.12/idempotent-message-validator). - `REDELIVERY_EXHAUSTED`: indicates that max attempts to reprocess a message from a source have been exhausted. - `CONNECTIVITY`: indicates that there was a problem establishing a connection. This could occur while using a connector, for example, an HTTP requester. - `RETRY_EXHAUSTED`: indicates that retries of a certain execution block have been exhausted. For example, for a given operation, or using [Until Successful Scope](https://docs.mulesoft.com/mule-runtime/4.12/until-successful-scope). - `ROUTING`: indicates an error occurred while routing a message. For example, using the [Round Robin router](https://docs.mulesoft.com/mule-runtime/4.12/round-robin). - `COMPOSITE_ROUTING`: indicates that one or more errors occurred while routing a message. For example, using a [Scatter Gather Router](https://docs.mulesoft.com/mule-runtime/4.12/scatter-gather-concept). - `SECURITY`: indicates a security error occurred, like invalid credentials being received or an expired token being used. - `CLIENT_SECURITY`: indicates an external entity (e.g., calling an external endpoint) produced a security error. - `SERVER_SECURITY`: indicates a security error enforced by the Mule runtime. - `NOT_PERMITTED`: indicates a security restriction enforced by a filter. For example, using [the Authorization Filter of the Mule Spring Module](https://docs.mulesoft.com/spring-module/latest/#_to_validate_authentication_using_the_spring_authorization_filter). - `STREAM_MAXIMUM_SIZE_EXCEEDED`: indicates the maximum size allowed for a stream has been exceeded. For more insight, see [Streaming in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.12/streaming-about). - `TIMEOUT`: indicates timeout occurred while processing a message. - `UNKNOWN`: indicates an unknown or unexpected error occurred. This cannot be handled directly, only by handling `ANY`, to ensure backward compatibility in case more error types are added in future runtime versions. - `SOURCE`: indicates that an error occurred in the source of the flow. These errors cannot be handled. - `SOURCE_ERROR_RESPONSE_GENERATE`: indicates that an error occurred in the source of the flow generating the parameters of an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_ERROR_RESPONSE_SEND`: indicates that an error occurred in the source of the flow sending an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_RESPONSE`: indicates that an error occurred in the source of a flow while processing a successful response. These errors can only be propagated since the source has already executed the successful path. These errors cannot be handled. - `SOURCE_RESPONSE_GENERATE`: indicates an error occurred in the source of the flow while generating the parameters of a successful response. - `SOURCE_RESPONSE_SEND`: indicates an error occurred in the source of the flow while sending a successful response. - `CRITICAL`: indicates a severe error occurred. These errors cannot be handled. - `OVERLOAD`: indicates a problem of overloading occurred and the execution was rejected. - `FLOW_BACK_PRESSURE`: indicates a problem of overloading occurred at the source level. For example, using an HTTP listener as a source. - `FATAL_JVM_ERROR`: indicates that a fatal error occurred, such as stack overflow. ### What Happens After a FATAL\_JVM\_ERROR When the JVM throws a `VirtualMachineError` (for example, `OutOfMemoryError` or `StackOverflowError`), Mule runtime wraps it as a `MULE:FATAL` error and raises a `FATAL_ERROR_RAISED` alert. Because these errors are in the `CRITICAL` hierarchy, On-Error components (`on-error-continue`, `on-error-propagate`) can’t handle them. After a `VirtualMachineError` occurs, the Mule runtime instance, its internal components, or the underlying JVM can remain in an invalid state. Memory can be corrupted, threads can enter undefined states, and further message processing is unreliable. > [!IMPORTANT] The only safe recovery action after a `VirtualMachineError` occurs is to restart the > Mule runtime instance. Don’t assume that the application can continue processing correctly after > encountering one of these errors. #### Common Causes
ErrorCommon Causes

OutOfMemoryError

Unbounded in-memory caching, unconsumed streams that accumulate buffers, processing very large payloads without streaming, or memory leaks in custom Java code.

StackOverflowError

Extremely long flows that create deeply nested Reactor operator stacks, or unbounded recursion in custom Java components or DataWeave expressions. Recursive flow references (a flow calling itself through flow-ref) are protected by Mule runtime internal nesting limit, which raises an EventContextDeepNestingException before a JVM stack overflow occurs.

#### Monitoring and Recovery - Monitor application logs for messages containing `VirtualMachineError`, `OutOfMemoryError`, or `StackOverflowError`. - In managed deployment targets (CloudHub, Runtime Fabric), configure health checks and automatic restarts so that affected instances are replaced quickly. - For on-premises deployments, configure your process supervisor (systemd, Tanuki wrapper) to restart the Mule process if it becomes unresponsive. - After a restart, investigate the root cause by using heap dumps (for `OutOfMemoryError`) or thread dumps (for `StackOverflowError`) captured before the failure occurs. For design patterns that help prevent these errors, see [Avoid Recursive Flow References](https://docs.mulesoft.com/mule-runtime/4.12/tuning-app-design#avoid-recursive-flow-references) and [Consume Streams Promptly](https://docs.mulesoft.com/mule-runtime/4.12/streaming-about#consume-streams-promptly). ## Custom Error Types To use custom error types, you need to define them either when mapping or when [raising](https://docs.mulesoft.com/mule-runtime/4.12/raise-error-component-reference) the errors. These errors require a specific custom namespace to distinguish them from other existing types within an application. This means that an app that uses HTTP and Database connector operations cannot use the HTTP and DB namespaces for custom error types. You need to define namespaces that are related to the particular Mule app name or context and avoid using existing connector namespaces. For example, a customer aggregation API might use the `CUSTOMER` namespace for its custom error types, and an order-processing API might use the `ORDER` namespace. ## Error Mappings In each operation of your flow, you can map the possible error types to a custom error type of your choosing. You can use these custom error types to differentiate where an error occurred in your flow. For example, if your flow has two HTTP Request operations that reach out to different REST services, a connectivity failure on either produces the same error. By mapping each error to different custom error types, you can differentiate the error handling of each operation failure and quickly identify the source of the error in the Mule app logs. In the following example, you can see how mappings allow granular error handling by defining two custom error types: `APP:CUSTOMER_API` and `APP:ORDER_API`. Example XML Configuration for Mappings: ```xml ``` ## See Also - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.12/on-error-scope-concept) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/4.12/logging-and-debugging) --- product: Mule Runtime version: 4.3 --- # Mule Errors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule execution failures result in an error. When a Mule app is running, both the Mule runtime engine and the module and connector operations configured in the app can throw errors that are represented by a Mule error object, which is associated with a Mule event. You can handle error objects with On-Error components and find information about them in the logs. Mule errors are grouped into [error types](#error_types) that follow a hierarchical order and use a naming convention that helps you identify the source of the error and handle the error at the level you choose. You can also create custom error types that you map to these errors. The mappings can help you further differentiate and group errors that you need to handle in your app. To inspect and use values of Mule errors in your error handling configurations, you can also use [selector expressions](#selector_expressions). Mule errors include expression (`EXPRESSION`) and stream-related errors (`STREAM_MAXIMUM_SIZE_EXCEEDED`), while the operations can throw many different types of errors. Examples include `HTTP:NOT_FOUND` (a 404 error) and `HTTP:CONNECTIVITY` errors from the HTTP listener in the HTTP connector. `DB:BAD_SYNTAX` and `DB:QUERY_EXPRESSION` are errors that the Select operation in the Database connector can throw. The reference documentation for modules and connectors (for example, the [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) and [Database Connector](https://docs.mulesoft.com/db-connector/latest/database-documentation) references) lists Mule errors. ## Selector Expressions for Mule Errors Mule errors are complex data types with several fields, such as a description and type. When logging and handling Mule errors, can select the values from any number of the error fields.
FieldDescriptionSelector Expression

Description

A description of the problem.

#[error.description]

Detailed Description

A description of the problem, which can be the same or more extensive than the description.

#[error.detailedDescription]

Type

A type, used to characterize the problem and allow for routing within an error handler.

#[error.errorType]

Cause

The underlying Java Throwable that resulted in the failure.

#[error.cause]

Message

An optional Mule message about the problem.

#[error.errorMessage]

Child Errors

An optional collection of inner errors, used by elements like Scatter-Gather to provide aggregated route errors.

#[error.childErrors]

> [!CAUTION] In most cases, the `error.cause` selector returns a `Throwable` instance that is part > of the Mule API. Do not access the error’s internal structure to define error handling logic. The > other selectors expose all the necessary information to handle errors. Also, serializing the > `error.cause` might result in redundant information. ### HTTP Request Error Example For example, when an HTTP request fails with an `HTTP:NOT_FOUND` error (for a 404 status code), the values for each part of the Error Message are: - `#[error.description]` returns: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404). ``` - `#[error.detailedDescription]` returns `HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404).` - `#[error.errorType]` returns `HTTP:NOT_FOUND` - `#[error.cause]` returns `org.mule.extension.http.api.request.validator.ResponseValidatorTypedException`. If you print the return instance of `ResponseValidatorTypedException`, Mule prints the result of `toString`. When the error has an associated known HTTP status code (such as 404), the string representation of the `ResponseValidatorTypedException` instance is a human-readable description of the error. - `#[error.errorMessage]` returns: ```txt org.mule.runtime.core.internal.message.DefaultMessageBuilder$MessageImplementation { payload=org.mule.runtime.core.internal.streaming.bytes.ManagedCursorStreamProvider@223d8f75 mediaType=application/json; charset=UTF-8 attributes=org.mule.extension.http.api.HttpResponseAttributes { Status Code=404 Reason Phrase=Not Found Headers=[ date=Sat, 03 Aug 2019 04:28:29 GMT content-type=application/json; charset=utf-8 content-length=2 connection=keep-alive set-cookie=__cfduid=de19ed0b495b5b58e74fa0ee31a700d651564806509; expires=Sun, 02-Aug-20 04:28:29 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 pragma=no-cache expires=Sat, 03 Aug 2019 08:28:29 GMT x-content-type-options=nosniff etag=W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8" via=1.1 vegur cf-cache-status=HIT age=96 server=cloudflare cf-ray=50058b8add0a92fe-SJC ] } attributesMediaType=*/* } ``` The `errorMessage` element becomes available when a connector or component exposes the message that it has interpreted as an error. For example, when an HTTP request receives a status code that Mule treats as an error, the process fails and also populates the `errorMessage` with information about the error. You can then gain access to error message attributes (metadata) and to the payload itself with `#[error.errorMessage.payload]` for the payload and `#[error.errorMessage.attributes]` for the metadata. In the case of an HTTP request that returns an error, you can then use `#[error.errorMessage.attributes.statusCode]` to select the value of the status code (such as `404`). To see message attributes in Studio, see [DataSense](https://docs.mulesoft.com/studio/datasense-concept). - `#[error.childErrors]` returns: `[]` ## Mule Error Types Mule errors have a namespace (such as `HTTP:` and `FILE:`) and identifier (such as `NOT_FOUND`), and they belong to a hierarchy of error types. The naming convention enables you to distinguish errors according to their domain. For example, instead of throwing `NOT_FOUND`, the HTTP connector can throw `HTTP:NOT_FOUND`, and the File connector can throw `FILE:NOT_FOUND` errors. Unlike connectors, Mule runtime errors have an implicit `MULE` namespace, so `MULE:EXPRESSION` and `EXPRESSION` are interpreted the same way. Error types can have a parent type. For example, the parent of `HTTP:UNAUTHORIZED` is `MULE:CLIENT_SECURITY`, and the parent of `MULE:CLIENT_SECURITY` is `MULE:SECURITY`. This hierarchy implies that each error type is a specification of more global error type. For example, an `HTTP:UNAUTHORIZED` error type is a type of client security error (`MULE:CLIENT_SECURITY`), which is a type of a more broad security issue (`MULE:SECURITY`). The hierarchies enable you to route errors in a general or more specific way. For example, an error handler for `MULE:SECURITY` catches `HTTP:UNAUTHORIZED` errors and OAuth errors. The follow figure shows the core runtime hierarchy: ![Error Hierarchy](/mulesoft/current/en-us/mule-runtime/4.3/_images/error-hierarchy.png) All errors belong to one of these two main types: `ANY` or `CRITICAL`. Each type under `ANY` is matched by its parent and can be handled, while error types under `CRITICAL` are so severe that cannot be handled and are only logged. `CRITICAL` errors include `FATAL_JVM_ERROR` and `OVERLOAD`. Whenever there is no clear reason for a failure, a component can use the `UNKNOWN` type. You handle this error through the `ANY` type to define unclear errors, without changing the existing behavior of the app. For connectors, each connector defines its error type hierarchy considering the core runtime hierarchy, though `CONNECTIVITY` and `RETRY_EXHAUSTED` types are always present because they are common to all connectors. Error Types: - `ANY`: error type that matches all error types that occur in a Flow and can be handled. This type does not include errors that occur on the source. - `TRANSFORMATION`: indicates an error occurred while transforming a value. This involves Mule Runtime internal transformations and not DataWeave transformations. - `EXPRESSION`: indicates an error occurred while evaluating a DataWeave expression. - `VALIDATION`: indicates a validation error occurred. - `DUPLICATE_MESSAGE`: indicates a validation error regarding a message being processed twice. For example, using the [Idempotent message validator](https://docs.mulesoft.com/mule-runtime/4.3/idempotent-message-validator). - `REDELIVERY_EXHAUSTED`: indicates that max attempts to reprocess a message from a source have been exhausted. - `CONNECTIVITY`: indicates that there was a problem establishing a connection. This could occur while using a connector, for example, an HTTP requester. - `RETRY_EXHAUSTED`: indicates that retries of a certain execution block have been exhausted. For example, for a given operation, or using [Until Successful Scope](https://docs.mulesoft.com/mule-runtime/4.3/until-successful-scope). - `ROUTING`: indicates an error occurred while routing a message. For example, using the [Round Robin router](https://docs.mulesoft.com/mule-runtime/4.3/round-robin). - `COMPOSITE_ROUTING`: indicates that one or more errors occurred while routing a message. For example, using a [Scatter Gather Router](https://docs.mulesoft.com/mule-runtime/4.3/scatter-gather-concept). - `SECURITY`: indicates a security error occurred, like invalid credentials being received or an expired token being used. - `CLIENT_SECURITY`: indicates an external entity (e.g., calling an external endpoint) produced a security error. - `SERVER_SECURITY`: indicates a security error enforced by the Mule Runtime. - `NOT_PERMITTED`: indicates a security restriction enforced by a filter. For example, using [the Authorization Filter of the Mule Spring Module](https://docs.mulesoft.com/spring-module/latest/#_to_validate_authentication_using_the_spring_authorization_filter). - `STREAM_MAXIMUM_SIZE_EXCEEDED`: indicates the maximum size allowed for a stream has been exceeded. For more insight, see [Streaming in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.3/streaming-about). - `TIMEOUT`: indicates timeout occurred while processing a message. - `UNKNOWN`: indicates an unknown or unexpected error occurred. This cannot be handled directly, only by handling `ANY`, to ensure backward compatibility in case more error types are added in future runtime versions. - `SOURCE`: indicates that an error occurred in the source of the flow. These errors cannot be handled. - `SOURCE_ERROR_RESPONSE_GENERATE`: indicates that an error occurred in the source of the flow generating the parameters of an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_ERROR_RESPONSE_SEND`: indicates that an error occurred in the source of the flow sending an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_RESPONSE`: indicates that an error occurred in the source of a flow while processing a successful response. These errors can only be propagated since the source has already executed the successful path. These errors cannot be handled. - `SOURCE_RESPONSE_GENERATE`: indicates an error occurred in the source of the flow while generating the parameters of a successful response. - `SOURCE_RESPONSE_SEND`: indicates an error occurred in the source of the flow while sending a successful response. - `CRITICAL`: indicates a severe error occurred. These errors cannot be handled. - `OVERLOAD`: indicates a problem of overloading occurred and the execution was rejected. - `FLOW_BACK_PRESSURE`: indicates a problem of overloading occurred at the source level. For example, using an HTTP listener as a source. - `FATAL_JVM_ERROR`: indicates that a fatal error occurred, such as stack overflow. ## Custom Error Types To use custom error types, you need to define them either when mapping or when [raising](https://docs.mulesoft.com/mule-runtime/4.3/raise-error-component-reference) the errors. These errors require a specific custom namespace to distinguish them from other existing types within an application. This means that an app that uses HTTP and Database connector operations cannot use the HTTP and DB namespaces for custom error types. You need to define namespaces that are related to the particular Mule app name or context and avoid using existing connector namespaces. For example, a customer aggregation API might use the `CUSTOMER` namespace for its custom error types, and an order-processing API might use the `ORDER` namespace. ## Error Mappings In each operation of your flow, you can map the possible error types to a custom error type of your choosing. You can use these custom error types to differentiate where an error occurred in your flow. For example, if your flow has two HTTP Request operations that reach out to different REST services, a connectivity failure on either produces the same error. By mapping each error to different custom error types, you can differentiate the error handling of each operation failure and quickly identify the source of the error in the Mule app logs. In the following example, you can see how mappings allow granular error handling by defining two custom error types: `APP:CUSTOMER_API` and `APP:ORDER_API`. Example XML Configuration for Mappings: ```xml ``` ## See Also - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.3/on-error-scope-concept) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/4.3/logging-and-debugging) --- product: Mule Runtime version: 4.4 --- # Mule Errors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule execution failures result in an error. When a Mule app is running, both the Mule runtime engine and the module and connector operations configured in the app can throw errors that are represented by a Mule error object, which is associated with a Mule event. You can handle error objects with On-Error components and find information about them in the logs. Mule errors are grouped into [error types](#error_types) that follow a hierarchical order and use a naming convention that helps you identify the source of the error and handle the error at the level you choose. You can also create custom error types that you map to these errors. The mappings can help you further differentiate and group errors that you need to handle in your app. To inspect and use values of Mule errors in your error handling configurations, you can also use [selector expressions](#selector_expressions). Mule errors include expression (`EXPRESSION`) and stream-related errors (`STREAM_MAXIMUM_SIZE_EXCEEDED`), while the operations can throw many different types of errors. Examples include `HTTP:NOT_FOUND` (a 404 error) and `HTTP:CONNECTIVITY` errors from the HTTP listener in the HTTP connector. `DB:BAD_SYNTAX` and `DB:QUERY_EXPRESSION` are errors that the Select operation in the Database connector can throw. The reference documentation for modules and connectors (for example, the [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) and [Database Connector](https://docs.mulesoft.com/db-connector/latest/database-documentation) references) lists Mule errors. ## Selector Expressions for Mule Errors Mule errors are complex data types with several fields, such as a description and type. When logging and handling Mule errors, can select the values from any number of the error fields.
FieldDescriptionSelector Expression

Description

A description of the problem.

#[error.description]

Detailed Description

A description of the problem, which can be the same or more extensive than the description.

#[error.detailedDescription]

Type

A type, used to characterize the problem and allow for routing within an error handler.

#[error.errorType]

Cause

The underlying Java Throwable that resulted in the failure.

#[error.cause]

Message

An optional Mule message about the problem.

#[error.errorMessage]

Child Errors

An optional collection of inner errors, used by elements like Scatter-Gather to provide aggregated route errors.

#[error.childErrors]

> [!CAUTION] In most cases, the `error.cause` selector returns a `Throwable` instance that is part > of the Mule API. Do not access the error’s internal structure to define error handling logic. The > other selectors expose all the necessary information to handle errors. Also, serializing the > `error.cause` might result in redundant information. ### HTTP Request Error Example For example, when an HTTP request fails with an `HTTP:NOT_FOUND` error (for a 404 status code), the values for each part of the Error Message are: - `#[error.description]` returns: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404). ``` - `#[error.detailedDescription]` returns `HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404).` - `#[error.errorType]` returns `HTTP:NOT_FOUND` - `#[error.cause]` returns `org.mule.extension.http.api.request.validator.ResponseValidatorTypedException`. If you print the return instance of `ResponseValidatorTypedException`, Mule prints the result of `toString`. When the error has an associated known HTTP status code (such as 404), the string representation of the `ResponseValidatorTypedException` instance is a human-readable description of the error. - `#[error.errorMessage]` returns: ```txt org.mule.runtime.core.internal.message.DefaultMessageBuilder$MessageImplementation { payload=org.mule.runtime.core.internal.streaming.bytes.ManagedCursorStreamProvider@223d8f75 mediaType=application/json; charset=UTF-8 attributes=org.mule.extension.http.api.HttpResponseAttributes { Status Code=404 Reason Phrase=Not Found Headers=[ date=Sat, 03 Aug 2019 04:28:29 GMT content-type=application/json; charset=utf-8 content-length=2 connection=keep-alive set-cookie=__cfduid=de19ed0b495b5b58e74fa0ee31a700d651564806509; expires=Sun, 02-Aug-20 04:28:29 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 pragma=no-cache expires=Sat, 03 Aug 2019 08:28:29 GMT x-content-type-options=nosniff etag=W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8" via=1.1 vegur cf-cache-status=HIT age=96 server=cloudflare cf-ray=50058b8add0a92fe-SJC ] } attributesMediaType=*/* } ``` The `errorMessage` element becomes available when a connector or component exposes the message that it has interpreted as an error. For example, when an HTTP request receives a status code that Mule treats as an error, the process fails and also populates the `errorMessage` with information about the error. You can then gain access to error message attributes (metadata) and to the payload itself with `#[error.errorMessage.payload]` for the payload and `#[error.errorMessage.attributes]` for the metadata. In the case of an HTTP request that returns an error, you can then use `#[error.errorMessage.attributes.statusCode]` to select the value of the status code (such as `404`). To see message attributes in Studio, see [DataSense](https://docs.mulesoft.com/studio/datasense-concept). - `#[error.childErrors]` returns: `[]` ## Mule Error Types Mule errors have a namespace (such as `HTTP:` and `FILE:`) and identifier (such as `NOT_FOUND`), and they belong to a hierarchy of error types. The naming convention enables you to distinguish errors according to their domain. For example, instead of throwing `NOT_FOUND`, the HTTP connector can throw `HTTP:NOT_FOUND`, and the File connector can throw `FILE:NOT_FOUND` errors. Unlike connectors, Mule runtime errors have an implicit `MULE` namespace, so `MULE:EXPRESSION` and `EXPRESSION` are interpreted the same way. Error types can have a parent type. For example, the parent of `HTTP:UNAUTHORIZED` is `MULE:CLIENT_SECURITY`, and the parent of `MULE:CLIENT_SECURITY` is `MULE:SECURITY`. This hierarchy implies that each error type is a specification of more global error type. For example, an `HTTP:UNAUTHORIZED` error type is a type of client security error (`MULE:CLIENT_SECURITY`), which is a type of a more broad security issue (`MULE:SECURITY`). The hierarchies enable you to route errors in a general or more specific way. For example, an error handler for `MULE:SECURITY` catches `HTTP:UNAUTHORIZED` errors and OAuth errors. The follow figure shows the core runtime hierarchy: ![Error Hierarchy](/mulesoft/current/en-us/mule-runtime/4.4/_images/error-hierarchy.png) All errors belong to one of these two main types: `ANY` or `CRITICAL`. Each type under `ANY` is matched by its parent and can be handled, while error types under `CRITICAL` are so severe that cannot be handled and are only logged. `CRITICAL` errors include `FATAL_JVM_ERROR` and `OVERLOAD`. Whenever there is no clear reason for a failure, a component can use the `UNKNOWN` type. You handle this error through the `ANY` type to define unclear errors, without changing the existing behavior of the app. For connectors, each connector defines its error type hierarchy considering the core runtime hierarchy, though `CONNECTIVITY` and `RETRY_EXHAUSTED` types are always present because they are common to all connectors. Error Types: - `ANY`: error type that matches all error types that occur in a Flow and can be handled. This type does not include errors that occur on the source. - `TRANSFORMATION`: indicates an error occurred while transforming a value. This involves Mule Runtime internal transformations and not DataWeave transformations. - `EXPRESSION`: indicates an error occurred while evaluating a DataWeave expression. - `VALIDATION`: indicates a validation error occurred. - `DUPLICATE_MESSAGE`: indicates a validation error regarding a message being processed twice. For example, using the [Idempotent message validator](https://docs.mulesoft.com/mule-runtime/4.4/idempotent-message-validator). - `REDELIVERY_EXHAUSTED`: indicates that max attempts to reprocess a message from a source have been exhausted. - `CONNECTIVITY`: indicates that there was a problem establishing a connection. This could occur while using a connector, for example, an HTTP requester. - `RETRY_EXHAUSTED`: indicates that retries of a certain execution block have been exhausted. For example, for a given operation, or using [Until Successful Scope](https://docs.mulesoft.com/mule-runtime/4.4/until-successful-scope). - `ROUTING`: indicates an error occurred while routing a message. For example, using the [Round Robin router](https://docs.mulesoft.com/mule-runtime/4.4/round-robin). - `COMPOSITE_ROUTING`: indicates that one or more errors occurred while routing a message. For example, using a [Scatter Gather Router](https://docs.mulesoft.com/mule-runtime/4.4/scatter-gather-concept). - `SECURITY`: indicates a security error occurred, like invalid credentials being received or an expired token being used. - `CLIENT_SECURITY`: indicates an external entity (e.g., calling an external endpoint) produced a security error. - `SERVER_SECURITY`: indicates a security error enforced by the Mule Runtime. - `NOT_PERMITTED`: indicates a security restriction enforced by a filter. For example, using [the Authorization Filter of the Mule Spring Module](https://docs.mulesoft.com/spring-module/latest/#_to_validate_authentication_using_the_spring_authorization_filter). - `STREAM_MAXIMUM_SIZE_EXCEEDED`: indicates the maximum size allowed for a stream has been exceeded. For more insight, see [Streaming in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.4/streaming-about). - `TIMEOUT`: indicates timeout occurred while processing a message. - `UNKNOWN`: indicates an unknown or unexpected error occurred. This cannot be handled directly, only by handling `ANY`, to ensure backward compatibility in case more error types are added in future runtime versions. - `SOURCE`: indicates that an error occurred in the source of the flow. These errors cannot be handled. - `SOURCE_ERROR_RESPONSE_GENERATE`: indicates that an error occurred in the source of the flow generating the parameters of an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_ERROR_RESPONSE_SEND`: indicates that an error occurred in the source of the flow sending an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_RESPONSE`: indicates that an error occurred in the source of a flow while processing a successful response. These errors can only be propagated since the source has already executed the successful path. These errors cannot be handled. - `SOURCE_RESPONSE_GENERATE`: indicates an error occurred in the source of the flow while generating the parameters of a successful response. - `SOURCE_RESPONSE_SEND`: indicates an error occurred in the source of the flow while sending a successful response. - `CRITICAL`: indicates a severe error occurred. These errors cannot be handled. - `OVERLOAD`: indicates a problem of overloading occurred and the execution was rejected. - `FLOW_BACK_PRESSURE`: indicates a problem of overloading occurred at the source level. For example, using an HTTP listener as a source. - `FATAL_JVM_ERROR`: indicates that a fatal error occurred, such as stack overflow. ## Custom Error Types To use custom error types, you need to define them either when mapping or when [raising](https://docs.mulesoft.com/mule-runtime/4.4/raise-error-component-reference) the errors. These errors require a specific custom namespace to distinguish them from other existing types within an application. This means that an app that uses HTTP and Database connector operations cannot use the HTTP and DB namespaces for custom error types. You need to define namespaces that are related to the particular Mule app name or context and avoid using existing connector namespaces. For example, a customer aggregation API might use the `CUSTOMER` namespace for its custom error types, and an order-processing API might use the `ORDER` namespace. ## Error Mappings In each operation of your flow, you can map the possible error types to a custom error type of your choosing. You can use these custom error types to differentiate where an error occurred in your flow. For example, if your flow has two HTTP Request operations that reach out to different REST services, a connectivity failure on either produces the same error. By mapping each error to different custom error types, you can differentiate the error handling of each operation failure and quickly identify the source of the error in the Mule app logs. In the following example, you can see how mappings allow granular error handling by defining two custom error types: `APP:CUSTOMER_API` and `APP:ORDER_API`. Example XML Configuration for Mappings: ```xml ``` ## See Also - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.4/on-error-scope-concept) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/4.4/logging-and-debugging) --- product: Mule Runtime version: 4.6 --- # Mule Errors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule execution failures result in an error. When a Mule app is running, both the Mule runtime engine and the module and connector operations configured in the app can throw errors that are represented by a Mule error object, which is associated with a Mule event. You can handle error objects with On-Error components and find information about them in the logs. Mule errors are grouped into [error types](#error_types) that follow a hierarchical order and use a naming convention that helps you identify the source of the error and handle the error at the level you choose. You can also create custom error types that you map to these errors. The mappings can help you further differentiate and group errors that you need to handle in your app. To inspect and use values of Mule errors in your error handling configurations, you can also use [selector expressions](#selector_expressions). Mule errors include expression (`EXPRESSION`) and stream-related errors (`STREAM_MAXIMUM_SIZE_EXCEEDED`), while the operations can throw many different types of errors. Examples include `HTTP:NOT_FOUND` (a 404 error) and `HTTP:CONNECTIVITY` errors from the HTTP listener in the HTTP connector. `DB:BAD_SYNTAX` and `DB:QUERY_EXPRESSION` are errors that the Select operation in the Database connector can throw. The reference documentation for modules and connectors (for example, the [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) and [Database Connector](https://docs.mulesoft.com/db-connector/latest/database-documentation) references) lists Mule errors. ## Selector Expressions for Mule Errors Mule errors are complex data types with several fields, such as a description and type. When logging and handling Mule errors, can select the values from any number of the error fields.
FieldDescriptionSelector Expression

Description

A description of the problem.

#[error.description]

Detailed Description

A description of the problem, which can be the same or more extensive than the description.

#[error.detailedDescription]

Type

A type, used to characterize the problem and allow for routing within an error handler.

#[error.errorType]

Cause

The underlying Java Throwable that resulted in the failure.

#[error.cause]

Message

An optional Mule message about the problem.

#[error.errorMessage]

Child Errors

An optional collection of inner errors, used by elements like Scatter-Gather to provide aggregated route errors.

#[error.childErrors]

> [!CAUTION] In most cases, the `error.cause` selector returns a `Throwable` instance that is part > of the Mule API. Do not access the error’s internal structure to define error handling logic. The > other selectors expose all the necessary information to handle errors. Also, serializing the > `error.cause` might result in redundant information. ### HTTP Request Error Example For example, when an HTTP request fails with an `HTTP:NOT_FOUND` error (for a 404 status code), the values for each part of the Error Message are: - `#[error.description]` returns: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404). ``` - `#[error.detailedDescription]` returns `HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404).` - `#[error.errorType]` returns `HTTP:NOT_FOUND` - `#[error.cause]` returns `org.mule.extension.http.api.request.validator.ResponseValidatorTypedException`. If you print the return instance of `ResponseValidatorTypedException`, Mule prints the result of `toString`. When the error has an associated known HTTP status code (such as 404), the string representation of the `ResponseValidatorTypedException` instance is a human-readable description of the error. - `#[error.errorMessage]` returns: ```txt org.mule.runtime.core.internal.message.DefaultMessageBuilder$MessageImplementation { payload=org.mule.runtime.core.internal.streaming.bytes.ManagedCursorStreamProvider@223d8f75 mediaType=application/json; charset=UTF-8 attributes=org.mule.extension.http.api.HttpResponseAttributes { Status Code=404 Reason Phrase=Not Found Headers=[ date=Sat, 03 Aug 2019 04:28:29 GMT content-type=application/json; charset=utf-8 content-length=2 connection=keep-alive set-cookie=__cfduid=de19ed0b495b5b58e74fa0ee31a700d651564806509; expires=Sun, 02-Aug-20 04:28:29 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 pragma=no-cache expires=Sat, 03 Aug 2019 08:28:29 GMT x-content-type-options=nosniff etag=W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8" via=1.1 vegur cf-cache-status=HIT age=96 server=cloudflare cf-ray=50058b8add0a92fe-SJC ] } attributesMediaType=*/* } ``` The `errorMessage` element becomes available when a connector or component exposes the message that it has interpreted as an error. For example, when an HTTP request receives a status code that Mule treats as an error, the process fails and also populates the `errorMessage` with information about the error. You can then gain access to error message attributes (metadata) and to the payload itself with `#[error.errorMessage.payload]` for the payload and `#[error.errorMessage.attributes]` for the metadata. In the case of an HTTP request that returns an error, you can then use `#[error.errorMessage.attributes.statusCode]` to select the value of the status code (such as `404`). To see message attributes in Studio, see [DataSense](https://docs.mulesoft.com/studio/datasense-concept). - `#[error.childErrors]` returns: `[]` ## Mule Error Types Mule errors have a namespace (such as `HTTP:` and `FILE:`) and identifier (such as `NOT_FOUND`), and they belong to a hierarchy of error types. The naming convention enables you to distinguish errors according to their domain. For example, instead of throwing `NOT_FOUND`, the HTTP connector can throw `HTTP:NOT_FOUND`, and the File connector can throw `FILE:NOT_FOUND` errors. Unlike connectors, Mule runtime errors have an implicit `MULE` namespace, so `MULE:EXPRESSION` and `EXPRESSION` are interpreted the same way. Error types can have a parent type. For example, the parent of `HTTP:UNAUTHORIZED` is `MULE:CLIENT_SECURITY`, and the parent of `MULE:CLIENT_SECURITY` is `MULE:SECURITY`. This hierarchy implies that each error type is a specification of more global error type. For example, an `HTTP:UNAUTHORIZED` error type is a type of client security error (`MULE:CLIENT_SECURITY`), which is a type of a more broad security issue (`MULE:SECURITY`). The hierarchies enable you to route errors in a general or more specific way. For example, an error handler for `MULE:SECURITY` catches `HTTP:UNAUTHORIZED` errors and OAuth errors. The follow figure shows the core runtime hierarchy: ![Error Hierarchy](/mulesoft/current/en-us/mule-runtime/4.6/_images/error-hierarchy.png) All errors belong to one of these two main types: `ANY` or `CRITICAL`. Each type under `ANY` is matched by its parent and can be handled, while error types under `CRITICAL` are so severe that cannot be handled and are only logged. `CRITICAL` errors include `FATAL_JVM_ERROR` and `OVERLOAD`. Whenever there is no clear reason for a failure, a component can use the `UNKNOWN` type. You handle this error through the `ANY` type to define unclear errors, without changing the existing behavior of the app. For connectors, each connector defines its error type hierarchy considering the core runtime hierarchy, though `CONNECTIVITY` and `RETRY_EXHAUSTED` types are always present because they are common to all connectors. Error Types: - `ANY`: error type that matches all error types that occur in a Flow and can be handled. This type does not include errors that occur on the source. - `TRANSFORMATION`: indicates an error occurred while transforming a value. This involves Mule runtime internal transformations and not DataWeave transformations. - `EXPRESSION`: indicates an error occurred while evaluating a DataWeave expression. - `VALIDATION`: indicates a validation error occurred. - `DUPLICATE_MESSAGE`: indicates a validation error regarding a message being processed twice. For example, using the [Idempotent message validator](https://docs.mulesoft.com/mule-runtime/4.6/idempotent-message-validator). - `REDELIVERY_EXHAUSTED`: indicates that max attempts to reprocess a message from a source have been exhausted. - `CONNECTIVITY`: indicates that there was a problem establishing a connection. This could occur while using a connector, for example, an HTTP requester. - `RETRY_EXHAUSTED`: indicates that retries of a certain execution block have been exhausted. For example, for a given operation, or using [Until Successful Scope](https://docs.mulesoft.com/mule-runtime/4.6/until-successful-scope). - `ROUTING`: indicates an error occurred while routing a message. For example, using the [Round Robin router](https://docs.mulesoft.com/mule-runtime/4.6/round-robin). - `COMPOSITE_ROUTING`: indicates that one or more errors occurred while routing a message. For example, using a [Scatter Gather Router](https://docs.mulesoft.com/mule-runtime/4.6/scatter-gather-concept). - `SECURITY`: indicates a security error occurred, like invalid credentials being received or an expired token being used. - `CLIENT_SECURITY`: indicates an external entity (e.g., calling an external endpoint) produced a security error. - `SERVER_SECURITY`: indicates a security error enforced by the Mule runtime. - `NOT_PERMITTED`: indicates a security restriction enforced by a filter. For example, using [the Authorization Filter of the Mule Spring Module](https://docs.mulesoft.com/spring-module/latest/#_to_validate_authentication_using_the_spring_authorization_filter). - `STREAM_MAXIMUM_SIZE_EXCEEDED`: indicates the maximum size allowed for a stream has been exceeded. For more insight, see [Streaming in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.6/streaming-about). - `TIMEOUT`: indicates timeout occurred while processing a message. - `UNKNOWN`: indicates an unknown or unexpected error occurred. This cannot be handled directly, only by handling `ANY`, to ensure backward compatibility in case more error types are added in future runtime versions. - `SOURCE`: indicates that an error occurred in the source of the flow. These errors cannot be handled. - `SOURCE_ERROR_RESPONSE_GENERATE`: indicates that an error occurred in the source of the flow generating the parameters of an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_ERROR_RESPONSE_SEND`: indicates that an error occurred in the source of the flow sending an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_RESPONSE`: indicates that an error occurred in the source of a flow while processing a successful response. These errors can only be propagated since the source has already executed the successful path. These errors cannot be handled. - `SOURCE_RESPONSE_GENERATE`: indicates an error occurred in the source of the flow while generating the parameters of a successful response. - `SOURCE_RESPONSE_SEND`: indicates an error occurred in the source of the flow while sending a successful response. - `CRITICAL`: indicates a severe error occurred. These errors cannot be handled. - `OVERLOAD`: indicates a problem of overloading occurred and the execution was rejected. - `FLOW_BACK_PRESSURE`: indicates a problem of overloading occurred at the source level. For example, using an HTTP listener as a source. - `FATAL_JVM_ERROR`: indicates that a fatal error occurred, such as stack overflow. ### What Happens After a FATAL\_JVM\_ERROR When the JVM throws a `VirtualMachineError` (for example, `OutOfMemoryError` or `StackOverflowError`), Mule runtime wraps it as a `MULE:FATAL` error and raises a `FATAL_ERROR_RAISED` alert. Because these errors are in the `CRITICAL` hierarchy, On-Error components (`on-error-continue`, `on-error-propagate`) can’t handle them. After a `VirtualMachineError` occurs, the Mule runtime instance, its internal components, or the underlying JVM can remain in an invalid state. Memory can be corrupted, threads can enter undefined states, and further message processing is unreliable. > [!IMPORTANT] The only safe recovery action after a `VirtualMachineError` occurs is to restart the > Mule runtime instance. Don’t assume that the application can continue processing correctly after > encountering one of these errors. #### Common Causes
ErrorCommon Causes

OutOfMemoryError

Unbounded in-memory caching, unconsumed streams that accumulate buffers, processing very large payloads without streaming, or memory leaks in custom Java code.

StackOverflowError

Extremely long flows that create deeply nested Reactor operator stacks, or unbounded recursion in custom Java components or DataWeave expressions. Recursive flow references (a flow calling itself through flow-ref) are protected by Mule runtime internal nesting limit, which raises an EventContextDeepNestingException before a JVM stack overflow occurs.

#### Monitoring and Recovery - Monitor application logs for messages containing `VirtualMachineError`, `OutOfMemoryError`, or `StackOverflowError`. - In managed deployment targets (CloudHub, Runtime Fabric), configure health checks and automatic restarts so that affected instances are replaced quickly. - For on-premises deployments, configure your process supervisor (systemd, Tanuki wrapper) to restart the Mule process if it becomes unresponsive. - After a restart, investigate the root cause by using heap dumps (for `OutOfMemoryError`) or thread dumps (for `StackOverflowError`) captured before the failure occurs. For design patterns that help prevent these errors, see [Avoid Recursive Flow References](https://docs.mulesoft.com/mule-runtime/4.6/tuning-app-design#avoid-recursive-flow-references) and [Consume Streams Promptly](https://docs.mulesoft.com/mule-runtime/4.6/streaming-about#consume-streams-promptly). ## Custom Error Types To use custom error types, you need to define them either when mapping or when [raising](https://docs.mulesoft.com/mule-runtime/4.6/raise-error-component-reference) the errors. These errors require a specific custom namespace to distinguish them from other existing types within an application. This means that an app that uses HTTP and Database connector operations cannot use the HTTP and DB namespaces for custom error types. You need to define namespaces that are related to the particular Mule app name or context and avoid using existing connector namespaces. For example, a customer aggregation API might use the `CUSTOMER` namespace for its custom error types, and an order-processing API might use the `ORDER` namespace. ## Error Mappings In each operation of your flow, you can map the possible error types to a custom error type of your choosing. You can use these custom error types to differentiate where an error occurred in your flow. For example, if your flow has two HTTP Request operations that reach out to different REST services, a connectivity failure on either produces the same error. By mapping each error to different custom error types, you can differentiate the error handling of each operation failure and quickly identify the source of the error in the Mule app logs. In the following example, you can see how mappings allow granular error handling by defining two custom error types: `APP:CUSTOMER_API` and `APP:ORDER_API`. Example XML Configuration for Mappings: ```xml ``` ## See Also - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.6/on-error-scope-concept) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/4.6/logging-and-debugging) --- product: Mule Runtime version: 4.9 --- # Mule Errors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule execution failures result in an error. When a Mule app is running, both the Mule runtime engine and the module and connector operations configured in the app can throw errors that are represented by a Mule error object, which is associated with a Mule event. You can handle error objects with On-Error components and find information about them in the logs. Mule errors are grouped into [error types](#error_types) that follow a hierarchical order and use a naming convention that helps you identify the source of the error and handle the error at the level you choose. You can also create custom error types that you map to these errors. The mappings can help you further differentiate and group errors that you need to handle in your app. To inspect and use values of Mule errors in your error handling configurations, you can also use [selector expressions](#selector_expressions). Mule errors include expression (`EXPRESSION`) and stream-related errors (`STREAM_MAXIMUM_SIZE_EXCEEDED`), while the operations can throw many different types of errors. Examples include `HTTP:NOT_FOUND` (a 404 error) and `HTTP:CONNECTIVITY` errors from the HTTP listener in the HTTP connector. `DB:BAD_SYNTAX` and `DB:QUERY_EXPRESSION` are errors that the Select operation in the Database connector can throw. The reference documentation for modules and connectors (for example, the [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) and [Database Connector](https://docs.mulesoft.com/db-connector/latest/database-documentation) references) lists Mule errors. ## Selector Expressions for Mule Errors Mule errors are complex data types with several fields, such as a description and type. When logging and handling Mule errors, can select the values from any number of the error fields.
FieldDescriptionSelector Expression

Description

A description of the problem.

#[error.description]

Detailed Description

A description of the problem, which can be the same or more extensive than the description.

#[error.detailedDescription]

Type

A type, used to characterize the problem and allow for routing within an error handler.

#[error.errorType]

Cause

The underlying Java Throwable that resulted in the failure.

#[error.cause]

Message

An optional Mule message about the problem.

#[error.errorMessage]

Child Errors

An optional collection of inner errors, used by elements like Scatter-Gather to provide aggregated route errors.

#[error.childErrors]

> [!IMPORTANT] In most cases, the `error.cause` selector returns a `Throwable` instance that is part > of the Mule API. Do not access the error’s internal structure to define error handling logic. The > other selectors expose all the necessary information to handle errors. Also, serializing the > `error.cause` might result in redundant information. ### HTTP Request Error Example For example, when an HTTP request fails with an `HTTP:NOT_FOUND` error (for a 404 status code), the values for each part of the Error Message are: - `#[error.description]` returns: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404). ``` - `#[error.detailedDescription]` returns `HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404).` - `#[error.errorType]` returns `HTTP:NOT_FOUND` - `#[error.cause]` returns `org.mule.extension.http.api.request.validator.ResponseValidatorTypedException`. If you print the return instance of `ResponseValidatorTypedException`, Mule prints the result of `toString`. When the error has an associated known HTTP status code (such as 404), the string representation of the `ResponseValidatorTypedException` instance is a human-readable description of the error. - `#[error.errorMessage]` returns: ```txt org.mule.runtime.core.internal.message.DefaultMessageBuilder$MessageImplementation { payload=org.mule.runtime.core.internal.streaming.bytes.ManagedCursorStreamProvider@223d8f75 mediaType=application/json; charset=UTF-8 attributes=org.mule.extension.http.api.HttpResponseAttributes { Status Code=404 Reason Phrase=Not Found Headers=[ date=Sat, 03 Aug 2019 04:28:29 GMT content-type=application/json; charset=utf-8 content-length=2 connection=keep-alive set-cookie=__cfduid=de19ed0b495b5b58e74fa0ee31a700d651564806509; expires=Sun, 02-Aug-20 04:28:29 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 pragma=no-cache expires=Sat, 03 Aug 2019 08:28:29 GMT x-content-type-options=nosniff etag=W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8" via=1.1 vegur cf-cache-status=HIT age=96 server=cloudflare cf-ray=50058b8add0a92fe-SJC ] } attributesMediaType=*/* } ``` The `errorMessage` element becomes available when a connector or component exposes the message that it has interpreted as an error. For example, when an HTTP request receives a status code that Mule treats as an error, the process fails and also populates the `errorMessage` with information about the error. You can then gain access to error message attributes (metadata) and to the payload itself with `#[error.errorMessage.payload]` for the payload and `#[error.errorMessage.attributes]` for the metadata. In the case of an HTTP request that returns an error, you can then use `#[error.errorMessage.attributes.statusCode]` to select the value of the status code (such as `404`). To see message attributes in Studio, see [DataSense](https://docs.mulesoft.com/studio/datasense-concept). - `#[error.childErrors]` returns: `[]` ## Mule Error Types Mule errors have a namespace (such as `HTTP:` and `FILE:`) and identifier (such as `NOT_FOUND`), and they belong to a hierarchy of error types. The naming convention enables you to distinguish errors according to their domain. For example, instead of throwing `NOT_FOUND`, the HTTP connector can throw `HTTP:NOT_FOUND`, and the File connector can throw `FILE:NOT_FOUND` errors. Unlike connectors, Mule runtime errors have an implicit `MULE` namespace, so `MULE:EXPRESSION` and `EXPRESSION` are interpreted the same way. Error types can have a parent type. For example, the parent of `HTTP:UNAUTHORIZED` is `MULE:CLIENT_SECURITY`, and the parent of `MULE:CLIENT_SECURITY` is `MULE:SECURITY`. This hierarchy implies that each error type is a specification of more global error type. For example, an `HTTP:UNAUTHORIZED` error type is a type of client security error (`MULE:CLIENT_SECURITY`), which is a type of a more broad security issue (`MULE:SECURITY`). The hierarchies enable you to route errors in a general or more specific way. For example, an error handler for `MULE:SECURITY` catches `HTTP:UNAUTHORIZED` errors and OAuth errors. The follow figure shows the core runtime hierarchy: ![A hierarchy of error types showing categories including ANY and CRITICAL](/mulesoft/current/en-us/mule-runtime/4.9/_images/error-hierarchy.png) All errors belong to one of these two main types: `ANY` or `CRITICAL`. Each type under `ANY` is matched by its parent and can be handled, while error types under `CRITICAL` are so severe that cannot be handled and are only logged. `CRITICAL` errors include `FATAL_JVM_ERROR` and `OVERLOAD`. Whenever there is no clear reason for a failure, a component can use the `UNKNOWN` type. You handle this error through the `ANY` type to define unclear errors, without changing the existing behavior of the app. For connectors, each connector defines its error type hierarchy considering the core runtime hierarchy, though `CONNECTIVITY` and `RETRY_EXHAUSTED` types are always present because they are common to all connectors. Error Types: - `ANY`: error type that matches all error types that occur in a Flow and can be handled. This type does not include errors that occur on the source. - `TRANSFORMATION`: indicates an error occurred while transforming a value. This involves Mule runtime internal transformations and not DataWeave transformations. - `EXPRESSION`: indicates an error occurred while evaluating a DataWeave expression. - `VALIDATION`: indicates a validation error occurred. - `DUPLICATE_MESSAGE`: indicates a validation error regarding a message being processed twice. For example, using the [Idempotent message validator](https://docs.mulesoft.com/mule-runtime/4.9/idempotent-message-validator). - `REDELIVERY_EXHAUSTED`: indicates that max attempts to reprocess a message from a source have been exhausted. - `CONNECTIVITY`: indicates that there was a problem establishing a connection. This could occur while using a connector, for example, an HTTP requester. - `RETRY_EXHAUSTED`: indicates that retries of a certain execution block have been exhausted. For example, for a given operation, or using [Until Successful Scope](https://docs.mulesoft.com/mule-runtime/4.9/until-successful-scope). - `ROUTING`: indicates an error occurred while routing a message. For example, using the [Round Robin router](https://docs.mulesoft.com/mule-runtime/4.9/round-robin). - `COMPOSITE_ROUTING`: indicates that one or more errors occurred while routing a message. For example, using a [Scatter Gather Router](https://docs.mulesoft.com/mule-runtime/4.9/scatter-gather-concept). - `SECURITY`: indicates a security error occurred, like invalid credentials being received or an expired token being used. - `CLIENT_SECURITY`: indicates an external entity (e.g., calling an external endpoint) produced a security error. - `SERVER_SECURITY`: indicates a security error enforced by the Mule runtime. - `NOT_PERMITTED`: indicates a security restriction enforced by a filter. For example, using [the Authorization Filter of the Mule Spring Module](https://docs.mulesoft.com/spring-module/latest/#_to_validate_authentication_using_the_spring_authorization_filter). - `STREAM_MAXIMUM_SIZE_EXCEEDED`: indicates the maximum size allowed for a stream has been exceeded. For more insight, see [Streaming in Mule Apps](https://docs.mulesoft.com/mule-runtime/4.9/streaming-about). - `TIMEOUT`: indicates timeout occurred while processing a message. - `UNKNOWN`: indicates an unknown or unexpected error occurred. This cannot be handled directly, only by handling `ANY`, to ensure backward compatibility in case more error types are added in future runtime versions. - `SOURCE`: indicates that an error occurred in the source of the flow. These errors cannot be handled. - `SOURCE_ERROR_RESPONSE_GENERATE`: indicates that an error occurred in the source of the flow generating the parameters of an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_ERROR_RESPONSE_SEND`: indicates that an error occurred in the source of the flow sending an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_RESPONSE`: indicates that an error occurred in the source of a flow while processing a successful response. These errors can only be propagated since the source has already executed the successful path. These errors cannot be handled. - `SOURCE_RESPONSE_GENERATE`: indicates an error occurred in the source of the flow while generating the parameters of a successful response. - `SOURCE_RESPONSE_SEND`: indicates an error occurred in the source of the flow while sending a successful response. - `CRITICAL`: indicates a severe error occurred. These errors cannot be handled. - `OVERLOAD`: indicates a problem of overloading occurred and the execution was rejected. - `FLOW_BACK_PRESSURE`: indicates a problem of overloading occurred at the source level. For example, using an HTTP listener as a source. - `FATAL_JVM_ERROR`: indicates that a fatal error occurred, such as stack overflow. ### What Happens After a FATAL\_JVM\_ERROR When the JVM throws a `VirtualMachineError` (for example, `OutOfMemoryError` or `StackOverflowError`), Mule runtime wraps it as a `MULE:FATAL` error and raises a `FATAL_ERROR_RAISED` alert. Because these errors are in the `CRITICAL` hierarchy, On-Error components (`on-error-continue`, `on-error-propagate`) can’t handle them. After a `VirtualMachineError` occurs, the Mule runtime instance, its internal components, or the underlying JVM can remain in an invalid state. Memory can be corrupted, threads can enter undefined states, and further message processing is unreliable. > [!IMPORTANT] The only safe recovery action after a `VirtualMachineError` occurs is to restart the > Mule runtime instance. Don’t assume that the application can continue processing correctly after > encountering one of these errors. #### Common Causes
ErrorCommon Causes

OutOfMemoryError

Unbounded in-memory caching, unconsumed streams that accumulate buffers, processing very large payloads without streaming, or memory leaks in custom Java code.

StackOverflowError

Extremely long flows that create deeply nested Reactor operator stacks, or unbounded recursion in custom Java components or DataWeave expressions. Recursive flow references (a flow calling itself through flow-ref) are protected by Mule runtime internal nesting limit, which raises an EventContextDeepNestingException before a JVM stack overflow occurs.

#### Monitoring and Recovery - Monitor application logs for messages containing `VirtualMachineError`, `OutOfMemoryError`, or `StackOverflowError`. - In managed deployment targets (CloudHub, Runtime Fabric), configure health checks and automatic restarts so that affected instances are replaced quickly. - For on-premises deployments, configure your process supervisor (systemd, Tanuki wrapper) to restart the Mule process if it becomes unresponsive. - After a restart, investigate the root cause by using heap dumps (for `OutOfMemoryError`) or thread dumps (for `StackOverflowError`) captured before the failure occurs. For design patterns that help prevent these errors, see [Avoid Recursive Flow References](https://docs.mulesoft.com/mule-runtime/4.9/tuning-app-design#avoid-recursive-flow-references) and [Consume Streams Promptly](https://docs.mulesoft.com/mule-runtime/4.9/streaming-about#consume-streams-promptly). ## Custom Error Types To use custom error types, you need to define them either when mapping or when [raising](https://docs.mulesoft.com/mule-runtime/4.9/raise-error-component-reference) the errors. These errors require a specific custom namespace to distinguish them from other existing types within an application. This means that an app that uses HTTP and Database connector operations cannot use the HTTP and DB namespaces for custom error types. You need to define namespaces that are related to the particular Mule app name or context and avoid using existing connector namespaces. For example, a customer aggregation API might use the `CUSTOMER` namespace for its custom error types, and an order-processing API might use the `ORDER` namespace. ## Error Mappings In each operation of your flow, you can map the possible error types to a custom error type of your choosing. You can use these custom error types to differentiate where an error occurred in your flow. For example, if your flow has two HTTP Request operations that reach out to different REST services, a connectivity failure on either produces the same error. By mapping each error to different custom error types, you can differentiate the error handling of each operation failure and quickly identify the source of the error in the Mule app logs. In the following example, you can see how mappings allow granular error handling by defining two custom error types: `APP:CUSTOMER_API` and `APP:ORDER_API`. Example XML Configuration for Mappings: ```xml ``` ## See Also - [On-Error Components](https://docs.mulesoft.com/mule-runtime/4.9/on-error-scope-concept) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/4.9/logging-and-debugging) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Mule Errors > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule execution failures result in an error. When a Mule app is running, both the Mule runtime engine and the module and connector operations configured in the app can throw errors that are represented by a Mule error object, which is associated with a Mule event. You can handle error objects with On-Error components and find information about them in the logs. Mule errors are grouped into [error types](#error_types) that follow a hierarchical order and use a naming convention that helps you identify the source of the error and handle the error at the level you choose. You can also create custom error types that you map to these errors. The mappings can help you further differentiate and group errors that you need to handle in your app. To inspect and use values of Mule errors in your error handling configurations, you can also use [selector expressions](#selector_expressions). Mule errors include expression (`EXPRESSION`) and stream-related errors (`STREAM_MAXIMUM_SIZE_EXCEEDED`), while the operations can throw many different types of errors. Examples include `HTTP:NOT_FOUND` (a 404 error) and `HTTP:CONNECTIVITY` errors from the HTTP listener in the HTTP connector. `DB:BAD_SYNTAX` and `DB:QUERY_EXPRESSION` are errors that the Select operation in the Database connector can throw. The reference documentation for modules and connectors (for example, the [HTTP Connector](https://docs.mulesoft.com/http-connector/1.10/) and [Database Connector](https://docs.mulesoft.com/db-connector/latest/database-documentation) references) lists Mule errors. ## Selector Expressions for Mule Errors Mule errors are complex data types with several fields, such as a description and type. When logging and handling Mule errors, can select the values from any number of the error fields.
FieldDescriptionSelector Expression

Description

A description of the problem.

#[error.description]

Detailed Description

A description of the problem, which can be the same or more extensive than the description.

#[error.detailedDescription]

Type

A type, used to characterize the problem and allow for routing within an error handler.

#[error.errorType]

Cause

The underlying Java Throwable that resulted in the failure.

#[error.cause]

Message

An optional Mule message about the problem.

#[error.errorMessage]

Child Errors

An optional collection of inner errors, used by elements like Scatter-Gather to provide aggregated route errors.

#[error.childErrors]

> [!IMPORTANT] In most cases, the `error.cause` selector returns a `Throwable` instance that is part > of the Mule API. Do not access the error’s internal structure to define error handling logic. The > other selectors expose all the necessary information to handle errors. Also, serializing the > `error.cause` might result in redundant information. ### HTTP Request Error Example For example, when an HTTP request fails with an `HTTP:NOT_FOUND` error (for a 404 status code), the values for each part of the Error Message are: - `#[error.description]` returns: ```txt HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404). ``` - `#[error.detailedDescription]` returns `HTTP GET on resource 'http://jsonplaceholder.typicode.com:80/mybadrequest' failed: not found (404).` - `#[error.errorType]` returns `HTTP:NOT_FOUND` - `#[error.cause]` returns `org.mule.extension.http.api.request.validator.ResponseValidatorTypedException`. If you print the return instance of `ResponseValidatorTypedException`, Mule prints the result of `toString`. When the error has an associated known HTTP status code (such as 404), the string representation of the `ResponseValidatorTypedException` instance is a human-readable description of the error. - `#[error.errorMessage]` returns: ```txt org.mule.runtime.core.internal.message.DefaultMessageBuilder$MessageImplementation { payload=org.mule.runtime.core.internal.streaming.bytes.ManagedCursorStreamProvider@223d8f75 mediaType=application/json; charset=UTF-8 attributes=org.mule.extension.http.api.HttpResponseAttributes { Status Code=404 Reason Phrase=Not Found Headers=[ date=Sat, 03 Aug 2019 04:28:29 GMT content-type=application/json; charset=utf-8 content-length=2 connection=keep-alive set-cookie=__cfduid=de19ed0b495b5b58e74fa0ee31a700d651564806509; expires=Sun, 02-Aug-20 04:28:29 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 pragma=no-cache expires=Sat, 03 Aug 2019 08:28:29 GMT x-content-type-options=nosniff etag=W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8" via=1.1 vegur cf-cache-status=HIT age=96 server=cloudflare cf-ray=50058b8add0a92fe-SJC ] } attributesMediaType=*/* } ``` The `errorMessage` element becomes available when a connector or component exposes the message that it has interpreted as an error. For example, when an HTTP request receives a status code that Mule treats as an error, the process fails and also populates the `errorMessage` with information about the error. You can then gain access to error message attributes (metadata) and to the payload itself with `#[error.errorMessage.payload]` for the payload and `#[error.errorMessage.attributes]` for the metadata. In the case of an HTTP request that returns an error, you can then use `#[error.errorMessage.attributes.statusCode]` to select the value of the status code (such as `404`). To see message attributes in Studio, see [DataSense](https://docs.mulesoft.com/studio/datasense-concept). - `#[error.childErrors]` returns: `[]` ## Mule Error Types Mule errors have a namespace (such as `HTTP:` and `FILE:`) and identifier (such as `NOT_FOUND`), and they belong to a hierarchy of error types. The naming convention enables you to distinguish errors according to their domain. For example, instead of throwing `NOT_FOUND`, the HTTP connector can throw `HTTP:NOT_FOUND`, and the File connector can throw `FILE:NOT_FOUND` errors. Unlike connectors, Mule runtime errors have an implicit `MULE` namespace, so `MULE:EXPRESSION` and `EXPRESSION` are interpreted the same way. Error types can have a parent type. For example, the parent of `HTTP:UNAUTHORIZED` is `MULE:CLIENT_SECURITY`, and the parent of `MULE:CLIENT_SECURITY` is `MULE:SECURITY`. This hierarchy implies that each error type is a specification of more global error type. For example, an `HTTP:UNAUTHORIZED` error type is a type of client security error (`MULE:CLIENT_SECURITY`), which is a type of a more broad security issue (`MULE:SECURITY`). The hierarchies enable you to route errors in a general or more specific way. For example, an error handler for `MULE:SECURITY` catches `HTTP:UNAUTHORIZED` errors and OAuth errors. The follow figure shows the core runtime hierarchy: ![A hierarchy of error types showing categories including ANY and CRITICAL](/mulesoft/current/en-us/mule-runtime/latest/_images/error-hierarchy.png) All errors belong to one of these two main types: `ANY` or `CRITICAL`. Each type under `ANY` is matched by its parent and can be handled, while error types under `CRITICAL` are so severe that cannot be handled and are only logged. `CRITICAL` errors include `FATAL_JVM_ERROR` and `OVERLOAD`. Whenever there is no clear reason for a failure, a component can use the `UNKNOWN` type. You handle this error through the `ANY` type to define unclear errors, without changing the existing behavior of the app. For connectors, each connector defines its error type hierarchy considering the core runtime hierarchy, though `CONNECTIVITY` and `RETRY_EXHAUSTED` types are always present because they are common to all connectors. Error Types: - `ANY`: error type that matches all error types that occur in a Flow and can be handled. This type does not include errors that occur on the source. - `TRANSFORMATION`: indicates an error occurred while transforming a value. This involves Mule runtime internal transformations and not DataWeave transformations. - `EXPRESSION`: indicates an error occurred while evaluating a DataWeave expression. - `VALIDATION`: indicates a validation error occurred. - `DUPLICATE_MESSAGE`: indicates a validation error regarding a message being processed twice. For example, using the [Idempotent message validator](https://docs.mulesoft.com/mule-runtime/latest/idempotent-message-validator). - `REDELIVERY_EXHAUSTED`: indicates that max attempts to reprocess a message from a source have been exhausted. - `CONNECTIVITY`: indicates that there was a problem establishing a connection. This could occur while using a connector, for example, an HTTP requester. - `RETRY_EXHAUSTED`: indicates that retries of a certain execution block have been exhausted. For example, for a given operation, or using [Until Successful Scope](https://docs.mulesoft.com/mule-runtime/latest/until-successful-scope). - `ROUTING`: indicates an error occurred while routing a message. For example, using the [Round Robin router](https://docs.mulesoft.com/mule-runtime/latest/round-robin). - `COMPOSITE_ROUTING`: indicates that one or more errors occurred while routing a message. For example, using a [Scatter Gather Router](https://docs.mulesoft.com/mule-runtime/latest/scatter-gather-concept). - `SECURITY`: indicates a security error occurred, like invalid credentials being received or an expired token being used. - `CLIENT_SECURITY`: indicates an external entity (e.g., calling an external endpoint) produced a security error. - `SERVER_SECURITY`: indicates a security error enforced by the Mule runtime. - `NOT_PERMITTED`: indicates a security restriction enforced by a filter. For example, using [the Authorization Filter of the Mule Spring Module](https://docs.mulesoft.com/spring-module/latest/#_to_validate_authentication_using_the_spring_authorization_filter). - `STREAM_MAXIMUM_SIZE_EXCEEDED`: indicates the maximum size allowed for a stream has been exceeded. For more insight, see [Streaming in Mule Apps](https://docs.mulesoft.com/mule-runtime/latest/streaming-about). - `TIMEOUT`: indicates timeout occurred while processing a message. - `UNKNOWN`: indicates an unknown or unexpected error occurred. This cannot be handled directly, only by handling `ANY`, to ensure backward compatibility in case more error types are added in future runtime versions. - `SOURCE`: indicates that an error occurred in the source of the flow. These errors cannot be handled. - `SOURCE_ERROR_RESPONSE_GENERATE`: indicates that an error occurred in the source of the flow generating the parameters of an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_ERROR_RESPONSE_SEND`: indicates that an error occurred in the source of the flow sending an error response. This error cannot be handled since the source has already executed the failing path. - `SOURCE_RESPONSE`: indicates that an error occurred in the source of a flow while processing a successful response. These errors can only be propagated since the source has already executed the successful path. These errors cannot be handled. - `SOURCE_RESPONSE_GENERATE`: indicates an error occurred in the source of the flow while generating the parameters of a successful response. - `SOURCE_RESPONSE_SEND`: indicates an error occurred in the source of the flow while sending a successful response. - `CRITICAL`: indicates a severe error occurred. These errors cannot be handled. - `OVERLOAD`: indicates a problem of overloading occurred and the execution was rejected. - `FLOW_BACK_PRESSURE`: indicates a problem of overloading occurred at the source level. For example, using an HTTP listener as a source. - `FATAL_JVM_ERROR`: indicates that a fatal error occurred, such as stack overflow. ### What Happens After a FATAL\_JVM\_ERROR When the JVM throws a `VirtualMachineError` (for example, `OutOfMemoryError` or `StackOverflowError`), Mule runtime wraps it as a `MULE:FATAL` error and raises a `FATAL_ERROR_RAISED` alert. Because these errors are in the `CRITICAL` hierarchy, On-Error components (`on-error-continue`, `on-error-propagate`) can’t handle them. After a `VirtualMachineError` occurs, the Mule runtime instance, its internal components, or the underlying JVM can remain in an invalid state. Memory can be corrupted, threads can enter undefined states, and further message processing is unreliable. > [!IMPORTANT] The only safe recovery action after a `VirtualMachineError` occurs is to restart the > Mule runtime instance. Don’t assume that the application can continue processing correctly after > encountering one of these errors. #### Common Causes
ErrorCommon Causes

OutOfMemoryError

Unbounded in-memory caching, unconsumed streams that accumulate buffers, processing very large payloads without streaming, or memory leaks in custom Java code.

StackOverflowError

Extremely long flows that create deeply nested Reactor operator stacks, or unbounded recursion in custom Java components or DataWeave expressions. Recursive flow references (a flow calling itself through flow-ref) are protected by Mule runtime internal nesting limit, which raises an EventContextDeepNestingException before a JVM stack overflow occurs.

#### Monitoring and Recovery - Monitor application logs for messages containing `VirtualMachineError`, `OutOfMemoryError`, or `StackOverflowError`. - In managed deployment targets (CloudHub, Runtime Fabric), configure health checks and automatic restarts so that affected instances are replaced quickly. - For on-premises deployments, configure your process supervisor (systemd, Tanuki wrapper) to restart the Mule process if it becomes unresponsive. - After a restart, investigate the root cause by using heap dumps (for `OutOfMemoryError`) or thread dumps (for `StackOverflowError`) captured before the failure occurs. For design patterns that help prevent these errors, see [Avoid Recursive Flow References](https://docs.mulesoft.com/mule-runtime/latest/tuning-app-design#avoid-recursive-flow-references) and [Consume Streams Promptly](https://docs.mulesoft.com/mule-runtime/latest/streaming-about#consume-streams-promptly). ## Custom Error Types To use custom error types, you need to define them either when mapping or when [raising](https://docs.mulesoft.com/mule-runtime/latest/raise-error-component-reference) the errors. These errors require a specific custom namespace to distinguish them from other existing types within an application. This means that an app that uses HTTP and Database connector operations cannot use the HTTP and DB namespaces for custom error types. You need to define namespaces that are related to the particular Mule app name or context and avoid using existing connector namespaces. For example, a customer aggregation API might use the `CUSTOMER` namespace for its custom error types, and an order-processing API might use the `ORDER` namespace. ## Error Mappings In each operation of your flow, you can map the possible error types to a custom error type of your choosing. You can use these custom error types to differentiate where an error occurred in your flow. For example, if your flow has two HTTP Request operations that reach out to different REST services, a connectivity failure on either produces the same error. By mapping each error to different custom error types, you can differentiate the error handling of each operation failure and quickly identify the source of the error in the Mule app logs. In the following example, you can see how mappings allow granular error handling by defining two custom error types: `APP:CUSTOMER_API` and `APP:ORDER_API`. Example XML Configuration for Mappings: ```xml ``` ## See Also - [On-Error Components](https://docs.mulesoft.com/mule-runtime/latest/on-error-scope-concept) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/latest/logging-and-debugging) --- product: Mule Runtime version: 4.11 --- # Mule Event Structure > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule event contains the core information processed by the runtime, including the message payload, attributes, and variables. It travels through components inside your Mule app following the configured application logic. Understanding Mule events helps you design flows that process and transform data effectively. The Mule event is immutable, so every change to an instance of a Mule event results in the creation of a new instance. A Mule event is composed of two objects: - A Mule Message contains a message payload and its associated attributes. - Variables are Mule event metadata that you use in your flow. ![A Mule event including message, attributes, payload, and variables](/mulesoft/current/en-us/mule-runtime/4.11/_images/mule-concepts-d46f9.png) A Mule event source triggers the generation of a Mule event and dispatches that event to the flow. Event sources include triggers such as the Scheduler and listeners such as the HTTP Listener and On New or Updated File components. ![A Mule event source sequence](/mulesoft/current/en-us/mule-runtime/4.11/_images/about-mule-event-2724e.png) This sequence shows how a Mule event flows through your application: 1. A trigger reaches the event source. 2. The event source produces a Mule event. 3. The Mule event travels sequentially through the components of a flow. 4. Each component interacts in a pre-defined manner with the Mule event. In some cases when an issue occurs in an event source, the component doesn’t produce a Mule event. For example, invalid or incorrect paths in an HTTP listener configuration prevent the creation of a Mule event. Connectors log such issues in ERROR, WARN, or INFO messages. ## See Also - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-message) - [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-variables) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/4.11/logging-and-debugging) - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.11/mule-error-concept) --- product: Mule Runtime version: 4.12 --- # Mule Event Structure > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule event contains the core information processed by the runtime, including the message payload, attributes, and variables. It travels through components inside your Mule app following the configured application logic. Understanding Mule events helps you design flows that process and transform data effectively. The Mule event is immutable, so every change to an instance of a Mule event results in the creation of a new instance. A Mule event is composed of two objects: - A Mule Message contains a message payload and its associated attributes. - Variables are Mule event metadata that you use in your flow. ![A Mule event including message, attributes, payload, and variables](/mulesoft/current/en-us/mule-runtime/4.12/_images/mule-concepts-d46f9.png) A Mule event source triggers the generation of a Mule event and dispatches that event to the flow. Event sources include triggers such as the Scheduler and listeners such as the HTTP Listener and On New or Updated File components. ![A Mule event source sequence](/mulesoft/current/en-us/mule-runtime/4.12/_images/about-mule-event-2724e.png) This sequence shows how a Mule event flows through your application: 1. A trigger reaches the event source. 2. The event source produces a Mule event. 3. The Mule event travels sequentially through the components of a flow. 4. Each component interacts in a pre-defined manner with the Mule event. In some cases when an issue occurs in an event source, the component doesn’t produce a Mule event. For example, invalid or incorrect paths in an HTTP listener configuration prevent the creation of a Mule event. Connectors log such issues in ERROR, WARN, or INFO messages. ## See Also - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-message) - [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-variables) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/4.12/logging-and-debugging) - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.12/mule-error-concept) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Mule Event Structure > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule event contains the core information processed by the runtime, including the message payload, attributes, and variables. It travels through components inside your Mule app following the configured application logic. Understanding Mule events helps you design flows that process and transform data effectively. The Mule event is immutable, so every change to an instance of a Mule event results in the creation of a new instance. A Mule event is composed of two objects: - A Mule Message contains a message payload and its associated attributes. - Variables are Mule event metadata that you use in your flow. ![A Mule event including message, attributes, payload, and variables](/mulesoft/current/en-us/mule-runtime/latest/_images/mule-concepts-d46f9.png) A Mule event source triggers the generation of a Mule event and dispatches that event to the flow. Event sources include triggers such as the Scheduler and listeners such as the HTTP Listener and On New or Updated File components. ![A Mule event source sequence](/mulesoft/current/en-us/mule-runtime/latest/_images/about-mule-event-2724e.png) This sequence shows how a Mule event flows through your application: 1. A trigger reaches the event source. 2. The event source produces a Mule event. 3. The Mule event travels sequentially through the components of a flow. 4. Each component interacts in a pre-defined manner with the Mule event. In some cases when an issue occurs in an event source, the component doesn’t produce a Mule event. For example, invalid or incorrect paths in an HTTP listener configuration prevent the creation of a Mule event. Connectors log such issues in ERROR, WARN, or INFO messages. ## See Also - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/latest/about-mule-message) - [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/latest/about-mule-variables) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/latest/logging-and-debugging) - [Mule Errors](https://docs.mulesoft.com/mule-runtime/latest/mule-error-concept) --- product: Mule Runtime version: 4.3 --- # Mule Events > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule event contains the core information processed by the runtime. It travels through components inside your Mule app following the configured application logic. Note that the Mule event is immutable, so every change to an instance of a Mule event results in the creation of a new instance. A Mule event is composed of these objects: - A Mule Message contains a message payload and its associated attributes. - Variables are Mule event metadata that you use in your flow. ![mule concepts d46f9](/mulesoft/current/en-us/mule-runtime/4.3/_images/mule-concepts-d46f9.png) A Message source, such as the Scheduler, HTTP Listener, or On New or Updated File component, triggers the generation of a Mule event and dispatches that event to the flow. ![about mule event 2724e](/mulesoft/current/en-us/mule-runtime/4.3/_images/about-mule-event-2724e.png) 1. A trigger reaches the event source. 2. The event source produces a Mule event. 3. The Mule event travels sequentially through the components of a flow. 4. Each component interacts in a pre-defined manner with the Mule event. In some cases when an issue occurs in a Message source, the component does not produce a Mule event. For example, invalid or incorrect paths in an HTTP listener configuration prevents the creation of a Mule event. Connectors log such issues in ERROR, WARN, or INFO messages. ## See Also - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-message) - [Predefined Variables](https://docs.mulesoft.com/dataweave/2.3/dataweave-variables-context) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-variables) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/4.3/logging-and-debugging) - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.3/mule-error-concept) --- product: Mule Runtime version: 4.4 --- # Mule Events > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule event contains the core information processed by the runtime. It travels through components inside your Mule app following the configured application logic. Note that the Mule event is immutable, so every change to an instance of a Mule event results in the creation of a new instance. A Mule event is composed of these objects: - A Mule Message contains a message payload and its associated attributes. - Variables are Mule event metadata that you use in your flow. ![mule concepts d46f9](/mulesoft/current/en-us/mule-runtime/4.4/_images/mule-concepts-d46f9.png) A Mule event source (previously called a "message source") triggers the generation of a Mule event and dispatches that event to the flow. Examples of event sources include triggers, such as the Scheduler, and listeners, such as the HTTP Listener and On New or Updated File components. ![about mule event 2724e](/mulesoft/current/en-us/mule-runtime/4.4/_images/about-mule-event-2724e.png) 1. A trigger reaches the event source. 2. The event source produces a Mule event. 3. The Mule event travels sequentially through the components of a flow. 4. Each component interacts in a pre-defined manner with the Mule event. In some cases when an issue occurs in an event source, the component does not produce a Mule event. For example, invalid or incorrect paths in an HTTP listener configuration prevents the creation of a Mule event. Connectors log such issues in ERROR, WARN, or INFO messages. ## See Also - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-message) - [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-variables) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/4.4/logging-and-debugging) - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.4/mule-error-concept) --- product: Mule Runtime version: 4.6 --- # Mule Events > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule event contains the core information processed by the runtime. It travels through components inside your Mule app following the configured application logic. Note that the Mule event is immutable, so every change to an instance of a Mule event results in the creation of a new instance. A Mule event is composed of these objects: - A Mule Message contains a message payload and its associated attributes. - Variables are Mule event metadata that you use in your flow. ![mule concepts d46f9](/mulesoft/current/en-us/mule-runtime/4.6/_images/mule-concepts-d46f9.png) A Mule event source (previously called a "message source") triggers the generation of a Mule event and dispatches that event to the flow. Examples of event sources include triggers, such as the Scheduler, and listeners, such as the HTTP Listener and On New or Updated File components. ![about mule event 2724e](/mulesoft/current/en-us/mule-runtime/4.6/_images/about-mule-event-2724e.png) 1. A trigger reaches the event source. 2. The event source produces a Mule event. 3. The Mule event travels sequentially through the components of a flow. 4. Each component interacts in a pre-defined manner with the Mule event. In some cases when an issue occurs in an event source, the component does not produce a Mule event. For example, invalid or incorrect paths in an HTTP listener configuration prevents the creation of a Mule event. Connectors log such issues in ERROR, WARN, or INFO messages. ## See Also - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-message) - [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-variables) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/4.6/logging-and-debugging) - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.6/mule-error-concept) --- product: Mule Runtime version: 4.9 --- # Mule Events > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule event contains the core information processed by the runtime. It travels through components inside your Mule app following the configured application logic. Note that the Mule event is immutable, so every change to an instance of a Mule event results in the creation of a new instance. A Mule event is composed of these objects: - A Mule Message contains a message payload and its associated attributes. - Variables are Mule event metadata that you use in your flow. ![A Mule event including message, attributes, payload, and variables](/mulesoft/current/en-us/mule-runtime/4.9/_images/mule-concepts-d46f9.png) A Mule event source (previously called a "message source") triggers the generation of a Mule event and dispatches that event to the flow. Examples of event sources include triggers, such as the Scheduler, and listeners, such as the HTTP Listener and On New or Updated File components. ![A Mule event source sequence](/mulesoft/current/en-us/mule-runtime/4.9/_images/about-mule-event-2724e.png) 1. A trigger reaches the event source. 2. The event source produces a Mule event. 3. The Mule event travels sequentially through the components of a flow. 4. Each component interacts in a pre-defined manner with the Mule event. In some cases when an issue occurs in an event source, the component does not produce a Mule event. For example, invalid or incorrect paths in an HTTP listener configuration prevents the creation of a Mule event. Connectors log such issues in ERROR, WARN, or INFO messages. ## See Also - [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-message) - [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) - [Variables in Mule Events](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-variables) - [Logging and Debugging](https://docs.mulesoft.com/mule-runtime/4.9/logging-and-debugging) - [Mule Errors](https://docs.mulesoft.com/mule-runtime/4.9/mule-error-concept) --- product: Mule Runtime version: 4.11 keywords: java, classes, javadoc, reference, objects, methods --- # Mule Kernel API Javadoc > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Access reference information for Mule Kernel Java APIs and review support limitations. MuleSoft provides Javadocs for the Mule Kernel (formerly called Mule Community Edition). Note that the Mule Kernel doesn’t provide all the functionality of the Mule runtime engine, and development with the Mule Kernel isn’t supported in Anypoint Studio. The Javadocs contain definitions for classes, fields and their data types, and they also describe methods, including their usage, parameters, and return values. For a supported and easier way to extend the Mule runtime engine, see [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## See Also - [Download Mule](https://www.mulesoft.com/lp/dl/anypoint-mule-studio) - [Download Mule Kernel](https://developer.mulesoft.com/download-mule-esb-runtime) --- product: Mule Runtime version: 4.12 keywords: java, classes, javadoc, reference, objects, methods --- # Mule Kernel API Javadoc > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Access reference information for Mule Kernel Java APIs and review support limitations. MuleSoft provides Javadocs for the Mule Kernel (formerly called Mule Community Edition). Note that the Mule Kernel doesn’t provide all the functionality of the Mule runtime engine, and development with the Mule Kernel isn’t supported in Anypoint Studio. The Javadocs contain definitions for classes, fields and their data types, and they also describe methods, including their usage, parameters, and return values. For a supported and easier way to extend the Mule runtime engine, see [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## See Also - [Download Mule](https://www.mulesoft.com/lp/dl/anypoint-mule-studio) - [Download Mule Kernel](https://developer.mulesoft.com/download-mule-esb-runtime) --- product: Mule Runtime version: 4.3 keywords: java, classes, javadoc, reference, objects, methods --- # Mule Kernel API Javadoc > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Access reference information for Mule Kernel Java APIs and review support limitations. MuleSoft provides Javadocs for the Mule Kernel (formerly called Mule Community Edition). Note that the Mule Kernel doesn’t provide all the functionality of the Mule runtime engine, and development with the Mule Kernel isn’t supported in Anypoint Studio. The Javadocs contain definitions for classes, fields and their data types, and they also describe methods, including their usage, parameters, and return values. For a supported and easier way to extend the Mule runtime engine, see [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## See Also - [Download Mule](https://www.mulesoft.com/lp/dl/anypoint-mule-studio) - [Download Mule Kernel](https://developer.mulesoft.com/download-mule-esb-runtime) --- product: Mule Runtime version: 4.4 keywords: java, classes, javadoc, reference, objects, methods --- # Mule Kernel API Javadoc > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Access reference information for Mule Kernel Java APIs and review support limitations. MuleSoft provides Javadocs for the Mule Kernel (formerly called Mule Community Edition). Note that the Mule Kernel doesn’t provide all the functionality of the Mule runtime engine, and development with the Mule Kernel isn’t supported in Anypoint Studio. The Javadocs contain definitions for classes, fields and their data types, and they also describe methods, including their usage, parameters, and return values. For a supported and easier way to extend the Mule runtime engine, see [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## See Also - [Download Mule](https://www.mulesoft.com/lp/dl/anypoint-mule-studio) - [Download Mule Kernel](https://developer.mulesoft.com/download-mule-esb-runtime) --- product: Mule Runtime version: 4.6 keywords: java, classes, javadoc, reference, objects, methods --- # Mule Kernel API Javadoc > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Access reference information for Mule Kernel Java APIs and review support limitations. MuleSoft provides Javadocs for the Mule Kernel (formerly called Mule Community Edition). Note that the Mule Kernel doesn’t provide all the functionality of the Mule runtime engine, and development with the Mule Kernel isn’t supported in Anypoint Studio. The Javadocs contain definitions for classes, fields and their data types, and they also describe methods, including their usage, parameters, and return values. For a supported and easier way to extend the Mule runtime engine, see [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## See Also - [Download Mule](https://www.mulesoft.com/lp/dl/anypoint-mule-studio) - [Download Mule Kernel](https://developer.mulesoft.com/download-mule-esb-runtime) --- product: Mule Runtime version: 4.9 keywords: java, classes, javadoc, reference, objects, methods --- # Mule Kernel API Javadoc > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Access reference information for Mule Kernel Java APIs and review support limitations. MuleSoft provides Javadocs for the Mule Kernel (formerly called Mule Community Edition). Note that the Mule Kernel doesn’t provide all the functionality of the Mule runtime engine, and development with the Mule Kernel isn’t supported in Anypoint Studio. The Javadocs contain definitions for classes, fields and their data types, and they also describe methods, including their usage, parameters, and return values. For a supported and easier way to extend the Mule runtime engine, see [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## See Also - [Download Mule](https://www.mulesoft.com/lp/dl/anypoint-mule-studio) - [Download Mule Kernel](https://developer.mulesoft.com/download-mule-esb-runtime) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: java, classes, javadoc, reference, objects, methods --- # Mule Kernel API Javadoc > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Access reference information for Mule Kernel Java APIs and review support limitations. MuleSoft provides Javadocs for the Mule Kernel (formerly called Mule Community Edition). Note that the Mule Kernel doesn’t provide all the functionality of the Mule runtime engine, and development with the Mule Kernel isn’t supported in Anypoint Studio. The Javadocs contain definitions for classes, fields and their data types, and they also describe methods, including their usage, parameters, and return values. For a supported and easier way to extend the Mule runtime engine, see [Mule SDK](https://docs.mulesoft.com/mule-sdk/latest/). ## See Also - [Download Mule](https://www.mulesoft.com/lp/dl/anypoint-mule-studio) - [Download Mule Kernel](https://developer.mulesoft.com/download-mule-esb-runtime) --- product: Mule Runtime version: 4.11 --- # Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. The Mule Maven plugin enables you to integrate the packaging and deployment of your Mule applications with your Maven lifecycle. See [Package a Mule Application](https://docs.mulesoft.com/mule-runtime/4.11/package-a-mule-application) for packaging instructions. The Mule Maven plugin is compatible with Mule runtime engine (Enterprise Edition) and with Mule Kernel (Community Edition). Using the Mule Maven plugin, you can automate your Mule application deployment to CloudHub, to CloudHub 2.0, to Anypoint Runtime Fabric, or on-premises, using any of the following deployment strategies: - CloudHub deployment Deploys your Mule application to CloudHub. See [Deploy Applications to CloudHub](https://docs.mulesoft.com/mule-runtime/4.11/deploy-to-cloudhub) for instructions. - CloudHub 2.0 deployment Deploys your Mule application to CloudHub 2.0. See [Deploy Applications to CloudHub 2.0](https://docs.mulesoft.com/mule-runtime/4.11/deploy-to-cloudhub-2) for instructions. - Runtime Fabric deployment Deploys your Mule application to Anypoint Runtime Fabric. See [Deploy Applications to Anypoint Runtime Fabric](https://docs.mulesoft.com/mule-runtime/4.11/deploy-to-rtf) for instructions. - Runtime Manager REST API deployment Deploys your Mule application to your server, or server clusters using the Runtime Manager REST API. See [Deploy a Mule Application Using the Runtime Manager REST API](https://docs.mulesoft.com/mule-runtime/4.11/deploy-on-premises#mmp-deploy-arm) for instructions. - Runtime Manager agent deployment Deploy your Mule application using the Runtime Manager agent. This deployment strategy works only if all your Mule instances reside in one address space. See [Deploy a Mule Application Using the Runtime Manager Agent](https://docs.mulesoft.com/mule-runtime/4.11/deploy-on-premises#mmp-deploy-agent) for instructions. - Standalone runtime deployment Deploy your Mule application to a Mule instance running on your machine. See [Deploy a Mule Application to a Standalone Mule Runtime Engine](https://docs.mulesoft.com/mule-runtime/4.11/deploy-on-premises#mmp-deploy-standalone) for instructions. ## Compatibility - Mule 4.x - Anypoint Studio 7.x ## Mule Maven Plugin Goals The Mule Maven plugin provides the following goals: - `package` Generates the jar file for your project. - `deploy` Automatically uploads and starts your application in any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). - `mule:deploy` Deploys an artifact from the specified location. - `mule:undeploy` Automatically removes your application from any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). Each goal accepts parameters that are unique to the desired plugin behavior. To provide a parameter from the command line, prepend `-D` to the parameter name. ### Package Goal The `package` goal generates the application JAR file. This goal binds by default to the Maven lifecycle phase: `package`. Optional Parameters
NameTypeDescription

onlyMuleSources

boolean

Generates the application JAR file containing only the source code. This property is just for sharing purposes.

attachMuleSources

boolean

Attaches the source code inside the generated JAR file.

lightweightPackage

boolean

Doesn’t generate the repository with all the application dependencies inside the JAR file. This property is just for sharing purposes.

For example, to execute the `package` goal and set the `attachMuleSources` parameter, you run the following command: ```console mvn package -DattachMuleSources ``` ### Deploy Goal This goal uploads and deploys the application JAR file to any of the application deployment targets. The deploy goal binds by default to the Maven lifecycle phase: `deploy`. Optional Parameters
NameTypeDescription

artifact

String

Path to the application JAR file to be deployed. By default is set to the application target folder.

muleDeploy

boolean

Instructs the plugin to deploy using the deployment strategy defined in the plugin configuration. If the muleDeploy parameter is not set, the plugin uploads the artifacts to the repository defined in the distributionManagement section of the application’s pom.xml file.

For example, to execute the `deploy` goal and set the `muleDeploy` parameter, you run the following command: ```console mvn deploy -DmuleDeploy ``` ### mule:deploy Goal This goal enables you to deploy an artifact without building it. To specify the artifact’s location, use the `mule.artifact` parameter. For example: ```console mvn mule:deploy -Dmule.artifact=myProject/myArtifact.jar ``` This property is valid for CloudHub, standalone, and on-premises deployments. ### mule:undeploy Goal This goal removes an application from any of the application deployment targets. It uses the information from the plugin configuration to remove the application from the defined deployment target. To execute the `undeploy` goal, run the following command: ```console mvn mule:undeploy ``` The undeploy goal also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Add the Mule Maven Plugin to a Mule Project Before you can perform any operations, you must add the Mule Maven plugin to your project. To add the Mule Maven plugin, you need to add its maven dependency to the project: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ``` From this repository: ```xml mule-public https://repository.mulesoft.org/nexus/content/repositories/releases ``` This enables the Mule Maven plugin in your project. > [!IMPORTANT] If `true` is not present, the plugin does not work. ## Skip Plugin Execution You can skip the plugin execution by setting the `skip` parameter to true inside your deployment configuration: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} true ``` ## Skip Deployment Verification You can skip the status verification of your deployed app by setting the `skipDeploymentVerification` parameter to true inside of any of the platform deployments (Cloudhub, Runtime Manager, and Runtime Fabric): ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ... true ... ``` If the `skipDeploymentVerification` parameter is not present, the default value is false. This feature is available in plugin version 3.2.5 and later. ## Configure Shared Libraries Shared libraries enable you to configure a dependency in your application and make this dependency accessible to all the connectors in your application. See [Shared Libraries](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#shared-libraries) for an in-depth explanation of this feature. To configure a dependency as a shared library, add the following elements inside your Mule Maven plugin configuration in your project’s `pom.xml` file: ```xml ${dependencyGroupID} ${dependencyArtifactID} ``` The following example configures Anypoint Connector for Database (Database Connector) in a project, and also configures the MySQL driver as a shared library: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true mysql mysql-connector-java org.mule.connectors mule-db-connector 1.5.0 mule-plugin mysql mysql-connector-java 5.1.33 ``` ## Configure Additional Plugin Dependencies Configuring additional plugin dependencies for a connector in your application makes those dependencies available for only that connector. Doing this enables you to configure different dependencies, or even multiple versions of the same dependency, for different connectors. See [Additional Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#additional-plugin-dependencies) for an in-depth explanation of this feature. To configure additional plugin dependencies, add the following elements inside your Mule Maven plugin configuration in your project’s `pom.xml` file: ```xml ${connectorGroupID} ${connectorArtifactID} ${dependencyGroupID} ${dependencyArtifactID} ${dependencyVersion} ``` The following example configures the Derby driver as a dependency of Database Connector: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} org.mule.connectors mule-db-connector org.apache.derby derby 10.11.1.1 ``` ## Mule Maven Plugin Reference The following links contain the parameter reference of each deployment strategy: - [CloudHub deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.11/deploy-to-cloudhub#cloudhub-deploy-reference) - [Runtime Fabric deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.11/deploy-to-rtf#rtf-deploy-reference) - [Standalone deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.11/deploy-on-premises#standalone-deploy-reference) - [Runtime Manager REST API deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.11/deploy-on-premises#arm-deploy-reference) - [Runtime Manager agent deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.11/deploy-on-premises#arm-agent-deploy-reference) ## See Also - [Classloading Isolation](https://docs.mulesoft.com/mule-runtime/4.11/about-classloading-isolation) - [Export Resources](https://docs.mulesoft.com/mule-runtime/4.11/how-to-export-resources) - [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven) - [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed) - [Runtime Manager REST API](https://docs.mulesoft.com/runtime-manager/runtime-manager-api) - [Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) --- product: Mule Runtime version: 4.12 --- # Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. The Mule Maven plugin enables you to integrate the packaging and deployment of your Mule applications with your Maven lifecycle. See [Package a Mule Application](https://docs.mulesoft.com/mule-runtime/4.12/package-a-mule-application) for packaging instructions. The Mule Maven plugin is compatible with Mule runtime engine (Enterprise Edition) and with Mule Kernel (Community Edition). Using the Mule Maven plugin, you can automate your Mule application deployment to CloudHub, to CloudHub 2.0, to Anypoint Runtime Fabric, or on-premises, using any of the following deployment strategies: - CloudHub deployment Deploys your Mule application to CloudHub. See [Deploy Applications to CloudHub](https://docs.mulesoft.com/mule-runtime/4.12/deploy-to-cloudhub) for instructions. - CloudHub 2.0 deployment Deploys your Mule application to CloudHub 2.0. See [Deploy Applications to CloudHub 2.0](https://docs.mulesoft.com/mule-runtime/4.12/deploy-to-cloudhub-2) for instructions. - Runtime Fabric deployment Deploys your Mule application to Anypoint Runtime Fabric. See [Deploy Applications to Anypoint Runtime Fabric](https://docs.mulesoft.com/mule-runtime/4.12/deploy-to-rtf) for instructions. - Runtime Manager REST API deployment Deploys your Mule application to your server, or server clusters using the Runtime Manager REST API. See [Deploy a Mule Application Using the Runtime Manager REST API](https://docs.mulesoft.com/mule-runtime/4.12/deploy-on-premises#mmp-deploy-arm) for instructions. - Runtime Manager agent deployment Deploy your Mule application using the Runtime Manager agent. This deployment strategy works only if all your Mule instances reside in one address space. See [Deploy a Mule Application Using the Runtime Manager Agent](https://docs.mulesoft.com/mule-runtime/4.12/deploy-on-premises#mmp-deploy-agent) for instructions. - Standalone runtime deployment Deploy your Mule application to a Mule instance running on your machine. See [Deploy a Mule Application to a Standalone Mule Runtime Engine](https://docs.mulesoft.com/mule-runtime/4.12/deploy-on-premises#mmp-deploy-standalone) for instructions. ## Compatibility - Mule 4.x - Anypoint Studio 7.x ## Mule Maven Plugin Goals The Mule Maven plugin provides the following goals: - `package` Generates the jar file for your project. - `deploy` Automatically uploads and starts your application in any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). - `mule:deploy` Deploys an artifact from the specified location. - `mule:undeploy` Automatically removes your application from any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). Each goal accepts parameters that are unique to the desired plugin behavior. To provide a parameter from the command line, prepend `-D` to the parameter name. ### Package Goal The `package` goal generates the application JAR file. This goal binds by default to the Maven lifecycle phase: `package`. Optional Parameters
NameTypeDescription

onlyMuleSources

boolean

Generates the application JAR file containing only the source code. This property is just for sharing purposes.

attachMuleSources

boolean

Attaches the source code inside the generated JAR file.

lightweightPackage

boolean

Doesn’t generate the repository with all the application dependencies inside the JAR file. This property is just for sharing purposes.

For example, to execute the `package` goal and set the `attachMuleSources` parameter, you run the following command: ```console mvn package -DattachMuleSources ``` ### Deploy Goal This goal uploads and deploys the application JAR file to any of the application deployment targets. The deploy goal binds by default to the Maven lifecycle phase: `deploy`. Optional Parameters
NameTypeDescription

artifact

String

Path to the application JAR file to be deployed. By default is set to the application target folder.

muleDeploy

boolean

Instructs the plugin to deploy using the deployment strategy defined in the plugin configuration. If the muleDeploy parameter is not set, the plugin uploads the artifacts to the repository defined in the distributionManagement section of the application’s pom.xml file.

For example, to execute the `deploy` goal and set the `muleDeploy` parameter, you run the following command: ```console mvn deploy -DmuleDeploy ``` ### mule:deploy Goal This goal enables you to deploy an artifact without building it. To specify the artifact’s location, use the `mule.artifact` parameter. For example: ```console mvn mule:deploy -Dmule.artifact=myProject/myArtifact.jar ``` This property is valid for CloudHub, standalone, and on-premises deployments. ### mule:undeploy Goal This goal removes an application from any of the application deployment targets. It uses the information from the plugin configuration to remove the application from the defined deployment target. To execute the `undeploy` goal, run the following command: ```console mvn mule:undeploy ``` The undeploy goal also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Add the Mule Maven Plugin to a Mule Project Before you can perform any operations, you must add the Mule Maven plugin to your project. To add the Mule Maven plugin, you need to add its maven dependency to the project: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ``` From this repository: ```xml mule-public https://repository.mulesoft.org/nexus/content/repositories/releases ``` This enables the Mule Maven plugin in your project. > [!IMPORTANT] If `true` is not present, the plugin does not work. ## Skip Plugin Execution You can skip the plugin execution by setting the `skip` parameter to true inside your deployment configuration: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} true ``` ## Skip Deployment Verification You can skip the status verification of your deployed app by setting the `skipDeploymentVerification` parameter to true inside of any of the platform deployments (Cloudhub, Runtime Manager, and Runtime Fabric): ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ... true ... ``` If the `skipDeploymentVerification` parameter is not present, the default value is false. This feature is available in plugin version 3.2.5 and later. ## Configure Shared Libraries Shared libraries enable you to configure a dependency in your application and make this dependency accessible to all the connectors in your application. See [Shared Libraries](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#shared-libraries) for an in-depth explanation of this feature. To configure a dependency as a shared library, add the following elements inside your Mule Maven plugin configuration in your project’s `pom.xml` file: ```xml ${dependencyGroupID} ${dependencyArtifactID} ``` The following example configures Anypoint Connector for Database (Database Connector) in a project, and also configures the MySQL driver as a shared library: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true mysql mysql-connector-java org.mule.connectors mule-db-connector 1.5.0 mule-plugin mysql mysql-connector-java 5.1.33 ``` ## Configure Additional Plugin Dependencies Configuring additional plugin dependencies for a connector in your application makes those dependencies available for only that connector. Doing this enables you to configure different dependencies, or even multiple versions of the same dependency, for different connectors. See [Additional Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#additional-plugin-dependencies) for an in-depth explanation of this feature. To configure additional plugin dependencies, add the following elements inside your Mule Maven plugin configuration in your project’s `pom.xml` file: ```xml ${connectorGroupID} ${connectorArtifactID} ${dependencyGroupID} ${dependencyArtifactID} ${dependencyVersion} ``` The following example configures the Derby driver as a dependency of Database Connector: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} org.mule.connectors mule-db-connector org.apache.derby derby 10.11.1.1 ``` ## Mule Maven Plugin Reference The following links contain the parameter reference of each deployment strategy: - [CloudHub deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.12/deploy-to-cloudhub#cloudhub-deploy-reference) - [Runtime Fabric deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.12/deploy-to-rtf#rtf-deploy-reference) - [Standalone deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.12/deploy-on-premises#standalone-deploy-reference) - [Runtime Manager REST API deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.12/deploy-on-premises#arm-deploy-reference) - [Runtime Manager agent deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.12/deploy-on-premises#arm-agent-deploy-reference) ## See Also - [Classloading Isolation](https://docs.mulesoft.com/mule-runtime/4.12/about-classloading-isolation) - [Export Resources](https://docs.mulesoft.com/mule-runtime/4.12/how-to-export-resources) - [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven) - [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed) - [Runtime Manager REST API](https://docs.mulesoft.com/runtime-manager/runtime-manager-api) - [Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) --- product: Mule Runtime version: 4.3 --- # Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. The Mule Maven plugin enables you to integrate the packaging and deployment of your Mule applications with your Maven lifecycle. See [Package a Mule Application](https://docs.mulesoft.com/mule-runtime/4.3/package-a-mule-application) for packaging instructions. The Mule Maven plugin is compatible with Mule runtime engine (Enterprise Edition) and with Mule Kernel (Community Edition). Using the Mule Maven plugin, you can automate your Mule application deployment to CloudHub, to Anypoint Runtime Fabric, or on-premises, using any of the following deployment strategies: - CloudHub deployment Deploys your Mule application to CloudHub. See [Deploy Applications to CloudHub](https://docs.mulesoft.com/mule-runtime/4.3/deploy-to-cloudhub) for instructions. - Runtime Fabric deployment Deploys your Mule application to Anypoint Runtime Fabric. See [Deploy Applications to Anypoint Runtime Fabric](https://docs.mulesoft.com/mule-runtime/4.3/deploy-to-rtf) for instructions. - Runtime Manager REST API deployment Deploys your Mule application to your server, or server clusters using the Runtime Manager REST API. See [Deploy a Mule Application Using the Runtime Manager REST API](https://docs.mulesoft.com/mule-runtime/4.3/deploy-on-premises#mmp-deploy-arm) for instructions. - Runtime Manager agent deployment Deploy your Mule application using the Runtime Manager agent. This deployment strategy works only if all your Mule instances reside in one address space. See [Deploy a Mule Application Using the Runtime Manager Agent](https://docs.mulesoft.com/mule-runtime/4.3/deploy-on-premises#mmp-deploy-agent) for instructions. - Standalone runtime deployment Deploy your Mule application to a Mule instance running on your machine. See [Deploy a Mule Application to a Standalone Mule Runtime Engine](https://docs.mulesoft.com/mule-runtime/4.3/deploy-on-premises#mmp-deploy-standalone) for instructions. ## Compatibility - Mule 4.x - Anypoint Studio 7.x ## Mule Maven Plugin Goals The Mule Maven plugin has four goals: - `package` Generates the jar file for your project. - `deploy` Automatically uploads and starts your application in any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). - `mule:deploy` Deploys an artifact from the specified location. - `mule:undeploy` Automatically removes your application from any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). Each goal accepts parameters that are unique to the desired plugin behavior. To provide a parameter from the command line, prepend `-D` to the parameter name. ### Package Goal The `package` goal generates the application JAR file. This goal binds by default to the Maven lifecycle phase: `package`. Optional Parameters
NameTypeDescription

onlyMuleSources

boolean

Generates the application JAR file containing only the source code. This property is just for sharing purposes.

attachMuleSources

boolean

Attaches the source code inside the generated JAR file.

lightweightPackage

boolean

Doesn’t generate the repository with all the application dependencies inside the JAR file. This property is just for sharing purposes.

For example, to execute the `package` goal and set the `attachMuleSources` parameter, you run the following command: ```console mvn package -DattachMuleSources ``` ### Deploy Goal This goal uploads and deploys the application JAR file to any of the application deployment targets. The deploy goal binds by default to the Maven lifecycle phase: `deploy`. Optional Parameters
NameTypeDescription

artifact

String

Path to the application JAR file to be deployed. By default is set to the application target folder.

muleDeploy

boolean

Instructs the plugin to deploy using the deployment strategy defined in the plugin configuration. If the muleDeploy parameter is not set, the plugin uploads the artifacts to the repository defined in the distributionManagement section of the application’s pom.xml file.

For example, to execute the `deploy` goal and set the `muleDeploy` parameter, you run the following command: ```console mvn deploy -DmuleDeploy ``` ### mule:deploy Goal This goal enables you to deploy an artifact without building it. To specify the artifact’s location, use the `mule.artifact` parameter. For example: ```console mvn mule:deploy -Dmule.artifact=myProject/myArtifact.jar ``` This property is valid for CloudHub, standalone, or on-premises deployments. ### mule:undeploy Goal This goal removes an application from any of the application deployment targets. It uses the information from the plugin configuration to remove the application from the defined deployment target. To execute the `undeploy` goal, run the following command: ```console mvn mule:undeploy ``` The undeploy goal also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Add the Mule Maven Plugin to a Mule Project Before you can perform any operations, you must add the Mule Maven plugin to your project. To add the Mule Maven plugin, you need to add its maven dependency to the project: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ``` From this repository: ```xml mule-public https://repository.mulesoft.org/nexus/content/repositories/releases ``` This enables the Mule Maven plugin in your project. > [!IMPORTANT] If `true` is not present, the plugin does not work. ## Skip Plugin Execution You can skip the plugin execution by setting the `skip` parameter to true inside your deployment configuration: ```xml org.mule.tools.maven mule-maven-plugin 3.4.2 true ${mule.home.test} true ``` ## Skip Deployment Verification You can skip the status verification of your deployed app by setting the `skipDeploymentVerification` parameter to true inside of any of the platform deployments (Cloudhub, Runtime Manager, and Runtime Fabric): ```xml org.mule.tools.maven mule-maven-plugin 3.4.2 true ... true ... ``` If the `skipDeploymentVerification` parameter is not present, the default value is false. This feature is available in plugin version 3.2.5 and later. ## Configure Shared Libraries Configure shared libraries when you need to make an application’s dependency visible to your application’s connectors. To configure a dependency as a shared library, add the following elements in your Mule Maven plugin configuration inside your project’s `pom.xml` file: ```xml ${dependencyGroupID} ${dependencyArtifactID} ``` The following example configures Anypoint Connector for Database (Database Connector) in a project, and also configures the MySQL driver as a shared library: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true mysql mysql-connector-java
org.mule.connectors mule-db-connector 1.5.0 mule-plugin mysql mysql-connector-java 5.1.33
``` ## Configure Additional Plugin Dependencies You can configure additional plugin dependencies for the connectors in your application. To configure additional plugin dependencies, add the following elements in your Mule Maven plugin configuration inside your project’s `pom.xml` file: ```xml ${connectorGroupID} ${connectorArtifactID} ${dependencyGroupID} ${dependencyArtifactID} ${dependencyVersion} ``` The following example configures the Derby driver as a dependency of Database Connector: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} org.mule.connectors mule-db-connector org.apache.derby derby 10.11.1.1 ``` ## Mule Maven Plugin Reference The following links contain the parameter reference of each deployment strategy: - [CloudHub deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.3/deploy-to-cloudhub#cloudhub-deploy-reference) - [Runtime Fabric deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.3/deploy-to-rtf#rtf-deploy-reference) - [Standalone deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.3/deploy-on-premises#standalone-deploy-reference) - [Runtime Manager REST API deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.3/deploy-on-premises#arm-deploy-reference) - [Runtime Manager agent deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.3/deploy-on-premises#arm-agent-deploy-reference) ## See Also - [Classloading Isolation](https://docs.mulesoft.com/mule-runtime/4.3/about-classloading-isolation) - [Export Resources](https://docs.mulesoft.com/mule-runtime/4.3/how-to-export-resources) - [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven) - [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed) - [Runtime Manager REST API](https://docs.mulesoft.com/runtime-manager/runtime-manager-api) - [Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) --- product: Mule Runtime version: 4.4 --- # Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. The Mule Maven plugin enables you to integrate the packaging and deployment of your Mule applications with your Maven lifecycle. See [Package a Mule Application](https://docs.mulesoft.com/mule-runtime/4.4/package-a-mule-application) for packaging instructions. The Mule Maven plugin is compatible with Mule runtime engine (Enterprise Edition) and with Mule Kernel (Community Edition). Using the Mule Maven plugin, you can automate your Mule application deployment to CloudHub, to CloudHub 2.0, to Anypoint Runtime Fabric, or on-premises, using any of the following deployment strategies: - CloudHub deployment Deploys your Mule application to CloudHub. See [Deploy Applications to CloudHub](https://docs.mulesoft.com/mule-runtime/4.4/deploy-to-cloudhub) for instructions. - CloudHub 2.0 deployment Deploys your Mule application to CloudHub 2.0. See [Deploy Applications to CloudHub 2.0](https://docs.mulesoft.com/mule-runtime/4.4/deploy-to-cloudhub-2) for instructions. - Runtime Fabric deployment Deploys your Mule application to Anypoint Runtime Fabric. See [Deploy Applications to Anypoint Runtime Fabric](https://docs.mulesoft.com/mule-runtime/4.4/deploy-to-rtf) for instructions. - Runtime Manager REST API deployment Deploys your Mule application to your server, or server clusters using the Runtime Manager REST API. See [Deploy a Mule Application Using the Runtime Manager REST API](https://docs.mulesoft.com/mule-runtime/4.4/deploy-on-premises#mmp-deploy-arm) for instructions. - Runtime Manager agent deployment Deploy your Mule application using the Runtime Manager agent. This deployment strategy works only if all your Mule instances reside in one address space. See [Deploy a Mule Application Using the Runtime Manager Agent](https://docs.mulesoft.com/mule-runtime/4.4/deploy-on-premises#mmp-deploy-agent) for instructions. - Standalone runtime deployment Deploy your Mule application to a Mule instance running on your machine. See [Deploy a Mule Application to a Standalone Mule Runtime Engine](https://docs.mulesoft.com/mule-runtime/4.4/deploy-on-premises#mmp-deploy-standalone) for instructions. ## Compatibility - Mule 4.x - Anypoint Studio 7.x ## Mule Maven Plugin Goals The Mule Maven plugin has four goals: - `package` Generates the jar file for your project. - `deploy` Automatically uploads and starts your application in any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). - `mule:deploy` Deploys an artifact from the specified location. - `mule:undeploy` Automatically removes your application from any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). Each goal accepts parameters that are unique to the desired plugin behavior. To provide a parameter from the command line, prepend `-D` to the parameter name. ### Package Goal The `package` goal generates the application JAR file. This goal binds by default to the Maven lifecycle phase: `package`. Optional Parameters
NameTypeDescription

onlyMuleSources

boolean

Generates the application JAR file containing only the source code. This property is just for sharing purposes.

attachMuleSources

boolean

Attaches the source code inside the generated JAR file.

lightweightPackage

boolean

Doesn’t generate the repository with all the application dependencies inside the JAR file. This property is just for sharing purposes.

For example, to execute the `package` goal and set the `attachMuleSources` parameter, you run the following command: ```console mvn package -DattachMuleSources ``` ### Deploy Goal This goal uploads and deploys the application JAR file to any of the application deployment targets. The deploy goal binds by default to the Maven lifecycle phase: `deploy`. Optional Parameters
NameTypeDescription

artifact

String

Path to the application JAR file to be deployed. By default is set to the application target folder.

muleDeploy

boolean

Instructs the plugin to deploy using the deployment strategy defined in the plugin configuration. If the muleDeploy parameter is not set, the plugin uploads the artifacts to the repository defined in the distributionManagement section of the application’s pom.xml file.

For example, to execute the `deploy` goal and set the `muleDeploy` parameter, you run the following command: ```console mvn deploy -DmuleDeploy ``` ### mule:deploy Goal This goal enables you to deploy an artifact without building it. To specify the artifact’s location, use the `mule.artifact` parameter. For example: ```console mvn mule:deploy -Dmule.artifact=myProject/myArtifact.jar ``` This property is valid for CloudHub, standalone, or on-premises deployments. ### mule:undeploy Goal This goal removes an application from any of the application deployment targets. It uses the information from the plugin configuration to remove the application from the defined deployment target. To execute the `undeploy` goal, run the following command: ```console mvn mule:undeploy ``` The undeploy goal also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Add the Mule Maven Plugin to a Mule Project Before you can perform any operations, you must add the Mule Maven plugin to your project. To add the Mule Maven plugin, you need to add its maven dependency to the project: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ``` From this repository: ```xml mule-public https://repository.mulesoft.org/nexus/content/repositories/releases ``` This enables the Mule Maven plugin in your project. > [!IMPORTANT] If `true` is not present, the plugin does not work. ## Skip Plugin Execution You can skip the plugin execution by setting the `skip` parameter to true inside your deployment configuration: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} true ``` ## Skip Deployment Verification You can skip the status verification of your deployed app by setting the `skipDeploymentVerification` parameter to true inside of any of the platform deployments (Cloudhub, Runtime Manager, and Runtime Fabric): ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ... true ... ``` If the `skipDeploymentVerification` parameter is not present, the default value is false. This feature is available in plugin version 3.2.5 and later. ## Configure Shared Libraries Shared libraries enable you to configure a dependency in your application and make this dependency accessible to all the connectors in your application. See [Shared Libraries](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#shared-libraries) for an in-depth explanation of this feature. To configure a dependency as a shared library, add the following elements inside your Mule Maven plugin configuration in your project’s `pom.xml` file: ```xml ${dependencyGroupID} ${dependencyArtifactID} ``` The following example configures Anypoint Connector for Database (Database Connector) in a project, and also configures the MySQL driver as a shared library: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true mysql mysql-connector-java org.mule.connectors mule-db-connector 1.5.0 mule-plugin mysql mysql-connector-java 5.1.33 ``` ## Configure Additional Plugin Dependencies Configuring additional plugin dependencies for a connector in your application makes those dependencies available for only that connector. Doing this enables you to configure different dependencies, or even multiple versions of the same dependency, for different connectors. See [Additional Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#additional-plugin-dependencies) for an in-depth explanation of this feature. To configure additional plugin dependencies, add the following elements inside your Mule Maven plugin configuration in your project’s `pom.xml` file: ```xml ${connectorGroupID} ${connectorArtifactID} ${dependencyGroupID} ${dependencyArtifactID} ${dependencyVersion} ``` The following example configures the Derby driver as a dependency of Database Connector: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} org.mule.connectors mule-db-connector org.apache.derby derby 10.11.1.1 ``` ## Mule Maven Plugin Reference The following links contain the parameter reference of each deployment strategy: - [CloudHub deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.4/deploy-to-cloudhub#cloudhub-deploy-reference) - [Runtime Fabric deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.4/deploy-to-rtf#rtf-deploy-reference) - [Standalone deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.4/deploy-on-premises#standalone-deploy-reference) - [Runtime Manager REST API deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.4/deploy-on-premises#arm-deploy-reference) - [Runtime Manager agent deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.4/deploy-on-premises#arm-agent-deploy-reference) ## See Also - [Classloading Isolation](https://docs.mulesoft.com/mule-runtime/4.4/about-classloading-isolation) - [Export Resources](https://docs.mulesoft.com/mule-runtime/4.4/how-to-export-resources) - [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven) - [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed) - [Runtime Manager REST API](https://docs.mulesoft.com/runtime-manager/runtime-manager-api) - [Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) --- product: Mule Runtime version: 4.6 --- # Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. The Mule Maven plugin enables you to integrate the packaging and deployment of your Mule applications with your Maven lifecycle. See [Package a Mule Application](https://docs.mulesoft.com/mule-runtime/4.6/package-a-mule-application) for packaging instructions. The Mule Maven plugin is compatible with Mule runtime engine (Enterprise Edition) and with Mule Kernel (Community Edition). Using the Mule Maven plugin, you can automate your Mule application deployment to CloudHub, to CloudHub 2.0, to Anypoint Runtime Fabric, or on-premises, using any of the following deployment strategies: - CloudHub deployment Deploys your Mule application to CloudHub. See [Deploy Applications to CloudHub](https://docs.mulesoft.com/mule-runtime/4.6/deploy-to-cloudhub) for instructions. - CloudHub 2.0 deployment Deploys your Mule application to CloudHub 2.0. See [Deploy Applications to CloudHub 2.0](https://docs.mulesoft.com/mule-runtime/4.6/deploy-to-cloudhub-2) for instructions. - Runtime Fabric deployment Deploys your Mule application to Anypoint Runtime Fabric. See [Deploy Applications to Anypoint Runtime Fabric](https://docs.mulesoft.com/mule-runtime/4.6/deploy-to-rtf) for instructions. - Runtime Manager REST API deployment Deploys your Mule application to your server, or server clusters using the Runtime Manager REST API. See [Deploy a Mule Application Using the Runtime Manager REST API](https://docs.mulesoft.com/mule-runtime/4.6/deploy-on-premises#mmp-deploy-arm) for instructions. - Runtime Manager agent deployment Deploy your Mule application using the Runtime Manager agent. This deployment strategy works only if all your Mule instances reside in one address space. See [Deploy a Mule Application Using the Runtime Manager Agent](https://docs.mulesoft.com/mule-runtime/4.6/deploy-on-premises#mmp-deploy-agent) for instructions. - Standalone runtime deployment Deploy your Mule application to a Mule instance running on your machine. See [Deploy a Mule Application to a Standalone Mule Runtime Engine](https://docs.mulesoft.com/mule-runtime/4.6/deploy-on-premises#mmp-deploy-standalone) for instructions. ## Compatibility - Mule 4.x - Anypoint Studio 7.x ## Mule Maven Plugin Goals The Mule Maven plugin provides the following goals: - `package` Generates the jar file for your project. - `deploy` Automatically uploads and starts your application in any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). - `mule:deploy` Deploys an artifact from the specified location. - `mule:undeploy` Automatically removes your application from any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). Each goal accepts parameters that are unique to the desired plugin behavior. To provide a parameter from the command line, prepend `-D` to the parameter name. ### Package Goal The `package` goal generates the application JAR file. This goal binds by default to the Maven lifecycle phase: `package`. Optional Parameters
NameTypeDescription

onlyMuleSources

boolean

Generates the application JAR file containing only the source code. This property is just for sharing purposes.

attachMuleSources

boolean

Attaches the source code inside the generated JAR file.

lightweightPackage

boolean

Doesn’t generate the repository with all the application dependencies inside the JAR file. This property is just for sharing purposes.

For example, to execute the `package` goal and set the `attachMuleSources` parameter, you run the following command: ```console mvn package -DattachMuleSources ``` ### Deploy Goal This goal uploads and deploys the application JAR file to any of the application deployment targets. The deploy goal binds by default to the Maven lifecycle phase: `deploy`. Optional Parameters
NameTypeDescription

artifact

String

Path to the application JAR file to be deployed. By default is set to the application target folder.

muleDeploy

boolean

Instructs the plugin to deploy using the deployment strategy defined in the plugin configuration. If the muleDeploy parameter is not set, the plugin uploads the artifacts to the repository defined in the distributionManagement section of the application’s pom.xml file.

For example, to execute the `deploy` goal and set the `muleDeploy` parameter, you run the following command: ```console mvn deploy -DmuleDeploy ``` ### mule:deploy Goal This goal enables you to deploy an artifact without building it. To specify the artifact’s location, use the `mule.artifact` parameter. For example: ```console mvn mule:deploy -Dmule.artifact=myProject/myArtifact.jar ``` This property is valid for CloudHub, standalone, and on-premises deployments. ### mule:undeploy Goal This goal removes an application from any of the application deployment targets. It uses the information from the plugin configuration to remove the application from the defined deployment target. To execute the `undeploy` goal, run the following command: ```console mvn mule:undeploy ``` The undeploy goal also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Add the Mule Maven Plugin to a Mule Project Before you can perform any operations, you must add the Mule Maven plugin to your project. To add the Mule Maven plugin, you need to add its maven dependency to the project: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ``` From this repository: ```xml mule-public https://repository.mulesoft.org/nexus/content/repositories/releases ``` This enables the Mule Maven plugin in your project. > [!IMPORTANT] If `true` is not present, the plugin does not work. ## Skip Plugin Execution You can skip the plugin execution by setting the `skip` parameter to true inside your deployment configuration: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} true ``` ## Skip Deployment Verification You can skip the status verification of your deployed app by setting the `skipDeploymentVerification` parameter to true inside of any of the platform deployments (Cloudhub, Runtime Manager, and Runtime Fabric): ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ... true ... ``` If the `skipDeploymentVerification` parameter is not present, the default value is false. This feature is available in plugin version 3.2.5 and later. ## Configure Shared Libraries Shared libraries enable you to configure a dependency in your application and make this dependency accessible to all the connectors in your application. See [Shared Libraries](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#shared-libraries) for an in-depth explanation of this feature. To configure a dependency as a shared library, add the following elements inside your Mule Maven plugin configuration in your project’s `pom.xml` file: ```xml ${dependencyGroupID} ${dependencyArtifactID} ``` The following example configures Anypoint Connector for Database (Database Connector) in a project, and also configures the MySQL driver as a shared library: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true mysql mysql-connector-java org.mule.connectors mule-db-connector 1.5.0 mule-plugin mysql mysql-connector-java 5.1.33 ``` ## Configure Additional Plugin Dependencies Configuring additional plugin dependencies for a connector in your application makes those dependencies available for only that connector. Doing this enables you to configure different dependencies, or even multiple versions of the same dependency, for different connectors. See [Additional Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#additional-plugin-dependencies) for an in-depth explanation of this feature. To configure additional plugin dependencies, add the following elements inside your Mule Maven plugin configuration in your project’s `pom.xml` file: ```xml ${connectorGroupID} ${connectorArtifactID} ${dependencyGroupID} ${dependencyArtifactID} ${dependencyVersion} ``` The following example configures the Derby driver as a dependency of Database Connector: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} org.mule.connectors mule-db-connector org.apache.derby derby 10.11.1.1 ``` ## Mule Maven Plugin Reference The following links contain the parameter reference of each deployment strategy: - [CloudHub deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.6/deploy-to-cloudhub#cloudhub-deploy-reference) - [Runtime Fabric deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.6/deploy-to-rtf#rtf-deploy-reference) - [Standalone deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.6/deploy-on-premises#standalone-deploy-reference) - [Runtime Manager REST API deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.6/deploy-on-premises#arm-deploy-reference) - [Runtime Manager agent deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.6/deploy-on-premises#arm-agent-deploy-reference) ## See Also - [Classloading Isolation](https://docs.mulesoft.com/mule-runtime/4.6/about-classloading-isolation) - [Export Resources](https://docs.mulesoft.com/mule-runtime/4.6/how-to-export-resources) - [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven) - [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed) - [Runtime Manager REST API](https://docs.mulesoft.com/runtime-manager/runtime-manager-api) - [Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) --- product: Mule Runtime version: 4.9 --- # Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. The Mule Maven plugin enables you to integrate the packaging and deployment of your Mule applications with your Maven lifecycle. See [Package a Mule Application](https://docs.mulesoft.com/mule-runtime/4.9/package-a-mule-application) for packaging instructions. The Mule Maven plugin is compatible with Mule runtime engine (Enterprise Edition) and with Mule Kernel (Community Edition). Using the Mule Maven plugin, you can automate your Mule application deployment to CloudHub, to CloudHub 2.0, to Anypoint Runtime Fabric, or on-premises, using any of the following deployment strategies: - CloudHub deployment Deploys your Mule application to CloudHub. See [Deploy Applications to CloudHub](https://docs.mulesoft.com/mule-runtime/4.9/deploy-to-cloudhub) for instructions. - CloudHub 2.0 deployment Deploys your Mule application to CloudHub 2.0. See [Deploy Applications to CloudHub 2.0](https://docs.mulesoft.com/mule-runtime/4.9/deploy-to-cloudhub-2) for instructions. - Runtime Fabric deployment Deploys your Mule application to Anypoint Runtime Fabric. See [Deploy Applications to Anypoint Runtime Fabric](https://docs.mulesoft.com/mule-runtime/4.9/deploy-to-rtf) for instructions. - Runtime Manager REST API deployment Deploys your Mule application to your server, or server clusters using the Runtime Manager REST API. See [Deploy a Mule Application Using the Runtime Manager REST API](https://docs.mulesoft.com/mule-runtime/4.9/deploy-on-premises#mmp-deploy-arm) for instructions. - Runtime Manager agent deployment Deploy your Mule application using the Runtime Manager agent. This deployment strategy works only if all your Mule instances reside in one address space. See [Deploy a Mule Application Using the Runtime Manager Agent](https://docs.mulesoft.com/mule-runtime/4.9/deploy-on-premises#mmp-deploy-agent) for instructions. - Standalone runtime deployment Deploy your Mule application to a Mule instance running on your machine. See [Deploy a Mule Application to a Standalone Mule Runtime Engine](https://docs.mulesoft.com/mule-runtime/4.9/deploy-on-premises#mmp-deploy-standalone) for instructions. ## Compatibility - Mule 4.x - Anypoint Studio 7.x ## Mule Maven Plugin Goals The Mule Maven plugin provides the following goals: - `package` Generates the jar file for your project. - `deploy` Automatically uploads and starts your application in any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). - `mule:deploy` Deploys an artifact from the specified location. - `mule:undeploy` Automatically removes your application from any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). Each goal accepts parameters that are unique to the desired plugin behavior. To provide a parameter from the command line, prepend `-D` to the parameter name. ### Package Goal The `package` goal generates the application JAR file. This goal binds by default to the Maven lifecycle phase: `package`. Optional Parameters
NameTypeDescription

onlyMuleSources

boolean

Generates the application JAR file containing only the source code. This property is just for sharing purposes.

attachMuleSources

boolean

Attaches the source code inside the generated JAR file.

lightweightPackage

boolean

Doesn’t generate the repository with all the application dependencies inside the JAR file. This property is just for sharing purposes.

For example, to execute the `package` goal and set the `attachMuleSources` parameter, you run the following command: ```console mvn package -DattachMuleSources ``` ### Deploy Goal This goal uploads and deploys the application JAR file to any of the application deployment targets. The deploy goal binds by default to the Maven lifecycle phase: `deploy`. Optional Parameters
NameTypeDescription

artifact

String

Path to the application JAR file to be deployed. By default is set to the application target folder.

muleDeploy

boolean

Instructs the plugin to deploy using the deployment strategy defined in the plugin configuration. If the muleDeploy parameter is not set, the plugin uploads the artifacts to the repository defined in the distributionManagement section of the application’s pom.xml file.

For example, to execute the `deploy` goal and set the `muleDeploy` parameter, you run the following command: ```console mvn deploy -DmuleDeploy ``` ### mule:deploy Goal This goal enables you to deploy an artifact without building it. To specify the artifact’s location, use the `mule.artifact` parameter. For example: ```console mvn mule:deploy -Dmule.artifact=myProject/myArtifact.jar ``` This property is valid for CloudHub, standalone, and on-premises deployments. ### mule:undeploy Goal This goal removes an application from any of the application deployment targets. It uses the information from the plugin configuration to remove the application from the defined deployment target. To execute the `undeploy` goal, run the following command: ```console mvn mule:undeploy ``` The undeploy goal also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Add the Mule Maven Plugin to a Mule Project Before you can perform any operations, you must add the Mule Maven plugin to your project. To add the Mule Maven plugin, you need to add its maven dependency to the project: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ``` From this repository: ```xml mule-public https://repository.mulesoft.org/nexus/content/repositories/releases ``` This enables the Mule Maven plugin in your project. > [!IMPORTANT] If `true` is not present, the plugin does not work. ## Skip Plugin Execution You can skip the plugin execution by setting the `skip` parameter to true inside your deployment configuration: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} true ``` ## Skip Deployment Verification You can skip the status verification of your deployed app by setting the `skipDeploymentVerification` parameter to true inside of any of the platform deployments (Cloudhub, Runtime Manager, and Runtime Fabric): ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ... true ... ``` If the `skipDeploymentVerification` parameter is not present, the default value is false. This feature is available in plugin version 3.2.5 and later. ## Configure Shared Libraries Shared libraries enable you to configure a dependency in your application and make this dependency accessible to all the connectors in your application. See [Shared Libraries](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#shared-libraries) for an in-depth explanation of this feature. To configure a dependency as a shared library, add the following elements inside your Mule Maven plugin configuration in your project’s `pom.xml` file: ```xml ${dependencyGroupID} ${dependencyArtifactID} ``` The following example configures Anypoint Connector for Database (Database Connector) in a project, and also configures the MySQL driver as a shared library: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true mysql mysql-connector-java org.mule.connectors mule-db-connector 1.5.0 mule-plugin mysql mysql-connector-java 5.1.33 ``` ## Configure Additional Plugin Dependencies Configuring additional plugin dependencies for a connector in your application makes those dependencies available for only that connector. Doing this enables you to configure different dependencies, or even multiple versions of the same dependency, for different connectors. See [Additional Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#additional-plugin-dependencies) for an in-depth explanation of this feature. To configure additional plugin dependencies, add the following elements inside your Mule Maven plugin configuration in your project’s `pom.xml` file: ```xml ${connectorGroupID} ${connectorArtifactID} ${dependencyGroupID} ${dependencyArtifactID} ${dependencyVersion} ``` The following example configures the Derby driver as a dependency of Database Connector: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} org.mule.connectors mule-db-connector org.apache.derby derby 10.11.1.1 ``` ## Mule Maven Plugin Reference The following links contain the parameter reference of each deployment strategy: - [CloudHub deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.9/deploy-to-cloudhub#cloudhub-deploy-reference) - [Runtime Fabric deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.9/deploy-to-rtf#rtf-deploy-reference) - [Standalone deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.9/deploy-on-premises#standalone-deploy-reference) - [Runtime Manager REST API deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.9/deploy-on-premises#arm-deploy-reference) - [Runtime Manager agent deployment parameters reference](https://docs.mulesoft.com/mule-runtime/4.9/deploy-on-premises#arm-agent-deploy-reference) ## See Also - [Classloading Isolation](https://docs.mulesoft.com/mule-runtime/4.9/about-classloading-isolation) - [Export Resources](https://docs.mulesoft.com/mule-runtime/4.9/how-to-export-resources) - [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven) - [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed) - [Runtime Manager REST API](https://docs.mulesoft.com/runtime-manager/runtime-manager-api) - [Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) --- product: Mule Runtime version: 4.13 is-latest-version: true --- # Mule Maven Plugin > For the full documentation index, see: https://docs.mulesoft.com/llms.txt > [!WARNING] Mule Maven plugin versions 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, > 3.1.7, and 3.8.3 are deprecated. The Mule Maven plugin enables you to integrate the packaging and deployment of your Mule applications with your Maven lifecycle. See [Package a Mule Application](https://docs.mulesoft.com/mule-runtime/latest/package-a-mule-application) for packaging instructions. The Mule Maven plugin is compatible with Mule runtime engine (Enterprise Edition) and with Mule Kernel (Community Edition). Using the Mule Maven plugin, you can automate your Mule application deployment to CloudHub, to CloudHub 2.0, to Anypoint Runtime Fabric, or on-premises, using any of the following deployment strategies: - CloudHub deployment Deploys your Mule application to CloudHub. See [Deploy Applications to CloudHub](https://docs.mulesoft.com/mule-runtime/latest/deploy-to-cloudhub) for instructions. - CloudHub 2.0 deployment Deploys your Mule application to CloudHub 2.0. See [Deploy Applications to CloudHub 2.0](https://docs.mulesoft.com/mule-runtime/latest/deploy-to-cloudhub-2) for instructions. - Runtime Fabric deployment Deploys your Mule application to Anypoint Runtime Fabric. See [Deploy Applications to Anypoint Runtime Fabric](https://docs.mulesoft.com/mule-runtime/latest/deploy-to-rtf) for instructions. - Runtime Manager REST API deployment Deploys your Mule application to your server, or server clusters using the Runtime Manager REST API. See [Deploy a Mule Application Using the Runtime Manager REST API](https://docs.mulesoft.com/mule-runtime/latest/deploy-on-premises#mmp-deploy-arm) for instructions. - Runtime Manager agent deployment Deploy your Mule application using the Runtime Manager agent. This deployment strategy works only if all your Mule instances reside in one address space. See [Deploy a Mule Application Using the Runtime Manager Agent](https://docs.mulesoft.com/mule-runtime/latest/deploy-on-premises#mmp-deploy-agent) for instructions. - Standalone runtime deployment Deploy your Mule application to a Mule instance running on your machine. See [Deploy a Mule Application to a Standalone Mule Runtime Engine](https://docs.mulesoft.com/mule-runtime/latest/deploy-on-premises#mmp-deploy-standalone) for instructions. ## Compatibility - Mule 4.x - Anypoint Studio 7.x ## Mule Maven Plugin Goals The Mule Maven plugin provides the following goals: - `package` Generates the jar file for your project. - `deploy` Automatically uploads and starts your application in any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). - `mule:deploy` Deploys an artifact from the specified location. - `mule:undeploy` Automatically removes your application from any of the application deployment targets (CloudHub, Runtime Fabric, or On-Premises). Each goal accepts parameters that are unique to the desired plugin behavior. To provide a parameter from the command line, prepend `-D` to the parameter name. ### Package Goal The `package` goal generates the application JAR file. This goal binds by default to the Maven lifecycle phase: `package`. Optional Parameters
NameTypeDescription

onlyMuleSources

boolean

Generates the application JAR file containing only the source code. This property is just for sharing purposes.

attachMuleSources

boolean

Attaches the source code inside the generated JAR file.

lightweightPackage

boolean

Doesn’t generate the repository with all the application dependencies inside the JAR file. This property is just for sharing purposes.

For example, to execute the `package` goal and set the `attachMuleSources` parameter, you run the following command: ```console mvn package -DattachMuleSources ``` ### Deploy Goal This goal uploads and deploys the application JAR file to any of the application deployment targets. The deploy goal binds by default to the Maven lifecycle phase: `deploy`. Optional Parameters
NameTypeDescription

artifact

String

Path to the application JAR file to be deployed. By default is set to the application target folder.

muleDeploy

boolean

Instructs the plugin to deploy using the deployment strategy defined in the plugin configuration. If the muleDeploy parameter is not set, the plugin uploads the artifacts to the repository defined in the distributionManagement section of the application’s pom.xml file.

For example, to execute the `deploy` goal and set the `muleDeploy` parameter, you run the following command: ```console mvn deploy -DmuleDeploy ``` ### mule:deploy Goal This goal enables you to deploy an artifact without building it. To specify the artifact’s location, use the `mule.artifact` parameter. For example: ```console mvn mule:deploy -Dmule.artifact=myProject/myArtifact.jar ``` This property is valid for CloudHub, standalone, and on-premises deployments. ### mule:undeploy Goal This goal removes an application from any of the application deployment targets. It uses the information from the plugin configuration to remove the application from the defined deployment target. To execute the `undeploy` goal, run the following command: ```console mvn mule:undeploy ``` The undeploy goal also deletes the app in Mule Maven plugin 3.3.0 and later versions. ## Add the Mule Maven Plugin to a Mule Project Before you can perform any operations, you must add the Mule Maven plugin to your project. To add the Mule Maven plugin, you need to add its maven dependency to the project: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ``` From this repository: ```xml mule-public https://repository.mulesoft.org/nexus/content/repositories/releases ``` This enables the Mule Maven plugin in your project. > [!IMPORTANT] If `true` is not present, the plugin does not work. ## Skip Plugin Execution You can skip the plugin execution by setting the `skip` parameter to true inside your deployment configuration: ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ${mule.home.test} true ``` ## Skip Deployment Verification You can skip the status verification of your deployed app by setting the `skipDeploymentVerification` parameter to true inside of any of the platform deployments (Cloudhub, Runtime Manager, and Runtime Fabric): ```xml org.mule.tools.maven mule-maven-plugin 3.7.1 true ... true ... ``` If the `skipDeploymentVerification` parameter is not present, the default value is false. This feature is available in plugin version 3.2.5 and later. ## Configure Shared Libraries Shared libraries enable you to configure a dependency in your application and make this dependency accessible to all the connectors in your application. See [Shared Libraries](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#shared-libraries) for an in-depth explanation of this feature. To configure a dependency as a shared library, add the following elements inside your Mule Maven plugin configuration in your project’s `pom.xml` file: ```xml ${dependencyGroupID} ${dependencyArtifactID} ``` The following example configures Anypoint Connector for Database (Database Connector) in a project, and also configures the MySQL driver as a shared library: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} true mysql mysql-connector-java org.mule.connectors mule-db-connector 1.5.0 mule-plugin mysql mysql-connector-java 5.1.33 ``` ## Configure Additional Plugin Dependencies Configuring additional plugin dependencies for a connector in your application makes those dependencies available for only that connector. Doing this enables you to configure different dependencies, or even multiple versions of the same dependency, for different connectors. See [Additional Plugin Dependencies](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation#additional-plugin-dependencies) for an in-depth explanation of this feature. To configure additional plugin dependencies, add the following elements inside your Mule Maven plugin configuration in your project’s `pom.xml` file: ```xml ${connectorGroupID} ${connectorArtifactID} ${dependencyGroupID} ${dependencyArtifactID} ${dependencyVersion} ``` The following example configures the Derby driver as a dependency of Database Connector: ```xml org.mule.tools.maven mule-maven-plugin ${mule.maven.plugin.version} org.mule.connectors mule-db-connector org.apache.derby derby 10.11.1.1 ``` ## Mule Maven Plugin Reference The following links contain the parameter reference of each deployment strategy: - [CloudHub deployment parameters reference](https://docs.mulesoft.com/mule-runtime/latest/deploy-to-cloudhub#cloudhub-deploy-reference) - [Runtime Fabric deployment parameters reference](https://docs.mulesoft.com/mule-runtime/latest/deploy-to-rtf#rtf-deploy-reference) - [Standalone deployment parameters reference](https://docs.mulesoft.com/mule-runtime/latest/deploy-on-premises#standalone-deploy-reference) - [Runtime Manager REST API deployment parameters reference](https://docs.mulesoft.com/mule-runtime/latest/deploy-on-premises#arm-deploy-reference) - [Runtime Manager agent deployment parameters reference](https://docs.mulesoft.com/mule-runtime/latest/deploy-on-premises#arm-agent-deploy-reference) ## See Also - [Classloading Isolation](https://docs.mulesoft.com/mule-runtime/latest/about-classloading-isolation) - [Export Resources](https://docs.mulesoft.com/mule-runtime/latest/how-to-export-resources) - [Publish and Deploy Exchange Assets Using Maven](https://docs.mulesoft.com/exchange/to-publish-assets-maven) - [Allocating Resources for Application Deployment on Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/deploy-resource-allocation-self-managed) - [Runtime Manager REST API](https://docs.mulesoft.com/runtime-manager/runtime-manager-api) - [Runtime Manager Agent](https://docs.mulesoft.com/runtime-manager/runtime-manager-agent) --- product: Mule Runtime version: 4.11 keywords: studio, components, elements, message, mule message, architecture --- # Mule Message Structure > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule message is the part of the Mule event that serves as a container for message content and metadata, typically from external sources, as it is processed within flows of a Mule app. The Mule message is immutable, so every change to a Mule message results in the creation of a new instance. Each processor in a flow that receives a message returns a new Mule message consisting of these parts: - A message `payload`, which contains the body of the message. For example: the content of a file, the HTTP body, a record from a database, or the response to a REST or Web Service request. - Message `attributes`, which are metadata associated with the payload, such as HTTP headers and query parameters. ![A Mule message including attributes and payload](/mulesoft/current/en-us/mule-runtime/4.11/_images/mule-message-structure-82af1.png) A Mule event source triggers a process that creates a Mule event with a Mule message and executes the Mule flow that contains the event source. For example, this process begins each time an [HTTP Listener](https://docs.mulesoft.com/http-connector/1.10/http-listener-ref) source receives a request or the [Scheduler](https://docs.mulesoft.com/mule-runtime/4.11/scheduler-concept) executes. After the flow begins its execution, downstream processors (such as Core components, File read operations, or the HTTP request operation) can then retrieve, set, and process Mule message data (payload and attributes) that reside in the Mule event according to their configurations. Note that in Anypoint Studio, the [DataSense Explorer](https://docs.mulesoft.com/studio/datasense-explorer) shows the structure of a Mule message at any given point of the flow. ## Message Payload The message payload contains the content or body of a message. For example, the payload can contain the results of an HTTP request, the content of records you retrieve through the Select operation of the Database connector, or the content of a file that you retrieve through a Read operation to the File or FTP connector. The payload content changes as it travels through a flow when message processors in a Mule flow set it, enrich it, transform it into a new format, extract information from it, or even store it in a Mule event variable and produce a new payload. You can select the payload of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), `payload`. For example, a Logger component configured to display the `payload` of a response to an HTTP request for the JSON content at `https://jsonplaceholder.typicode.com/users` outputs the following example JSON content in the Studio console: Example: HTTP Response Payload ```txt [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } } }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", "address": { "street": "Victor Plains", "city": "Wisokyburgh", "zipcode": "90566-7771", "geo": { "lat": "-43.9509", "lng": "-34.4618" } } } ] ``` A Logger component set to display the `payload` for the output of a File Read operation for a simple JSON file can output the following example JSON content in the Studio console: Example: File Payload ```txt { "hello" : "world" } ``` The next message processor in the flow can then act on this payload, for example, by selecting the value of the JSON object in the payload with `payload.'hello'` to replace the preceding JSON payload with the string, `"world"`. ## Attributes Attributes contain the metadata associated with the body (or payload) of the message. The specific attributes of a message depend on the connector (such as HTTP, FTP, File) associated with the message. Metadata can consist of headers and properties received or returned by a connector, as well as other metadata that is populated by the connector or through a Core component, such as Transform Message. You can select attributes of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), `attributes`. For example, when using the `attributes` variable to display HTTP response metadata through a Logger component, the Studio console outputs the following example HTTP response attributes: Example: HTTP Response Attributes ```txt { Status Code=200 Reason Phrase=OK Headers=[ date=Sun, 20 Jan 2019 19:13:51 GMT content-type=text/html; charset=UTF-8 transfer-encoding=chunked connection=keep-alive set-cookie=__cfduid=d03462713a0b2c57c8d2ad3bf311287041548011631; expires=Mon, 20-Jan-20 19:13:51 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 last-modified=Tue, 15 Jan 2019 18:17:15 GMT via=1.1 vegur cf-cache-status=HIT expires=Sun, 20 Jan 2019 23:13:51 GMT expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" server=cloudflare cf-ray=49c3dc570c2f281c-SJC ] } ``` The example is a response from an HTTP Request operation to the web page `https://jsonplaceholder.typicode.com/users`. Notice that each attribute is a key-value pair separated by an equal sign (`=`). When using a connector or component (such as the Logger) in your flow, you can use the `attribute` variable with specific attributes and their inner attributes to select the attribute values that you require, such as the status code or content type. For example, you can select the values of attributes in an HTTP response using the following syntax: - `attributes.statusCode` to select an HTTP status code like `200`. - `attributes.headers.date` to select `Sun, 20 Jan 2019 18:54:54 GMT` from the header of an HTTP response. - `attributes.headers.'content-type'` to select the HTTP content type `application/json`. To select the value of inner attributes like `content-type`, you must surround the name `content-type` in quotes. You do not need quotes around values like `date` because DataWeave applies the rules described in [Valid Identifiers for Attribute Names](#valid_identifiers) to inner values. To understand why you use `statusCode` for the selector instead of `'Status Code'` or `"Status Code"` to select the status code value, see the [note](#note_top_level_selectors) in that section. For file metadata, the attributes are different. For example, when using the `attributes` variable to display file metadata through a Logger component, the Studio console displays the following example content: Example: File Attributes ```txt LocalFileAttributes[ lastModifiedTime=2019-01-20T08:17:55, lastAccessTime=2019-01-20T10:54:55, creationTime=2019-01-20T08:17:55, size=22, regularFile=true, directory=false, symbolicLink=false, path=/Users/me/Desktop/myJson.json, fileName=myJson.json ``` Notice that each attribute is a key-value pair (such as `fileName=myJson.json`). You can select the value of an attribute by referencing its key, for example: - `attributes.'fileName'` to return the file name: `myJson.json`. - `attributes.size` to return the size of the file: `22`. ### Valid Identifiers for Attribute Names You can access and declare attribute names that follow the rules described in [Rules for Declaring Valid Identifiers](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction#valid-identifiers) without using any quotation marks. To use an attribute name that is not a valid identifier, surround the attribute name with any of the following characters: - Single quotation marks (`'`) - Double quotation marks (`"`) - Backticks (`` ` ``) For example, consider the following DataWeave variable declaration: ```java var myVar = { id : "1234", "123 abc !@#" : "some_value" } ``` Because attribute name `123 abc !@#` is not a valid identifier, you must use quotation marks or backticks to declare it. To access the value from attribute `123 abc !@#`, which is `"some_value"`, use quotation marks or backticks: ```none myVar.'123 abc !@#' ``` Using quotation marks or backticks to declare an attribute or select a value from an attribute when the attribute name is a valid identifier is optional. In the previous variable declaration example, attribute `id` is declared without using any quotation marks. To access the value stored in attribute `id`, you can use any of the following methods: - `myVar.id` - `myVar.'id'` - `myVar."id"` - `` myVar.`id` `` Note that human-readable names, such as `Status Code`, that you see in console output for top-level attributes can differ from the name to use for selecting the attribute, which is `statusCode`. Putting quotes around the human-readable name `Status Code` returns `null` instead of making that top-level attribute selectable. You can find the syntax to use for selecting the top-level attribute names, such as `Status Code`, `Reason Phrase`, and `Headers`, through [autocompletion in Studio](https://docs.mulesoft.com/studio/datasense-concept#using-datasense-for-autocomplete) or in the connector documentation, for example, in [HTTP Request](https://docs.mulesoft.com/http-connector/1.10/http-connector-xml-reference#http-request) documentation. ## See Also - [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-event) - [DataWeave Selectors](https://docs.mulesoft.com/dataweave/latest/dataweave-selectors) - [Set Payload Transformer](https://docs.mulesoft.com/mule-runtime/4.11/set-payload-transformer-reference) --- product: Mule Runtime version: 4.12 keywords: studio, components, elements, message, mule message, architecture --- # Mule Message Structure > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule message is the part of the Mule event that serves as a container for message content and metadata, typically from external sources, as it is processed within flows of a Mule app. The Mule message is immutable, so every change to a Mule message results in the creation of a new instance. Each processor in a flow that receives a message returns a new Mule message consisting of these parts: - A message `payload`, which contains the body of the message. For example: the content of a file, the HTTP body, a record from a database, or the response to a REST or Web Service request. - Message `attributes`, which are metadata associated with the payload, such as HTTP headers and query parameters. ![A Mule message including attributes and payload](/mulesoft/current/en-us/mule-runtime/4.12/_images/mule-message-structure-82af1.png) A Mule event source triggers a process that creates a Mule event with a Mule message and executes the Mule flow that contains the event source. For example, this process begins each time an [HTTP Listener](https://docs.mulesoft.com/http-connector/1.10/http-listener-ref) source receives a request or the [Scheduler](https://docs.mulesoft.com/mule-runtime/4.12/scheduler-concept) executes. After the flow begins its execution, downstream processors (such as Core components, File read operations, or the HTTP request operation) can then retrieve, set, and process Mule message data (payload and attributes) that reside in the Mule event according to their configurations. Note that in Anypoint Studio, the [DataSense Explorer](https://docs.mulesoft.com/studio/datasense-explorer) shows the structure of a Mule message at any given point of the flow. ## Message Payload The message payload contains the content or body of a message. For example, the payload can contain the results of an HTTP request, the content of records you retrieve through the Select operation of the Database connector, or the content of a file that you retrieve through a Read operation to the File or FTP connector. The payload content changes as it travels through a flow when message processors in a Mule flow set it, enrich it, transform it into a new format, extract information from it, or even store it in a Mule event variable and produce a new payload. You can select the payload of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), `payload`. For example, a Logger component configured to display the `payload` of a response to an HTTP request for the JSON content at `https://jsonplaceholder.typicode.com/users` outputs the following example JSON content in the Studio console: Example: HTTP Response Payload ```txt [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } } }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", "address": { "street": "Victor Plains", "city": "Wisokyburgh", "zipcode": "90566-7771", "geo": { "lat": "-43.9509", "lng": "-34.4618" } } } ] ``` A Logger component set to display the `payload` for the output of a File Read operation for a simple JSON file can output the following example JSON content in the Studio console: Example: File Payload ```txt { "hello" : "world" } ``` The next message processor in the flow can then act on this payload, for example, by selecting the value of the JSON object in the payload with `payload.'hello'` to replace the preceding JSON payload with the string, `"world"`. ## Attributes Attributes contain the metadata associated with the body (or payload) of the message. The specific attributes of a message depend on the connector (such as HTTP, FTP, File) associated with the message. Metadata can consist of headers and properties received or returned by a connector, as well as other metadata that is populated by the connector or through a Core component, such as Transform Message. You can select attributes of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), `attributes`. For example, when using the `attributes` variable to display HTTP response metadata through a Logger component, the Studio console outputs the following example HTTP response attributes: Example: HTTP Response Attributes ```txt { Status Code=200 Reason Phrase=OK Headers=[ date=Sun, 20 Jan 2019 19:13:51 GMT content-type=text/html; charset=UTF-8 transfer-encoding=chunked connection=keep-alive set-cookie=__cfduid=d03462713a0b2c57c8d2ad3bf311287041548011631; expires=Mon, 20-Jan-20 19:13:51 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 last-modified=Tue, 15 Jan 2019 18:17:15 GMT via=1.1 vegur cf-cache-status=HIT expires=Sun, 20 Jan 2019 23:13:51 GMT expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" server=cloudflare cf-ray=49c3dc570c2f281c-SJC ] } ``` The example is a response from an HTTP Request operation to the web page `https://jsonplaceholder.typicode.com/users`. Notice that each attribute is a key-value pair separated by an equal sign (`=`). When using a connector or component (such as the Logger) in your flow, you can use the `attribute` variable with specific attributes and their inner attributes to select the attribute values that you require, such as the status code or content type. For example, you can select the values of attributes in an HTTP response using the following syntax: - `attributes.statusCode` to select an HTTP status code like `200`. - `attributes.headers.date` to select `Sun, 20 Jan 2019 18:54:54 GMT` from the header of an HTTP response. - `attributes.headers.'content-type'` to select the HTTP content type `application/json`. To select the value of inner attributes like `content-type`, you must surround the name `content-type` in quotes. You do not need quotes around values like `date` because DataWeave applies the rules described in [Valid Identifiers for Attribute Names](#valid_identifiers) to inner values. To understand why you use `statusCode` for the selector instead of `'Status Code'` or `"Status Code"` to select the status code value, see the [note](#note_top_level_selectors) in that section. For file metadata, the attributes are different. For example, when using the `attributes` variable to display file metadata through a Logger component, the Studio console displays the following example content: Example: File Attributes ```txt LocalFileAttributes[ lastModifiedTime=2019-01-20T08:17:55, lastAccessTime=2019-01-20T10:54:55, creationTime=2019-01-20T08:17:55, size=22, regularFile=true, directory=false, symbolicLink=false, path=/Users/me/Desktop/myJson.json, fileName=myJson.json ``` Notice that each attribute is a key-value pair (such as `fileName=myJson.json`). You can select the value of an attribute by referencing its key, for example: - `attributes.'fileName'` to return the file name: `myJson.json`. - `attributes.size` to return the size of the file: `22`. ### Valid Identifiers for Attribute Names You can access and declare attribute names that follow the rules described in [Rules for Declaring Valid Identifiers](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction#valid-identifiers) without using any quotation marks. To use an attribute name that is not a valid identifier, surround the attribute name with any of the following characters: - Single quotation marks (`'`) - Double quotation marks (`"`) - Backticks (`` ` ``) For example, consider the following DataWeave variable declaration: ```java var myVar = { id : "1234", "123 abc !@#" : "some_value" } ``` Because attribute name `123 abc !@#` is not a valid identifier, you must use quotation marks or backticks to declare it. To access the value from attribute `123 abc !@#`, which is `"some_value"`, use quotation marks or backticks: ```none myVar.'123 abc !@#' ``` Using quotation marks or backticks to declare an attribute or select a value from an attribute when the attribute name is a valid identifier is optional. In the previous variable declaration example, attribute `id` is declared without using any quotation marks. To access the value stored in attribute `id`, you can use any of the following methods: - `myVar.id` - `myVar.'id'` - `myVar."id"` - `` myVar.`id` `` Note that human-readable names, such as `Status Code`, that you see in console output for top-level attributes can differ from the name to use for selecting the attribute, which is `statusCode`. Putting quotes around the human-readable name `Status Code` returns `null` instead of making that top-level attribute selectable. You can find the syntax to use for selecting the top-level attribute names, such as `Status Code`, `Reason Phrase`, and `Headers`, through [autocompletion in Studio](https://docs.mulesoft.com/studio/datasense-concept#using-datasense-for-autocomplete) or in the connector documentation, for example, in [HTTP Request](https://docs.mulesoft.com/http-connector/1.10/http-connector-xml-reference#http-request) documentation. ## See Also - [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-event) - [DataWeave Selectors](https://docs.mulesoft.com/dataweave/latest/dataweave-selectors) - [Set Payload Transformer](https://docs.mulesoft.com/mule-runtime/4.12/set-payload-transformer-reference) --- product: Mule Runtime version: 4.3 keywords: studio, components, elements, message, mule message, architecture --- # Mule Message Structure > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule message is the part of the Mule event that serves as a container for message content and metadata, typically from external sources, as it is processed within flows of a Mule app. The Mule message is immutable, so every change to a Mule message results in the creation of a new instance. Each processor in a flow that receives a message returns a new Mule message consisting of these parts: - A message `payload`, which contains the body of the message. For example: the content of a file, a record from a database, or the response to a REST or Web Service request. - Message `attributes`, which are metadata associated with the payload. ![mule message structure 82af1](/mulesoft/current/en-us/mule-runtime/4.3/_images/mule-message-structure-82af1.png) A Mule message is created as part of a [Mule event](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-event) when a Message source in a Mule flow triggers a flow to start, as when an HTTP listener receives a response or each time the Scheduler component triggers an execution of the flow. For example, when an HTTP listener in a Mule app receives a response, it creates a Mule event with a Mule message that contains the content of the response as its payload along with the metadata associated with that content, such as HTTP headers, as it attributes. Message processors in the flow (such as Core components, File read operations, or the HTTP request operations) can then retrieve, set, and process Mule message data that resides in the Mule event according to their configurations. Note that in Anypoint Studio, the [DataSense Explorer](https://docs.mulesoft.com/studio/datasense-explorer) shows the structure of a Mule message at any given point of the flow. ## Message Payload The message payload contains the content or body of a message. For example, the payload can contain the results of an HTTP request, the content of records you retrieve through the Select operation of the Database connector, or the content of a file that you retrieve through a Read operation to the File or FTP connector. The payload content changes as it travels through a flow when message processors in a Mule flow set it, enrich it, transform it into a new format, extract information from it, or even store it in a Mule event variable and produce a new payload. You can select the payload of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/2.3/dataweave-variables-context), `payload`. For example, a Logger component configured to display the `payload` of a response to an HTTP request for the JSON content at `https://jsonplaceholder.typicode.com/users` outputs the following example JSON content in the Studio console: Example: HTTP Response Payload ```txt [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } } }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", "address": { "street": "Victor Plains", "city": "Wisokyburgh", "zipcode": "90566-7771", "geo": { "lat": "-43.9509", "lng": "-34.4618" } } } ] ``` A Logger component set to display the `payload` for the output of a File Read operation for a simple JSON file can output the following example JSON content in the Studio console: Example: File Payload ```txt { "hello" : "world" } ``` The next message processor in the flow can then act on this payload, for example, by selecting the value of the JSON object in the payload with `payload.'hello'` to replace the preceding JSON payload with the string, `"world"`. ## Attributes Attributes contain the metadata associated with the body (or payload) of the message. The specific attributes of a message depend on the connector (such as HTTP, FTP, File) associated with the message. Metadata can consist of headers and properties received or returned by a connector, as well as other metadata that is populated by the connector or through a Core component, such as Transform Message. You can select attributes of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/2.3/dataweave-variables-context), `attributes`. For example, when using the `attributes` variable to display HTTP response metadata through a Logger component, the Studio console outputs the following example HTTP response attributes: Example: HTTP Response Attributes ```txt { Status Code=200 Reason Phrase=OK Headers=[ date=Sun, 20 Jan 2019 19:13:51 GMT content-type=text/html; charset=UTF-8 transfer-encoding=chunked connection=keep-alive set-cookie=__cfduid=d03462713a0b2c57c8d2ad3bf311287041548011631; expires=Mon, 20-Jan-20 19:13:51 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 last-modified=Tue, 15 Jan 2019 18:17:15 GMT via=1.1 vegur cf-cache-status=HIT expires=Sun, 20 Jan 2019 23:13:51 GMT expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" server=cloudflare cf-ray=49c3dc570c2f281c-SJC ] } ``` The example is a response from an HTTP Request operation to the web page `https://jsonplaceholder.typicode.com/users`. Notice that each attribute is a key-value pair separated by an equal sign (`=`). When using a connector or component (such as the Logger) in your flow, you can use the `attribute` variable with specific attributes and their inner attributes to select the attribute values that you require, such as the status code or content type. For example, you can select the values of attributes in an HTTP response using the following syntax: - `attributes.statusCode` to select an HTTP status code like `200`. - `attributes.headers.date` to select `Sun, 20 Jan 2019 18:54:54 GMT` from the header of an HTTP response. - `attributes.headers.'content-type'` to select the HTTP content type `application/json`. To select the value of inner attributes like `content-type`, you must surround the name `content-type` in quotes. You do not need quotes around values like `date` because DataWeave applies the rules described in [Valid Identifiers for Attribute Names](#valid_identifiers) to inner values. To understand why you use `statusCode` for the selector instead of `'Status Code'` or `"Status Code"` to select the status code value, see the [note](#note_top_level_selectors) in that section. For file metadata, the attributes are different. For example, when using the `attributes` variable to display file metadata through a Logger component, the Studio console displays the following example content: Example: File Attributes ```txt LocalFileAttributes[ lastModifiedTime=2019-01-20T08:17:55, lastAccessTime=2019-01-20T10:54:55, creationTime=2019-01-20T08:17:55, size=22, regularFile=true, directory=false, symbolicLink=false, path=/Users/me/Desktop/myJson.json, fileName=myJson.json ``` Notice that each attribute is a key-value pair (such as `fileName=myJson.json`). You can select the value of an attribute by referencing its key, for example: - `attributes.'fileName'` to return the file name: `myJson.json`. - `attributes.size` to return the size of the file: `22`. ### Valid Identifiers for Attribute Names You can access and declare attribute names that follow the rules described in [Rules for Declaring Valid Identifiers](https://docs.mulesoft.com/dataweave/2.3/dataweave-language-introduction#valid-identifiers) without using any quotation marks. To use an attribute name that is not a valid identifier, surround the attribute name with any of the following characters: - Single quotation marks (`'`) - Double quotation marks (`"`) - Backticks (`` ` ``) For example, consider the following DataWeave variable declaration: ```java var myVar = { id : "1234", "123 abc !@#" : "some_value" } ``` Because attribute name `123 abc !@#` is not a valid identifier, you must use quotation marks or backticks to declare it. To access the value from attribute `123 abc !@#`, which is `"some_value"`, use quotation marks or backticks: ```none myVar.'123 abc !@#' ``` Using quotation marks or backticks to declare an attribute or select a value from an attribute when the attribute name is a valid identifier is optional. In the previous variable declaration example, attribute `id` is declared without using any quotation marks. To access the value stored in attribute `id`, you can use any of the following methods: - `myVar.id` - `myVar.'id'` - `myVar."id"` - `` myVar.`id` `` Note that human-readable names, such as `Status Code`, that you see in console output for top-level attributes can differ from the name to use for selecting the attribute, which is `statusCode`. Putting quotes around the human-readable name `Status Code` returns `null` instead of making that top-level attribute selectable. You can find the syntax to use for selecting the top-level attribute names, such as `Status Code`, `Reason Phrase`, and `Headers`, through [autocompletion in Studio](https://docs.mulesoft.com/studio/datasense-concept#using-datasense-for-autocomplete) or in the connector documentation, for example, in [HTTP Request](https://docs.mulesoft.com/http-connector/1.10/http-connector-xml-reference#http-request) documentation. ## See Also - [Predefined Variables](https://docs.mulesoft.com/dataweave/2.3/dataweave-variables-context) - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-event) - [DataWeave Selectors](https://docs.mulesoft.com/dataweave/2.3/dataweave-selectors) - [Set Payload Transformer](https://docs.mulesoft.com/mule-runtime/4.3/set-payload-transformer-reference) --- product: Mule Runtime version: 4.4 keywords: studio, components, elements, message, mule message, architecture --- # Mule Message Structure > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule message is the part of the Mule event that serves as a container for message content and metadata, typically from external sources, as it is processed within flows of a Mule app. The Mule message is immutable, so every change to a Mule message results in the creation of a new instance. Each processor in a flow that receives a message returns a new Mule message consisting of these parts: - A message `payload`, which contains the body of the message. For example: the content of a file, the HTTP body, a record from a database, or the response to a REST or Web Service request. - Message `attributes`, which are metadata associated with the payload, such as HTTP headers and query parameters. ![mule message structure 82af1](/mulesoft/current/en-us/mule-runtime/4.4/_images/mule-message-structure-82af1.png) A Mule event source triggers a process that creates a Mule event with a Mule message and executes the Mule flow that contains the event source. For example, this process begins each time an [HTTP Listener](https://docs.mulesoft.com/http-connector/1.10/http-listener-ref) source receives a request or the [Scheduler](https://docs.mulesoft.com/mule-runtime/4.4/scheduler-concept) executes. After the flow begins its execution, downstream processors (such as Core components, File read operations, or the HTTP request operation) can then retrieve, set, and process Mule message data (payload and attributes) that reside in the Mule event according to their configurations. Note that in Anypoint Studio, the [DataSense Explorer](https://docs.mulesoft.com/studio/datasense-explorer) shows the structure of a Mule message at any given point of the flow. ## Message Payload The message payload contains the content or body of a message. For example, the payload can contain the results of an HTTP request, the content of records you retrieve through the Select operation of the Database connector, or the content of a file that you retrieve through a Read operation to the File or FTP connector. The payload content changes as it travels through a flow when message processors in a Mule flow set it, enrich it, transform it into a new format, extract information from it, or even store it in a Mule event variable and produce a new payload. You can select the payload of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), `payload`. For example, a Logger component configured to display the `payload` of a response to an HTTP request for the JSON content at `https://jsonplaceholder.typicode.com/users` outputs the following example JSON content in the Studio console: Example: HTTP Response Payload ```txt [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } } }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", "address": { "street": "Victor Plains", "city": "Wisokyburgh", "zipcode": "90566-7771", "geo": { "lat": "-43.9509", "lng": "-34.4618" } } } ] ``` A Logger component set to display the `payload` for the output of a File Read operation for a simple JSON file can output the following example JSON content in the Studio console: Example: File Payload ```txt { "hello" : "world" } ``` The next message processor in the flow can then act on this payload, for example, by selecting the value of the JSON object in the payload with `payload.'hello'` to replace the preceding JSON payload with the string, `"world"`. ## Attributes Attributes contain the metadata associated with the body (or payload) of the message. The specific attributes of a message depend on the connector (such as HTTP, FTP, File) associated with the message. Metadata can consist of headers and properties received or returned by a connector, as well as other metadata that is populated by the connector or through a Core component, such as Transform Message. You can select attributes of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), `attributes`. For example, when using the `attributes` variable to display HTTP response metadata through a Logger component, the Studio console outputs the following example HTTP response attributes: Example: HTTP Response Attributes ```txt { Status Code=200 Reason Phrase=OK Headers=[ date=Sun, 20 Jan 2019 19:13:51 GMT content-type=text/html; charset=UTF-8 transfer-encoding=chunked connection=keep-alive set-cookie=__cfduid=d03462713a0b2c57c8d2ad3bf311287041548011631; expires=Mon, 20-Jan-20 19:13:51 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 last-modified=Tue, 15 Jan 2019 18:17:15 GMT via=1.1 vegur cf-cache-status=HIT expires=Sun, 20 Jan 2019 23:13:51 GMT expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" server=cloudflare cf-ray=49c3dc570c2f281c-SJC ] } ``` The example is a response from an HTTP Request operation to the web page `https://jsonplaceholder.typicode.com/users`. Notice that each attribute is a key-value pair separated by an equal sign (`=`). When using a connector or component (such as the Logger) in your flow, you can use the `attribute` variable with specific attributes and their inner attributes to select the attribute values that you require, such as the status code or content type. For example, you can select the values of attributes in an HTTP response using the following syntax: - `attributes.statusCode` to select an HTTP status code like `200`. - `attributes.headers.date` to select `Sun, 20 Jan 2019 18:54:54 GMT` from the header of an HTTP response. - `attributes.headers.'content-type'` to select the HTTP content type `application/json`. To select the value of inner attributes like `content-type`, you must surround the name `content-type` in quotes. You do not need quotes around values like `date` because DataWeave applies the rules described in [Valid Identifiers for Attribute Names](#valid_identifiers) to inner values. To understand why you use `statusCode` for the selector instead of `'Status Code'` or `"Status Code"` to select the status code value, see the [note](#note_top_level_selectors) in that section. For file metadata, the attributes are different. For example, when using the `attributes` variable to display file metadata through a Logger component, the Studio console displays the following example content: Example: File Attributes ```txt LocalFileAttributes[ lastModifiedTime=2019-01-20T08:17:55, lastAccessTime=2019-01-20T10:54:55, creationTime=2019-01-20T08:17:55, size=22, regularFile=true, directory=false, symbolicLink=false, path=/Users/me/Desktop/myJson.json, fileName=myJson.json ``` Notice that each attribute is a key-value pair (such as `fileName=myJson.json`). You can select the value of an attribute by referencing its key, for example: - `attributes.'fileName'` to return the file name: `myJson.json`. - `attributes.size` to return the size of the file: `22`. ### Valid Identifiers for Attribute Names You can access and declare attribute names that follow the rules described in [Rules for Declaring Valid Identifiers](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction#valid-identifiers) without using any quotation marks. To use an attribute name that is not a valid identifier, surround the attribute name with any of the following characters: - Single quotation marks (`'`) - Double quotation marks (`"`) - Backticks (`` ` ``) For example, consider the following DataWeave variable declaration: ```java var myVar = { id : "1234", "123 abc !@#" : "some_value" } ``` Because attribute name `123 abc !@#` is not a valid identifier, you must use quotation marks or backticks to declare it. To access the value from attribute `123 abc !@#`, which is `"some_value"`, use quotation marks or backticks: ```none myVar.'123 abc !@#' ``` Using quotation marks or backticks to declare an attribute or select a value from an attribute when the attribute name is a valid identifier is optional. In the previous variable declaration example, attribute `id` is declared without using any quotation marks. To access the value stored in attribute `id`, you can use any of the following methods: - `myVar.id` - `myVar.'id'` - `myVar."id"` - `` myVar.`id` `` Note that human-readable names, such as `Status Code`, that you see in console output for top-level attributes can differ from the name to use for selecting the attribute, which is `statusCode`. Putting quotes around the human-readable name `Status Code` returns `null` instead of making that top-level attribute selectable. You can find the syntax to use for selecting the top-level attribute names, such as `Status Code`, `Reason Phrase`, and `Headers`, through [autocompletion in Studio](https://docs.mulesoft.com/studio/datasense-concept#using-datasense-for-autocomplete) or in the connector documentation, for example, in [HTTP Request](https://docs.mulesoft.com/http-connector/1.10/http-connector-xml-reference#http-request) documentation. ## See Also - [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-event) - [DataWeave Selectors](https://docs.mulesoft.com/dataweave/latest/dataweave-selectors) - [Set Payload Transformer](https://docs.mulesoft.com/mule-runtime/4.4/set-payload-transformer-reference) --- product: Mule Runtime version: 4.6 keywords: studio, components, elements, message, mule message, architecture --- # Mule Message Structure > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule message is the part of the Mule event that serves as a container for message content and metadata, typically from external sources, as it is processed within flows of a Mule app. The Mule message is immutable, so every change to a Mule message results in the creation of a new instance. Each processor in a flow that receives a message returns a new Mule message consisting of these parts: - A message `payload`, which contains the body of the message. For example: the content of a file, the HTTP body, a record from a database, or the response to a REST or Web Service request. - Message `attributes`, which are metadata associated with the payload, such as HTTP headers and query parameters. ![mule message structure 82af1](/mulesoft/current/en-us/mule-runtime/4.6/_images/mule-message-structure-82af1.png) A Mule event source triggers a process that creates a Mule event with a Mule message and executes the Mule flow that contains the event source. For example, this process begins each time an [HTTP Listener](https://docs.mulesoft.com/http-connector/1.10/http-listener-ref) source receives a request or the [Scheduler](https://docs.mulesoft.com/mule-runtime/4.6/scheduler-concept) executes. After the flow begins its execution, downstream processors (such as Core components, File read operations, or the HTTP request operation) can then retrieve, set, and process Mule message data (payload and attributes) that reside in the Mule event according to their configurations. Note that in Anypoint Studio, the [DataSense Explorer](https://docs.mulesoft.com/studio/datasense-explorer) shows the structure of a Mule message at any given point of the flow. ## Message Payload The message payload contains the content or body of a message. For example, the payload can contain the results of an HTTP request, the content of records you retrieve through the Select operation of the Database connector, or the content of a file that you retrieve through a Read operation to the File or FTP connector. The payload content changes as it travels through a flow when message processors in a Mule flow set it, enrich it, transform it into a new format, extract information from it, or even store it in a Mule event variable and produce a new payload. You can select the payload of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), `payload`. For example, a Logger component configured to display the `payload` of a response to an HTTP request for the JSON content at `https://jsonplaceholder.typicode.com/users` outputs the following example JSON content in the Studio console: Example: HTTP Response Payload ```txt [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } } }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", "address": { "street": "Victor Plains", "city": "Wisokyburgh", "zipcode": "90566-7771", "geo": { "lat": "-43.9509", "lng": "-34.4618" } } } ] ``` A Logger component set to display the `payload` for the output of a File Read operation for a simple JSON file can output the following example JSON content in the Studio console: Example: File Payload ```txt { "hello" : "world" } ``` The next message processor in the flow can then act on this payload, for example, by selecting the value of the JSON object in the payload with `payload.'hello'` to replace the preceding JSON payload with the string, `"world"`. ## Attributes Attributes contain the metadata associated with the body (or payload) of the message. The specific attributes of a message depend on the connector (such as HTTP, FTP, File) associated with the message. Metadata can consist of headers and properties received or returned by a connector, as well as other metadata that is populated by the connector or through a Core component, such as Transform Message. You can select attributes of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), `attributes`. For example, when using the `attributes` variable to display HTTP response metadata through a Logger component, the Studio console outputs the following example HTTP response attributes: Example: HTTP Response Attributes ```txt { Status Code=200 Reason Phrase=OK Headers=[ date=Sun, 20 Jan 2019 19:13:51 GMT content-type=text/html; charset=UTF-8 transfer-encoding=chunked connection=keep-alive set-cookie=__cfduid=d03462713a0b2c57c8d2ad3bf311287041548011631; expires=Mon, 20-Jan-20 19:13:51 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 last-modified=Tue, 15 Jan 2019 18:17:15 GMT via=1.1 vegur cf-cache-status=HIT expires=Sun, 20 Jan 2019 23:13:51 GMT expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" server=cloudflare cf-ray=49c3dc570c2f281c-SJC ] } ``` The example is a response from an HTTP Request operation to the web page `https://jsonplaceholder.typicode.com/users`. Notice that each attribute is a key-value pair separated by an equal sign (`=`). When using a connector or component (such as the Logger) in your flow, you can use the `attribute` variable with specific attributes and their inner attributes to select the attribute values that you require, such as the status code or content type. For example, you can select the values of attributes in an HTTP response using the following syntax: - `attributes.statusCode` to select an HTTP status code like `200`. - `attributes.headers.date` to select `Sun, 20 Jan 2019 18:54:54 GMT` from the header of an HTTP response. - `attributes.headers.'content-type'` to select the HTTP content type `application/json`. To select the value of inner attributes like `content-type`, you must surround the name `content-type` in quotes. You do not need quotes around values like `date` because DataWeave applies the rules described in [Valid Identifiers for Attribute Names](#valid_identifiers) to inner values. To understand why you use `statusCode` for the selector instead of `'Status Code'` or `"Status Code"` to select the status code value, see the [note](#note_top_level_selectors) in that section. For file metadata, the attributes are different. For example, when using the `attributes` variable to display file metadata through a Logger component, the Studio console displays the following example content: Example: File Attributes ```txt LocalFileAttributes[ lastModifiedTime=2019-01-20T08:17:55, lastAccessTime=2019-01-20T10:54:55, creationTime=2019-01-20T08:17:55, size=22, regularFile=true, directory=false, symbolicLink=false, path=/Users/me/Desktop/myJson.json, fileName=myJson.json ``` Notice that each attribute is a key-value pair (such as `fileName=myJson.json`). You can select the value of an attribute by referencing its key, for example: - `attributes.'fileName'` to return the file name: `myJson.json`. - `attributes.size` to return the size of the file: `22`. ### Valid Identifiers for Attribute Names You can access and declare attribute names that follow the rules described in [Rules for Declaring Valid Identifiers](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction#valid-identifiers) without using any quotation marks. To use an attribute name that is not a valid identifier, surround the attribute name with any of the following characters: - Single quotation marks (`'`) - Double quotation marks (`"`) - Backticks (`` ` ``) For example, consider the following DataWeave variable declaration: ```java var myVar = { id : "1234", "123 abc !@#" : "some_value" } ``` Because attribute name `123 abc !@#` is not a valid identifier, you must use quotation marks or backticks to declare it. To access the value from attribute `123 abc !@#`, which is `"some_value"`, use quotation marks or backticks: ```none myVar.'123 abc !@#' ``` Using quotation marks or backticks to declare an attribute or select a value from an attribute when the attribute name is a valid identifier is optional. In the previous variable declaration example, attribute `id` is declared without using any quotation marks. To access the value stored in attribute `id`, you can use any of the following methods: - `myVar.id` - `myVar.'id'` - `myVar."id"` - `` myVar.`id` `` Note that human-readable names, such as `Status Code`, that you see in console output for top-level attributes can differ from the name to use for selecting the attribute, which is `statusCode`. Putting quotes around the human-readable name `Status Code` returns `null` instead of making that top-level attribute selectable. You can find the syntax to use for selecting the top-level attribute names, such as `Status Code`, `Reason Phrase`, and `Headers`, through [autocompletion in Studio](https://docs.mulesoft.com/studio/datasense-concept#using-datasense-for-autocomplete) or in the connector documentation, for example, in [HTTP Request](https://docs.mulesoft.com/http-connector/1.10/http-connector-xml-reference#http-request) documentation. ## See Also - [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-event) - [DataWeave Selectors](https://docs.mulesoft.com/dataweave/latest/dataweave-selectors) - [Set Payload Transformer](https://docs.mulesoft.com/mule-runtime/4.6/set-payload-transformer-reference) --- product: Mule Runtime version: 4.9 keywords: studio, components, elements, message, mule message, architecture --- # Mule Message Structure > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule message is the part of the Mule event that serves as a container for message content and metadata, typically from external sources, as it is processed within flows of a Mule app. The Mule message is immutable, so every change to a Mule message results in the creation of a new instance. Each processor in a flow that receives a message returns a new Mule message consisting of these parts: - A message `payload`, which contains the body of the message. For example: the content of a file, the HTTP body, a record from a database, or the response to a REST or Web Service request. - Message `attributes`, which are metadata associated with the payload, such as HTTP headers and query parameters. ![A Mule message including attributes and payload](/mulesoft/current/en-us/mule-runtime/4.9/_images/mule-message-structure-82af1.png) A Mule event source triggers a process that creates a Mule event with a Mule message and executes the Mule flow that contains the event source. For example, this process begins each time an [HTTP Listener](https://docs.mulesoft.com/http-connector/1.10/http-listener-ref) source receives a request or the [Scheduler](https://docs.mulesoft.com/mule-runtime/4.9/scheduler-concept) executes. After the flow begins its execution, downstream processors (such as Core components, File read operations, or the HTTP request operation) can then retrieve, set, and process Mule message data (payload and attributes) that reside in the Mule event according to their configurations. Note that in Anypoint Studio, the [DataSense Explorer](https://docs.mulesoft.com/studio/datasense-explorer) shows the structure of a Mule message at any given point of the flow. ## Message Payload The message payload contains the content or body of a message. For example, the payload can contain the results of an HTTP request, the content of records you retrieve through the Select operation of the Database connector, or the content of a file that you retrieve through a Read operation to the File or FTP connector. The payload content changes as it travels through a flow when message processors in a Mule flow set it, enrich it, transform it into a new format, extract information from it, or even store it in a Mule event variable and produce a new payload. You can select the payload of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), `payload`. For example, a Logger component configured to display the `payload` of a response to an HTTP request for the JSON content at `https://jsonplaceholder.typicode.com/users` outputs the following example JSON content in the Studio console: Example: HTTP Response Payload ```txt [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } } }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", "address": { "street": "Victor Plains", "city": "Wisokyburgh", "zipcode": "90566-7771", "geo": { "lat": "-43.9509", "lng": "-34.4618" } } } ] ``` A Logger component set to display the `payload` for the output of a File Read operation for a simple JSON file can output the following example JSON content in the Studio console: Example: File Payload ```txt { "hello" : "world" } ``` The next message processor in the flow can then act on this payload, for example, by selecting the value of the JSON object in the payload with `payload.'hello'` to replace the preceding JSON payload with the string, `"world"`. ## Attributes Attributes contain the metadata associated with the body (or payload) of the message. The specific attributes of a message depend on the connector (such as HTTP, FTP, File) associated with the message. Metadata can consist of headers and properties received or returned by a connector, as well as other metadata that is populated by the connector or through a Core component, such as Transform Message. You can select attributes of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), `attributes`. For example, when using the `attributes` variable to display HTTP response metadata through a Logger component, the Studio console outputs the following example HTTP response attributes: Example: HTTP Response Attributes ```txt { Status Code=200 Reason Phrase=OK Headers=[ date=Sun, 20 Jan 2019 19:13:51 GMT content-type=text/html; charset=UTF-8 transfer-encoding=chunked connection=keep-alive set-cookie=__cfduid=d03462713a0b2c57c8d2ad3bf311287041548011631; expires=Mon, 20-Jan-20 19:13:51 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 last-modified=Tue, 15 Jan 2019 18:17:15 GMT via=1.1 vegur cf-cache-status=HIT expires=Sun, 20 Jan 2019 23:13:51 GMT expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" server=cloudflare cf-ray=49c3dc570c2f281c-SJC ] } ``` The example is a response from an HTTP Request operation to the web page `https://jsonplaceholder.typicode.com/users`. Notice that each attribute is a key-value pair separated by an equal sign (`=`). When using a connector or component (such as the Logger) in your flow, you can use the `attribute` variable with specific attributes and their inner attributes to select the attribute values that you require, such as the status code or content type. For example, you can select the values of attributes in an HTTP response using the following syntax: - `attributes.statusCode` to select an HTTP status code like `200`. - `attributes.headers.date` to select `Sun, 20 Jan 2019 18:54:54 GMT` from the header of an HTTP response. - `attributes.headers.'content-type'` to select the HTTP content type `application/json`. To select the value of inner attributes like `content-type`, you must surround the name `content-type` in quotes. You do not need quotes around values like `date` because DataWeave applies the rules described in [Valid Identifiers for Attribute Names](#valid_identifiers) to inner values. To understand why you use `statusCode` for the selector instead of `'Status Code'` or `"Status Code"` to select the status code value, see the [note](#note_top_level_selectors) in that section. For file metadata, the attributes are different. For example, when using the `attributes` variable to display file metadata through a Logger component, the Studio console displays the following example content: Example: File Attributes ```txt LocalFileAttributes[ lastModifiedTime=2019-01-20T08:17:55, lastAccessTime=2019-01-20T10:54:55, creationTime=2019-01-20T08:17:55, size=22, regularFile=true, directory=false, symbolicLink=false, path=/Users/me/Desktop/myJson.json, fileName=myJson.json ``` Notice that each attribute is a key-value pair (such as `fileName=myJson.json`). You can select the value of an attribute by referencing its key, for example: - `attributes.'fileName'` to return the file name: `myJson.json`. - `attributes.size` to return the size of the file: `22`. ### Valid Identifiers for Attribute Names You can access and declare attribute names that follow the rules described in [Rules for Declaring Valid Identifiers](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction#valid-identifiers) without using any quotation marks. To use an attribute name that is not a valid identifier, surround the attribute name with any of the following characters: - Single quotation marks (`'`) - Double quotation marks (`"`) - Backticks (`` ` ``) For example, consider the following DataWeave variable declaration: ```java var myVar = { id : "1234", "123 abc !@#" : "some_value" } ``` Because attribute name `123 abc !@#` is not a valid identifier, you must use quotation marks or backticks to declare it. To access the value from attribute `123 abc !@#`, which is `"some_value"`, use quotation marks or backticks: ```none myVar.'123 abc !@#' ``` Using quotation marks or backticks to declare an attribute or select a value from an attribute when the attribute name is a valid identifier is optional. In the previous variable declaration example, attribute `id` is declared without using any quotation marks. To access the value stored in attribute `id`, you can use any of the following methods: - `myVar.id` - `myVar.'id'` - `myVar."id"` - `` myVar.`id` `` Note that human-readable names, such as `Status Code`, that you see in console output for top-level attributes can differ from the name to use for selecting the attribute, which is `statusCode`. Putting quotes around the human-readable name `Status Code` returns `null` instead of making that top-level attribute selectable. You can find the syntax to use for selecting the top-level attribute names, such as `Status Code`, `Reason Phrase`, and `Headers`, through [autocompletion in Studio](https://docs.mulesoft.com/studio/datasense-concept#using-datasense-for-autocomplete) or in the connector documentation, for example, in [HTTP Request](https://docs.mulesoft.com/http-connector/1.10/http-connector-xml-reference#http-request) documentation. ## See Also - [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) - [Mule Events](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-event) - [DataWeave Selectors](https://docs.mulesoft.com/dataweave/latest/dataweave-selectors) - [Set Payload Transformer](https://docs.mulesoft.com/mule-runtime/4.9/set-payload-transformer-reference) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: studio, components, elements, message, mule message, architecture --- # Mule Message Structure > For the full documentation index, see: https://docs.mulesoft.com/llms.txt A Mule message is the part of the Mule event that serves as a container for message content and metadata, typically from external sources, as it is processed within flows of a Mule app. The Mule message is immutable, so every change to a Mule message results in the creation of a new instance. Each processor in a flow that receives a message returns a new Mule message consisting of these parts: - A message `payload`, which contains the body of the message. For example: the content of a file, the HTTP body, a record from a database, or the response to a REST or Web Service request. - Message `attributes`, which are metadata associated with the payload, such as HTTP headers and query parameters. ![A Mule message including attributes and payload](/mulesoft/current/en-us/mule-runtime/latest/_images/mule-message-structure-82af1.png) A Mule event source triggers a process that creates a Mule event with a Mule message and executes the Mule flow that contains the event source. For example, this process begins each time an [HTTP Listener](https://docs.mulesoft.com/http-connector/1.10/http-listener-ref) source receives a request or the [Scheduler](https://docs.mulesoft.com/mule-runtime/latest/scheduler-concept) executes. After the flow begins its execution, downstream processors (such as Core components, File read operations, or the HTTP request operation) can then retrieve, set, and process Mule message data (payload and attributes) that reside in the Mule event according to their configurations. Note that in Anypoint Studio, the [DataSense Explorer](https://docs.mulesoft.com/studio/datasense-explorer) shows the structure of a Mule message at any given point of the flow. ## Message Payload The message payload contains the content or body of a message. For example, the payload can contain the results of an HTTP request, the content of records you retrieve through the Select operation of the Database connector, or the content of a file that you retrieve through a Read operation to the File or FTP connector. The payload content changes as it travels through a flow when message processors in a Mule flow set it, enrich it, transform it into a new format, extract information from it, or even store it in a Mule event variable and produce a new payload. You can select the payload of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), `payload`. For example, a Logger component configured to display the `payload` of a response to an HTTP request for the JSON content at `https://jsonplaceholder.typicode.com/users` outputs the following example JSON content in the Studio console: Example: HTTP Response Payload ```txt [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } } }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", "address": { "street": "Victor Plains", "city": "Wisokyburgh", "zipcode": "90566-7771", "geo": { "lat": "-43.9509", "lng": "-34.4618" } } } ] ``` A Logger component set to display the `payload` for the output of a File Read operation for a simple JSON file can output the following example JSON content in the Studio console: Example: File Payload ```txt { "hello" : "world" } ``` The next message processor in the flow can then act on this payload, for example, by selecting the value of the JSON object in the payload with `payload.'hello'` to replace the preceding JSON payload with the string, `"world"`. ## Attributes Attributes contain the metadata associated with the body (or payload) of the message. The specific attributes of a message depend on the connector (such as HTTP, FTP, File) associated with the message. Metadata can consist of headers and properties received or returned by a connector, as well as other metadata that is populated by the connector or through a Core component, such as Transform Message. You can select attributes of a Mule message through a DataWeave expression that uses the [Mule Runtime variable](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context), `attributes`. For example, when using the `attributes` variable to display HTTP response metadata through a Logger component, the Studio console outputs the following example HTTP response attributes: Example: HTTP Response Attributes ```txt { Status Code=200 Reason Phrase=OK Headers=[ date=Sun, 20 Jan 2019 19:13:51 GMT content-type=text/html; charset=UTF-8 transfer-encoding=chunked connection=keep-alive set-cookie=__cfduid=d03462713a0b2c57c8d2ad3bf311287041548011631; expires=Mon, 20-Jan-20 19:13:51 GMT; path=/; domain=.typicode.com; HttpOnly x-powered-by=Express vary=Origin, Accept-Encoding access-control-allow-credentials=true cache-control=public, max-age=14400 last-modified=Tue, 15 Jan 2019 18:17:15 GMT via=1.1 vegur cf-cache-status=HIT expires=Sun, 20 Jan 2019 23:13:51 GMT expect-ct=max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" server=cloudflare cf-ray=49c3dc570c2f281c-SJC ] } ``` The example is a response from an HTTP Request operation to the web page `https://jsonplaceholder.typicode.com/users`. Notice that each attribute is a key-value pair separated by an equal sign (`=`). When using a connector or component (such as the Logger) in your flow, you can use the `attribute` variable with specific attributes and their inner attributes to select the attribute values that you require, such as the status code or content type. For example, you can select the values of attributes in an HTTP response using the following syntax: - `attributes.statusCode` to select an HTTP status code like `200`. - `attributes.headers.date` to select `Sun, 20 Jan 2019 18:54:54 GMT` from the header of an HTTP response. - `attributes.headers.'content-type'` to select the HTTP content type `application/json`. To select the value of inner attributes like `content-type`, you must surround the name `content-type` in quotes. You do not need quotes around values like `date` because DataWeave applies the rules described in [Valid Identifiers for Attribute Names](#valid_identifiers) to inner values. To understand why you use `statusCode` for the selector instead of `'Status Code'` or `"Status Code"` to select the status code value, see the [note](#note_top_level_selectors) in that section. For file metadata, the attributes are different. For example, when using the `attributes` variable to display file metadata through a Logger component, the Studio console displays the following example content: Example: File Attributes ```txt LocalFileAttributes[ lastModifiedTime=2019-01-20T08:17:55, lastAccessTime=2019-01-20T10:54:55, creationTime=2019-01-20T08:17:55, size=22, regularFile=true, directory=false, symbolicLink=false, path=/Users/me/Desktop/myJson.json, fileName=myJson.json ``` Notice that each attribute is a key-value pair (such as `fileName=myJson.json`). You can select the value of an attribute by referencing its key, for example: - `attributes.'fileName'` to return the file name: `myJson.json`. - `attributes.size` to return the size of the file: `22`. ### Valid Identifiers for Attribute Names You can access and declare attribute names that follow the rules described in [Rules for Declaring Valid Identifiers](https://docs.mulesoft.com/dataweave/latest/dataweave-language-introduction#valid-identifiers) without using any quotation marks. To use an attribute name that is not a valid identifier, surround the attribute name with any of the following characters: - Single quotation marks (`'`) - Double quotation marks (`"`) - Backticks (`` ` ``) For example, consider the following DataWeave variable declaration: ```java var myVar = { id : "1234", "123 abc !@#" : "some_value" } ``` Because attribute name `123 abc !@#` is not a valid identifier, you must use quotation marks or backticks to declare it. To access the value from attribute `123 abc !@#`, which is `"some_value"`, use quotation marks or backticks: ```none myVar.'123 abc !@#' ``` Using quotation marks or backticks to declare an attribute or select a value from an attribute when the attribute name is a valid identifier is optional. In the previous variable declaration example, attribute `id` is declared without using any quotation marks. To access the value stored in attribute `id`, you can use any of the following methods: - `myVar.id` - `myVar.'id'` - `myVar."id"` - `` myVar.`id` `` Note that human-readable names, such as `Status Code`, that you see in console output for top-level attributes can differ from the name to use for selecting the attribute, which is `statusCode`. Putting quotes around the human-readable name `Status Code` returns `null` instead of making that top-level attribute selectable. You can find the syntax to use for selecting the top-level attribute names, such as `Status Code`, `Reason Phrase`, and `Headers`, through [autocompletion in Studio](https://docs.mulesoft.com/studio/datasense-concept#using-datasense-for-autocomplete) or in the connector documentation, for example, in [HTTP Request](https://docs.mulesoft.com/http-connector/1.10/http-connector-xml-reference#http-request) documentation. ## See Also - [Predefined Variables](https://docs.mulesoft.com/dataweave/latest/dataweave-variables-context) - [Mule Events](https://docs.mulesoft.com/mule-runtime/latest/about-mule-event) - [DataWeave Selectors](https://docs.mulesoft.com/dataweave/latest/dataweave-selectors) - [Set Payload Transformer](https://docs.mulesoft.com/mule-runtime/latest/set-payload-transformer-reference) --- product: Mule Runtime version: 4.11 keywords: mule, getting started, transform, message, payload --- # Mule Runtime Engine Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) is a lightweight integration engine that runs Mule applications and supports domains and policies. Mule applications, domains, and policies share an XML DSL (domain-specific language). ## Mule Applications Mule applications connect systems, services, APIs, and devices using API-led connectivity instead of point-to-point integrations. Mule applications provide functionality for message routing, data mapping, orchestration, reliability, security, and scalability. Anypoint Studio supports Mule application development. ## Mule Domains Domains enable you to share global configurations that Mule applications need to reuse, such as default error handlers, shared properties, scheduler pools, and component configurations. You can only deploy domains when running Mule runtime engine on premises. See [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.11/shared-resources) for information about developing and configuring Mule domains by using Anypoint Studio. See [Deploy a Domain](https://docs.mulesoft.com/mule-runtime/4.11/deploy-on-premises#deploy-a-domain) for domain deployment instructions. ## Policies Policies on HTTP-based APIs can enforce security, regulate traffic through Mule applications, and adapt APIs to your business needs. Mule includes an embedded API Gateway, which enables you to apply security policies to an API, enrich incoming or outgoing messages, and add capabilities to an API without having to write any code. See [API Gateway Capabilities](https://docs.mulesoft.com/mule-gateway/mule-gateway-capabilities-mule4) for additional information. API Manager supports the configuration of automated policies. Custom policy development and configuration are also supported. ## Maven Support Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality. For the Mule runtime engine, you can integrate the packaging, testing, and deployment of your Mule applications, domains, and custom policies with your Maven lifecycle using the Mule Maven plugin. For details, see [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.11/using-maven-with-mule). ## Mule Installation, Deployment, and Management For a Mule app to run, it must be deployed to an environment where the Mule runtime engine is installed. Mule is packaged within the [Studio](https://docs.mulesoft.com/studio/) IDE and with [Design Center](https://docs.mulesoft.com/design-center/) on Anypoint Platform so that you can run a Mule app as you design it. MuleSoft provides different options for hosting the Anypoint Platform runtime plane: - CloudHub 2.0 CloudHub 2.0 is a fully managed, containerized integration platform as a service (iPaaS) where you can deploy APIs and integrations as lightweight containers in the cloud. CloudHub 2.0 provides for deployments across 12 regions globally, either single or shared tenancy, and dynamically scales infrastructure and built-in services up or down to support elastic transaction volumes. See [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) for more information. - CloudHub 1.0 CloudHub is MuleSoft’s cloud-based environment for hosting the Mule runtime server and related services. CloudHub enables you to deploy an API or a Mule application on a platform that’s managed by MuleSoft. CloudHub also provides high availability, clustering and failover of your APIs and Mule applications and performs load balancing for them. See [CloudHub](https://docs.mulesoft.com/cloudhub/) for more information. CloudHub can be managed only by version of the cloud control plane that exists in the same environment (US cloud, EU cloud, or MuleSoft Government Cloud). - Runtime Fabric Runtime Fabric is a container service that enables you to run Mule applications and API gateways within a data center or third-party cloud environment that you control and manage. You can install Runtime Fabric on a set of physical servers, virtual machines, or within Amazon Web Services and Microsoft Azure. Runtime Fabric comes bundled with technology such as Docker and Kubernetes, which offer benefits such as high availability, failover, clustering, and load balancing. See [Anypoint Runtime Fabric Overview](https://docs.mulesoft.com/runtime-fabric/latest/) for more information. Runtime Fabric can be managed only by Cloud control planes (US cloud, EU cloud). MuleSoft Government Cloud and Anypoint Platform PCE do not support Runtime Fabric. - Hybrid Standalone Runtimes Hybrid standalone runtimes enable you to host the Mule runtime engine in an environment you control. This model provides the control and security of deployments within customer trust boundary combined with the flexibility, scalability, and centralized management of cloud-based services. With hybrid standalone runtimes, the Mule runtime engine can run on a physical server, a virtual machine, or within a third-party cloud service like Amazon Web Services (AWS) or Microsoft Azure. - Standalone Runtimes Standalone runtimes are useful for isolated environments where connecting to the internet or Anypoint Control Plane isn’t feasible. These environments enable you to host Mule runtime engine on a single instance, such as a physical server, virtual machine, or within a third-party cloud service like AWS or Azure. This setup offers simplicity and control, but it requires that you manually manage infrastructure tasks like high availability, failover, clustering, and load balancing. No connection to Anypoint Control Plane is required, and you manage these Mule instances entirely within your own environment. You can manage standalone runtimes by using cloud control planes (US Cloud, EU Cloud, MuleSoft Government Cloud) or a customer-hosted control plane (Anypoint Platform PCE). In addition to using Runtime Manager, you can perform deployments and manage Mule apps with [Anypoint CLI 3.x](https://docs.mulesoft.com/anypoint-cli/latest/anypoint-platform-cli-commands), which includes commands for deployments and a number of Anypoint Platform use cases. ## See Also - [Mule Application Development](https://docs.mulesoft.com/mule-runtime/4.11/mule-app-dev) - [Domains](https://docs.mulesoft.com/studio/domain-support-concept) - [Policies](https://docs.mulesoft.com/gateway/latest/gateway-secure-apis) - [Mule Configuration XML](https://docs.mulesoft.com/mule-runtime/4.11/about-mule-configuration) - [Deployment Strategies](https://docs.mulesoft.com/runtime-manager/deployment-strategies) - [Download, Install, Upgrade Mule](https://docs.mulesoft.com/on-premises/latest/runtime-installation-task) --- product: Mule Runtime version: 4.12 keywords: mule, getting started, transform, message, payload --- # Mule Runtime Engine Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) is a lightweight integration engine that runs Mule applications and supports domains and policies. Mule applications, domains, and policies share an XML DSL (domain-specific language). ## Mule Applications Mule applications connect systems, services, APIs, and devices using API-led connectivity instead of point-to-point integrations. Mule applications provide functionality for message routing, data mapping, orchestration, reliability, security, and scalability. Anypoint Studio supports Mule application development. ## Mule Domains Domains enable you to share global configurations that Mule applications need to reuse, such as default error handlers, shared properties, scheduler pools, and component configurations. You can only deploy domains when running Mule runtime engine on premises. See [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.12/shared-resources) for information about developing and configuring Mule domains by using Anypoint Studio. See [Deploy a Domain](https://docs.mulesoft.com/mule-runtime/4.12/deploy-on-premises#deploy-a-domain) for domain deployment instructions. ## Policies Policies on HTTP-based APIs can enforce security, regulate traffic through Mule applications, and adapt APIs to your business needs. Mule includes an embedded API Gateway, which enables you to apply security policies to an API, enrich incoming or outgoing messages, and add capabilities to an API without having to write any code. See [API Gateway Capabilities](https://docs.mulesoft.com/mule-gateway/mule-gateway-capabilities-mule4) for additional information. API Manager supports the configuration of automated policies. Custom policy development and configuration are also supported. ## Maven Support Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality. For the Mule runtime engine, you can integrate the packaging, testing, and deployment of your Mule applications, domains, and custom policies with your Maven lifecycle using the Mule Maven plugin. For details, see [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.12/using-maven-with-mule). ## Mule Installation, Deployment, and Management For a Mule app to run, it must be deployed to an environment where the Mule runtime engine is installed. Mule is packaged within the [Studio](https://docs.mulesoft.com/studio/) IDE and with [Design Center](https://docs.mulesoft.com/design-center/) on Anypoint Platform so that you can run a Mule app as you design it. MuleSoft provides different options for hosting the Anypoint Platform runtime plane: - CloudHub 2.0 CloudHub 2.0 is a fully managed, containerized integration platform as a service (iPaaS) where you can deploy APIs and integrations as lightweight containers in the cloud. CloudHub 2.0 provides for deployments across 12 regions globally, either single or shared tenancy, and dynamically scales infrastructure and built-in services up or down to support elastic transaction volumes. See [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) for more information. - CloudHub 1.0 CloudHub is MuleSoft’s cloud-based environment for hosting the Mule runtime server and related services. CloudHub enables you to deploy an API or a Mule application on a platform that’s managed by MuleSoft. CloudHub also provides high availability, clustering and failover of your APIs and Mule applications and performs load balancing for them. See [CloudHub](https://docs.mulesoft.com/cloudhub/) for more information. CloudHub can be managed only by version of the cloud control plane that exists in the same environment (US cloud, EU cloud, or MuleSoft Government Cloud). - Runtime Fabric Runtime Fabric is a container service that enables you to run Mule applications and API gateways within a data center or third-party cloud environment that you control and manage. You can install Runtime Fabric on a set of physical servers, virtual machines, or within Amazon Web Services and Microsoft Azure. Runtime Fabric comes bundled with technology such as Docker and Kubernetes, which offer benefits such as high availability, failover, clustering, and load balancing. See [Anypoint Runtime Fabric Overview](https://docs.mulesoft.com/runtime-fabric/latest/) for more information. Runtime Fabric can be managed only by Cloud control planes (US cloud, EU cloud). MuleSoft Government Cloud and Anypoint Platform PCE do not support Runtime Fabric. - Hybrid Standalone Runtimes Hybrid standalone runtimes enable you to host the Mule runtime engine in an environment you control. This model provides the control and security of deployments within customer trust boundary combined with the flexibility, scalability, and centralized management of cloud-based services. With hybrid standalone runtimes, the Mule runtime engine can run on a physical server, a virtual machine, or within a third-party cloud service like Amazon Web Services (AWS) or Microsoft Azure. - Standalone Runtimes Standalone runtimes are useful for isolated environments where connecting to the internet or Anypoint Control Plane isn’t feasible. These environments enable you to host Mule runtime engine on a single instance, such as a physical server, virtual machine, or within a third-party cloud service like AWS or Azure. This setup offers simplicity and control, but it requires that you manually manage infrastructure tasks like high availability, failover, clustering, and load balancing. No connection to Anypoint Control Plane is required, and you manage these Mule instances entirely within your own environment. You can manage standalone runtimes by using cloud control planes (US Cloud, EU Cloud, MuleSoft Government Cloud) or a customer-hosted control plane (Anypoint Platform PCE). In addition to using Runtime Manager, you can perform deployments and manage Mule apps with [Anypoint CLI 3.x](https://docs.mulesoft.com/anypoint-cli/latest/anypoint-platform-cli-commands), which includes commands for deployments and a number of Anypoint Platform use cases. ## See Also - [Mule Application Development](https://docs.mulesoft.com/mule-runtime/4.12/mule-app-dev) - [Domains](https://docs.mulesoft.com/studio/domain-support-concept) - [Policies](https://docs.mulesoft.com/gateway/latest/gateway-secure-apis) - [Mule Configuration XML](https://docs.mulesoft.com/mule-runtime/4.12/about-mule-configuration) - [Deployment Strategies](https://docs.mulesoft.com/runtime-manager/deployment-strategies) - [Download, Install, Upgrade Mule](https://docs.mulesoft.com/on-premises/latest/runtime-installation-task) --- product: Mule Runtime version: 4.3 keywords: mule, getting started, transform, message, payload --- # Mule Runtime Engine Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) is a lightweight integration engine that runs Mule applications and supports domains and policies. Mule applications, domains, and policies share an XML DSL (domain-specific language). ## Mule Applications Mule applications connect systems, services, APIs, and devices using API-led connectivity instead of point-to-point integrations. Mule applications provide functionality for message routing, data mapping, orchestration, reliability, security, and scalability. Anypoint Studio supports Mule application development. ## Mule Domains Domains enable you to share global configurations that Mule applications need to reuse, such as default error handlers, shared properties, scheduler pools, and component configurations. You can only deploy domains when running Mule runtime engine on premises. See [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.3/shared-resources) for information about developing and configuring Mule domains by using Anypoint Studio. See [Deploy a Domain](https://docs.mulesoft.com/mule-runtime/4.3/deploy-on-premises#deploy-a-domain) for domain deployment instructions. ## Policies Policies on HTTP-based APIs can enforce security, regulate traffic through Mule applications, and adapt APIs to your business needs. Mule includes an embedded API Gateway, which enables you to apply security policies to an API, enrich incoming or outgoing messages, and add capabilities to an API without having to write any code. See [API Gateway Capabilities](https://docs.mulesoft.com/mule-gateway/mule-gateway-capabilities-mule4) for additional information. API Manager supports the configuration of automated policies. Custom policy development and configuration are also supported. ## Maven Support Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality. For the Mule runtime engine, you can integrate the packaging, testing, and deployment of your Mule applications, domains, and custom policies with your Maven lifecycle using the Mule Maven plugin. For details, see [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.3/using-maven-with-mule). ## Mule Installation, Deployment, and Management For a Mule app to run, it must be deployed to an environment where the Mule runtime engine is installed. Mule is packaged within the [Studio](https://docs.mulesoft.com/studio/) IDE and with [Design Center](https://docs.mulesoft.com/design-center/) on Anypoint Platform so that you can run a Mule app as you design it. For production and pre-production deployments of Mule apps, you can use [Runtime Manager](https://docs.mulesoft.com/runtime-manager/) to deploy Mule apps to runtimes within CloudHub and other supported platform as a service (PaaS) solutions. - [CloudHub](https://docs.mulesoft.com/cloudhub/) is a fully managed, cloud-based integration platform as a service (iPaaS) for Anypoint Platform that enables you to run your Mule apps without requiring you to provide Mule runtime engines or the infrastructure on which your apps run. You use Runtime Manager to deploy Mule apps to CloudHub, select the Mule version, set the number of vCores needed to run the app, and so on. - Hybrid deployment models manage Mule apps and runtimes from the Cloud while running them in a datacenter that is managed by your company: - For remote Mule runtimes (also called standalone or "naked" Mules), you start Mule runtimes from your datacenter, but you can deploy and manage Mule apps from the Cloud, through Runtime Manager. In this deployment model, you provide the infrastructure and Mule runtime (see [Run Mule Runtime Engine On-Premises](https://docs.mulesoft.com/on-premises/latest/)). - For a hybrid PaaS deployment, you set up and run the PaaS on your company’s datacenter and use Runtime Manager to manage Mule apps within the PaaS. In this case, you provision the infrastructure in which the apps run. To guarantee the high availability of Mule apps, you use Runtime Manager to handle Mule runtimes. MuleSoft also provides the built-in PaaS solution, [Runtime Fabric](https://docs.mulesoft.com/runtime-fabric/latest/), which runs Mule runtime engines in a "containerized" environment. In addition to using Runtime Manager, you can perform deployments and manage Mule apps with [Anypoint CLI 3.x](https://docs.mulesoft.com/anypoint-cli/latest/anypoint-platform-cli-commands), which includes commands for deployments and a number of Anypoint Platform use cases. ## See Also - [Mule Application Development](https://docs.mulesoft.com/mule-runtime/4.3/mule-app-dev) - [Domains](https://docs.mulesoft.com/studio/domain-support-concept) - [Policies](https://docs.mulesoft.com/gateway/latest/gateway-secure-apis) - [Mule Configuration XML](https://docs.mulesoft.com/mule-runtime/4.3/about-mule-configuration) - [Deployment Strategies](https://docs.mulesoft.com/runtime-manager/deployment-strategies) - [Download, Install, Upgrade Mule](https://docs.mulesoft.com/on-premises/latest/runtime-installation-task) --- product: Mule Runtime version: 4.4 keywords: mule, getting started, transform, message, payload --- # Mule Runtime Engine Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) is a lightweight integration engine that runs Mule applications and supports domains and policies. Mule applications, domains, and policies share an XML DSL (domain-specific language). ## Mule Applications Mule applications connect systems, services, APIs, and devices using API-led connectivity instead of point-to-point integrations. Mule applications provide functionality for message routing, data mapping, orchestration, reliability, security, and scalability. Anypoint Studio supports Mule application development. ## Mule Domains Domains enable you to share global configurations that Mule applications need to reuse, such as default error handlers, shared properties, scheduler pools, and component configurations. You can only deploy domains when running Mule runtime engine on premises. See [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.4/shared-resources) for information about developing and configuring Mule domains by using Anypoint Studio. See [Deploy a Domain](https://docs.mulesoft.com/mule-runtime/4.4/deploy-on-premises#deploy-a-domain) for domain deployment instructions. ## Policies Policies on HTTP-based APIs can enforce security, regulate traffic through Mule applications, and adapt APIs to your business needs. Mule includes an embedded API Gateway, which enables you to apply security policies to an API, enrich incoming or outgoing messages, and add capabilities to an API without having to write any code. See [API Gateway Capabilities](https://docs.mulesoft.com/mule-gateway/mule-gateway-capabilities-mule4) for additional information. API Manager supports the configuration of automated policies. Custom policy development and configuration are also supported. ## Maven Support Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality. For the Mule runtime engine, you can integrate the packaging, testing, and deployment of your Mule applications, domains, and custom policies with your Maven lifecycle using the Mule Maven plugin. For details, see [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.4/using-maven-with-mule). ## Mule Installation, Deployment, and Management For a Mule app to run, it must be deployed to an environment where the Mule runtime engine is installed. Mule is packaged within the [Studio](https://docs.mulesoft.com/studio/) IDE and with [Design Center](https://docs.mulesoft.com/design-center/) on Anypoint Platform so that you can run a Mule app as you design it. MuleSoft provides different options for hosting the Anypoint Platform runtime plane: - CloudHub 2.0 CloudHub 2.0 is a fully managed, containerized integration platform as a service (iPaaS) where you can deploy APIs and integrations as lightweight containers in the cloud. CloudHub 2.0 provides for deployments across 12 regions globally, either single or shared tenancy, and dynamically scales infrastructure and built-in services up or down to support elastic transaction volumes. See [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) for more information. - CloudHub 1.0 CloudHub is MuleSoft’s cloud-based environment for hosting the Mule runtime server and related services. CloudHub enables you to deploy an API or a Mule application on a platform that’s managed by MuleSoft. CloudHub also provides high availability, clustering and failover of your APIs and Mule applications and performs load balancing for them. See [CloudHub](https://docs.mulesoft.com/cloudhub/) for more information. CloudHub can be managed only by version of the cloud control plane that exists in the same environment (US cloud, EU cloud, or MuleSoft Government Cloud). - Runtime Fabric Runtime Fabric is a container service that enables you to run Mule applications and API gateways within a data center or third-party cloud environment that you control and manage. You can install Runtime Fabric on a set of physical servers, virtual machines, or within Amazon Web Services and Microsoft Azure. Runtime Fabric comes bundled with technology such as Docker and Kubernetes, which offer benefits such as high availability, failover, clustering, and load balancing. See [Anypoint Runtime Fabric Overview](https://docs.mulesoft.com/runtime-fabric/latest/) for more information. Runtime Fabric can be managed only by Cloud control planes (US cloud, EU cloud). MuleSoft Government Cloud and Anypoint Platform PCE do not support Runtime Fabric. - Hybrid Standalone Runtimes Hybrid standalone runtimes enable you to host the Mule runtime engine in an environment you control. This model provides the control and security of deployments within customer trust boundary combined with the flexibility, scalability, and centralized management of cloud-based services. With hybrid standalone runtimes, the Mule runtime engine can run on a physical server, a virtual machine, or within a third-party cloud service like Amazon Web Services (AWS) or Microsoft Azure. - Standalone Runtimes Standalone runtimes are useful for isolated environments where connecting to the internet or Anypoint Control Plane isn’t feasible. These environments enable you to host Mule runtime engine on a single instance, such as a physical server, virtual machine, or within a third-party cloud service like AWS or Azure. This setup offers simplicity and control, but it requires that you manually manage infrastructure tasks like high availability, failover, clustering, and load balancing. No connection to Anypoint Control Plane is required, and you manage these Mule instances entirely within your own environment. You can manage standalone runtimes by using cloud control planes (US Cloud, EU Cloud, MuleSoft Government Cloud) or a customer-hosted control plane (Anypoint Platform PCE). In addition to using Runtime Manager, you can perform deployments and manage Mule apps with [Anypoint CLI 3.x](https://docs.mulesoft.com/anypoint-cli/latest/anypoint-platform-cli-commands), which includes commands for deployments and a number of Anypoint Platform use cases. ## See Also - [Mule Application Development](https://docs.mulesoft.com/mule-runtime/4.4/mule-app-dev) - [Domains](https://docs.mulesoft.com/studio/domain-support-concept) - [Policies](https://docs.mulesoft.com/gateway/latest/gateway-secure-apis) - [Mule Configuration XML](https://docs.mulesoft.com/mule-runtime/4.4/about-mule-configuration) - [Deployment Strategies](https://docs.mulesoft.com/runtime-manager/deployment-strategies) - [Download, Install, Upgrade Mule](https://docs.mulesoft.com/on-premises/latest/runtime-installation-task) --- product: Mule Runtime version: 4.6 keywords: mule, getting started, transform, message, payload --- # Mule Runtime Engine Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) is a lightweight integration engine that runs Mule applications and supports domains and policies. Mule applications, domains, and policies share an XML DSL (domain-specific language). ## Mule Applications Mule applications connect systems, services, APIs, and devices using API-led connectivity instead of point-to-point integrations. Mule applications provide functionality for message routing, data mapping, orchestration, reliability, security, and scalability. Anypoint Studio supports Mule application development. ## Mule Domains Domains enable you to share global configurations that Mule applications need to reuse, such as default error handlers, shared properties, scheduler pools, and component configurations. You can only deploy domains when running Mule runtime engine on premises. See [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.6/shared-resources) for information about developing and configuring Mule domains by using Anypoint Studio. See [Deploy a Domain](https://docs.mulesoft.com/mule-runtime/4.6/deploy-on-premises#deploy-a-domain) for domain deployment instructions. ## Policies Policies on HTTP-based APIs can enforce security, regulate traffic through Mule applications, and adapt APIs to your business needs. Mule includes an embedded API Gateway, which enables you to apply security policies to an API, enrich incoming or outgoing messages, and add capabilities to an API without having to write any code. See [API Gateway Capabilities](https://docs.mulesoft.com/mule-gateway/mule-gateway-capabilities-mule4) for additional information. API Manager supports the configuration of automated policies. Custom policy development and configuration are also supported. ## Maven Support Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality. For the Mule runtime engine, you can integrate the packaging, testing, and deployment of your Mule applications, domains, and custom policies with your Maven lifecycle using the Mule Maven plugin. For details, see [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.6/using-maven-with-mule). ## Mule Installation, Deployment, and Management For a Mule app to run, it must be deployed to an environment where the Mule runtime engine is installed. Mule is packaged within the [Studio](https://docs.mulesoft.com/studio/) IDE and with [Design Center](https://docs.mulesoft.com/design-center/) on Anypoint Platform so that you can run a Mule app as you design it. MuleSoft provides different options for hosting the Anypoint Platform runtime plane: - CloudHub 2.0 CloudHub 2.0 is a fully managed, containerized integration platform as a service (iPaaS) where you can deploy APIs and integrations as lightweight containers in the cloud. CloudHub 2.0 provides for deployments across 12 regions globally, either single or shared tenancy, and dynamically scales infrastructure and built-in services up or down to support elastic transaction volumes. See [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) for more information. - CloudHub 1.0 CloudHub is MuleSoft’s cloud-based environment for hosting the Mule runtime server and related services. CloudHub enables you to deploy an API or a Mule application on a platform that’s managed by MuleSoft. CloudHub also provides high availability, clustering and failover of your APIs and Mule applications and performs load balancing for them. See [CloudHub](https://docs.mulesoft.com/cloudhub/) for more information. CloudHub can be managed only by version of the cloud control plane that exists in the same environment (US cloud, EU cloud, or MuleSoft Government Cloud). - Runtime Fabric Runtime Fabric is a container service that enables you to run Mule applications and API gateways within a data center or third-party cloud environment that you control and manage. You can install Runtime Fabric on a set of physical servers, virtual machines, or within Amazon Web Services and Microsoft Azure. Runtime Fabric comes bundled with technology such as Docker and Kubernetes, which offer benefits such as high availability, failover, clustering, and load balancing. See [Anypoint Runtime Fabric Overview](https://docs.mulesoft.com/runtime-fabric/latest/) for more information. Runtime Fabric can be managed only by Cloud control planes (US cloud, EU cloud). MuleSoft Government Cloud and Anypoint Platform PCE do not support Runtime Fabric. - Hybrid Standalone Runtimes Hybrid standalone runtimes enable you to host the Mule runtime engine in an environment you control. This model provides the control and security of deployments within customer trust boundary combined with the flexibility, scalability, and centralized management of cloud-based services. With hybrid standalone runtimes, the Mule runtime engine can run on a physical server, a virtual machine, or within a third-party cloud service like Amazon Web Services (AWS) or Microsoft Azure. - Standalone Runtimes Standalone runtimes are useful for isolated environments where connecting to the internet or Anypoint Control Plane isn’t feasible. These environments enable you to host Mule runtime engine on a single instance, such as a physical server, virtual machine, or within a third-party cloud service like AWS or Azure. This setup offers simplicity and control, but it requires that you manually manage infrastructure tasks like high availability, failover, clustering, and load balancing. No connection to Anypoint Control Plane is required, and you manage these Mule instances entirely within your own environment. You can manage standalone runtimes by using cloud control planes (US Cloud, EU Cloud, MuleSoft Government Cloud) or a customer-hosted control plane (Anypoint Platform PCE). In addition to using Runtime Manager, you can perform deployments and manage Mule apps with [Anypoint CLI 3.x](https://docs.mulesoft.com/anypoint-cli/latest/anypoint-platform-cli-commands), which includes commands for deployments and a number of Anypoint Platform use cases. ## See Also - [Mule Application Development](https://docs.mulesoft.com/mule-runtime/4.6/mule-app-dev) - [Domains](https://docs.mulesoft.com/studio/domain-support-concept) - [Policies](https://docs.mulesoft.com/gateway/latest/gateway-secure-apis) - [Mule Configuration XML](https://docs.mulesoft.com/mule-runtime/4.6/about-mule-configuration) - [Deployment Strategies](https://docs.mulesoft.com/runtime-manager/deployment-strategies) - [Download, Install, Upgrade Mule](https://docs.mulesoft.com/on-premises/latest/runtime-installation-task) --- product: Mule Runtime version: 4.9 keywords: mule, getting started, transform, message, payload --- # Mule Runtime Engine Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) is a lightweight integration engine that runs Mule applications and supports domains and policies. Mule applications, domains, and policies share an XML DSL (domain-specific language). ## Mule Applications Mule applications connect systems, services, APIs, and devices using API-led connectivity instead of point-to-point integrations. Mule applications provide functionality for message routing, data mapping, orchestration, reliability, security, and scalability. Anypoint Studio supports Mule application development. ## Mule Domains Domains enable you to share global configurations that Mule applications need to reuse, such as default error handlers, shared properties, scheduler pools, and component configurations. You can only deploy domains when running Mule runtime engine on premises. See [Shared Resources](https://docs.mulesoft.com/mule-runtime/4.9/shared-resources) for information about developing and configuring Mule domains by using Anypoint Studio. See [Deploy a Domain](https://docs.mulesoft.com/mule-runtime/4.9/deploy-on-premises#deploy-a-domain) for domain deployment instructions. ## Policies Policies on HTTP-based APIs can enforce security, regulate traffic through Mule applications, and adapt APIs to your business needs. Mule includes an embedded API Gateway, which enables you to apply security policies to an API, enrich incoming or outgoing messages, and add capabilities to an API without having to write any code. See [API Gateway Capabilities](https://docs.mulesoft.com/mule-gateway/mule-gateway-capabilities-mule4) for additional information. API Manager supports the configuration of automated policies. Custom policy development and configuration are also supported. ## Maven Support Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality. For the Mule runtime engine, you can integrate the packaging, testing, and deployment of your Mule applications, domains, and custom policies with your Maven lifecycle using the Mule Maven plugin. For details, see [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/4.9/using-maven-with-mule). ## Mule Installation, Deployment, and Management For a Mule app to run, it must be deployed to an environment where the Mule runtime engine is installed. Mule is packaged within the [Studio](https://docs.mulesoft.com/studio/) IDE and with [Design Center](https://docs.mulesoft.com/design-center/) on Anypoint Platform so that you can run a Mule app as you design it. MuleSoft provides different options for hosting the Anypoint Platform runtime plane: - CloudHub 2.0 CloudHub 2.0 is a fully managed, containerized integration platform as a service (iPaaS) where you can deploy APIs and integrations as lightweight containers in the cloud. CloudHub 2.0 provides for deployments across 12 regions globally, either single or shared tenancy, and dynamically scales infrastructure and built-in services up or down to support elastic transaction volumes. See [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) for more information. - CloudHub 1.0 CloudHub is MuleSoft’s cloud-based environment for hosting the Mule runtime server and related services. CloudHub enables you to deploy an API or a Mule application on a platform that’s managed by MuleSoft. CloudHub also provides high availability, clustering and failover of your APIs and Mule applications and performs load balancing for them. See [CloudHub](https://docs.mulesoft.com/cloudhub/) for more information. CloudHub can be managed only by version of the cloud control plane that exists in the same environment (US cloud, EU cloud, or MuleSoft Government Cloud). - Runtime Fabric Runtime Fabric is a container service that enables you to run Mule applications and API gateways within a data center or third-party cloud environment that you control and manage. You can install Runtime Fabric on a set of physical servers, virtual machines, or within Amazon Web Services and Microsoft Azure. Runtime Fabric comes bundled with technology such as Docker and Kubernetes, which offer benefits such as high availability, failover, clustering, and load balancing. See [Anypoint Runtime Fabric Overview](https://docs.mulesoft.com/runtime-fabric/latest/) for more information. Runtime Fabric can be managed only by Cloud control planes (US cloud, EU cloud). MuleSoft Government Cloud and Anypoint Platform PCE do not support Runtime Fabric. - Hybrid Standalone Runtimes Hybrid standalone runtimes enable you to host the Mule runtime engine in an environment you control. This model provides the control and security of deployments within customer trust boundary combined with the flexibility, scalability, and centralized management of cloud-based services. With hybrid standalone runtimes, the Mule runtime engine can run on a physical server, a virtual machine, or within a third-party cloud service like Amazon Web Services (AWS) or Microsoft Azure. - Standalone Runtimes Standalone runtimes are useful for isolated environments where connecting to the internet or Anypoint Control Plane isn’t feasible. These environments enable you to host Mule runtime engine on a single instance, such as a physical server, virtual machine, or within a third-party cloud service like AWS or Azure. This setup offers simplicity and control, but it requires that you manually manage infrastructure tasks like high availability, failover, clustering, and load balancing. No connection to Anypoint Control Plane is required, and you manage these Mule instances entirely within your own environment. You can manage standalone runtimes by using cloud control planes (US Cloud, EU Cloud, MuleSoft Government Cloud) or a customer-hosted control plane (Anypoint Platform PCE). In addition to using Runtime Manager, you can perform deployments and manage Mule apps with [Anypoint CLI 3.x](https://docs.mulesoft.com/anypoint-cli/latest/anypoint-platform-cli-commands), which includes commands for deployments and a number of Anypoint Platform use cases. ## See Also - [Mule Application Development](https://docs.mulesoft.com/mule-runtime/4.9/mule-app-dev) - [Domains](https://docs.mulesoft.com/studio/domain-support-concept) - [Policies](https://docs.mulesoft.com/gateway/latest/gateway-secure-apis) - [Mule Configuration XML](https://docs.mulesoft.com/mule-runtime/4.9/about-mule-configuration) - [Deployment Strategies](https://docs.mulesoft.com/runtime-manager/deployment-strategies) - [Download, Install, Upgrade Mule](https://docs.mulesoft.com/on-premises/latest/runtime-installation-task) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: mule, getting started, transform, message, payload --- # Mule Runtime Engine Overview > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule runtime engine (Mule) is a lightweight integration engine that runs Mule applications and supports domains and policies. Mule applications, domains, and policies share an XML DSL (domain-specific language). ## Mule Applications Mule applications connect systems, services, APIs, and devices using API-led connectivity instead of point-to-point integrations. Mule applications provide functionality for message routing, data mapping, orchestration, reliability, security, and scalability. Anypoint Studio supports Mule application development. ## Mule Domains Domains enable you to share global configurations that Mule applications need to reuse, such as default error handlers, shared properties, scheduler pools, and component configurations. You can only deploy domains when running Mule runtime engine on premises. See [Shared Resources](https://docs.mulesoft.com/mule-runtime/latest/shared-resources) for information about developing and configuring Mule domains by using Anypoint Studio. See [Deploy a Domain](https://docs.mulesoft.com/mule-runtime/latest/deploy-on-premises#deploy-a-domain) for domain deployment instructions. ## Policies Policies on HTTP-based APIs can enforce security, regulate traffic through Mule applications, and adapt APIs to your business needs. Mule includes an embedded API Gateway, which enables you to apply security policies to an API, enrich incoming or outgoing messages, and add capabilities to an API without having to write any code. See [API Gateway Capabilities](https://docs.mulesoft.com/mule-gateway/mule-gateway-capabilities-mule4) for additional information. API Manager supports the configuration of automated policies. Custom policy development and configuration are also supported. ## Maven Support Maven is a project management utility that Mule implements to enhance project development. Mule provides built-in Maven functionality. For the Mule runtime engine, you can integrate the packaging, testing, and deployment of your Mule applications, domains, and custom policies with your Maven lifecycle using the Mule Maven plugin. For details, see [Maven Support in Mule](https://docs.mulesoft.com/mule-runtime/latest/using-maven-with-mule). ## Mule Installation, Deployment, and Management For a Mule app to run, it must be deployed to an environment where the Mule runtime engine is installed. Mule is packaged within the [Studio](https://docs.mulesoft.com/studio/) IDE and with [Design Center](https://docs.mulesoft.com/design-center/) on Anypoint Platform so that you can run a Mule app as you design it. MuleSoft provides different options for hosting the Anypoint Platform runtime plane: - CloudHub 2.0 CloudHub 2.0 is a fully managed, containerized integration platform as a service (iPaaS) where you can deploy APIs and integrations as lightweight containers in the cloud. CloudHub 2.0 provides for deployments across 12 regions globally, either single or shared tenancy, and dynamically scales infrastructure and built-in services up or down to support elastic transaction volumes. See [CloudHub 2.0](https://docs.mulesoft.com/cloudhub-2/) for more information. - CloudHub 1.0 CloudHub is MuleSoft’s cloud-based environment for hosting the Mule runtime server and related services. CloudHub enables you to deploy an API or a Mule application on a platform that’s managed by MuleSoft. CloudHub also provides high availability, clustering and failover of your APIs and Mule applications and performs load balancing for them. See [CloudHub](https://docs.mulesoft.com/cloudhub/) for more information. CloudHub can be managed only by version of the cloud control plane that exists in the same environment (US cloud, EU cloud, or MuleSoft Government Cloud). - Runtime Fabric Runtime Fabric is a container service that enables you to run Mule applications and API gateways within a data center or third-party cloud environment that you control and manage. You can install Runtime Fabric on a set of physical servers, virtual machines, or within Amazon Web Services and Microsoft Azure. Runtime Fabric comes bundled with technology such as Docker and Kubernetes, which offer benefits such as high availability, failover, clustering, and load balancing. See [Anypoint Runtime Fabric Overview](https://docs.mulesoft.com/runtime-fabric/latest/) for more information. Runtime Fabric can be managed only by Cloud control planes (US cloud, EU cloud). MuleSoft Government Cloud and Anypoint Platform PCE do not support Runtime Fabric. - Hybrid Standalone Runtimes Hybrid standalone runtimes enable you to host the Mule runtime engine in an environment you control. This model provides the control and security of deployments within customer trust boundary combined with the flexibility, scalability, and centralized management of cloud-based services. With hybrid standalone runtimes, the Mule runtime engine can run on a physical server, a virtual machine, or within a third-party cloud service like Amazon Web Services (AWS) or Microsoft Azure. - Standalone Runtimes Standalone runtimes are useful for isolated environments where connecting to the internet or Anypoint Control Plane isn’t feasible. These environments enable you to host Mule runtime engine on a single instance, such as a physical server, virtual machine, or within a third-party cloud service like AWS or Azure. This setup offers simplicity and control, but it requires that you manually manage infrastructure tasks like high availability, failover, clustering, and load balancing. No connection to Anypoint Control Plane is required, and you manage these Mule instances entirely within your own environment. You can manage standalone runtimes by using cloud control planes (US Cloud, EU Cloud, MuleSoft Government Cloud) or a customer-hosted control plane (Anypoint Platform PCE). In addition to using Runtime Manager, you can perform deployments and manage Mule apps with [Anypoint CLI 3.x](https://docs.mulesoft.com/anypoint-cli/latest/anypoint-platform-cli-commands), which includes commands for deployments and a number of Anypoint Platform use cases. ## See Also - [Mule Application Development](https://docs.mulesoft.com/mule-runtime/latest/mule-app-dev) - [Domains](https://docs.mulesoft.com/studio/domain-support-concept) - [Policies](https://docs.mulesoft.com/gateway/latest/gateway-secure-apis) - [Mule Configuration XML](https://docs.mulesoft.com/mule-runtime/latest/about-mule-configuration) - [Deployment Strategies](https://docs.mulesoft.com/runtime-manager/deployment-strategies) - [Download, Install, Upgrade Mule](https://docs.mulesoft.com/on-premises/latest/runtime-installation-task) --- product: Mule Runtime version: 4.11 keywords: release notes, mule, 4.13, 4.12, 4.11, 4.9, 4.6, 4.4, 4.3 --- # Mule Runtime Release Notes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule follows semantic versioning to denote major, minor, and patch releases. MuleSoft releases enhance the quality, capabilities, and security of Mule runtime engine (Mule). To take advantage of these improvements, it’s important to adopt a strategy for upgrading your Mule version and to regularly update patches of your Mule deployments with the latest bug fixes and security enhancements. To upgrade to a new Mule version, see [Mule Upgrades and Patch Updates](#mule-upgrades). ## Mule 4 Release Notes - [Mule Runtime 4.13.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.13.0-release-notes) - [Mule Runtime 4.12.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.12.0-release-notes) - [Mule Runtime 4.11.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.11.0-release-notes) - [Mule Runtime 4.9.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.9.0-release-notes) - [Mule Runtime 4.6.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.6.0-release-notes) - [Mule Runtime 4.4.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.4.0-release-notes) (This version of the product has reached [End of Life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf).) - [Mule Runtime 4.3.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.3.0-release-notes) (This version of the product has reached [End of Life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf).) ## Mule Upgrades and Patch Updates For Mule 4 upgrades and patch updates: - [Java Adoption](https://docs.mulesoft.com/release-notes/mule-runtime/java-adoption) - [Edge and LTS Releases for Mule](https://docs.mulesoft.com/release-notes/mule-runtime/lts-edge-release-cadence) (for Mule versions 4.6 and later) - [Mule Upgrade Tool](https://docs.mulesoft.com/mule-runtime/latest/mule-upgrade-tool) (for upgrading standalone Mule 4 instances, including minor versions and patch updates) - [Mule Upgrades and Patch Updates](https://docs.mulesoft.com/release-notes/mule-runtime/upgrade-update-mule) (overview) - [Update Patches to Mule](https://docs.mulesoft.com/release-notes/mule-runtime/patching-mule-versions) - [Upgrading Mule Runtime Engine (Versions 4.x to 4.n)](https://docs.mulesoft.com/release-notes/mule-runtime/updating-mule-4-versions) ## Mule Troubleshooting Plugin - [Mule Troubleshooting Plugin](https://docs.mulesoft.com/mule-runtime/latest/mule-troubleshooting-plugin) ## Mule Services - [HTTP Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-http-release-notes) - [OAuth Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-oauth-release-notes) - [Scheduler Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-scheduler-release-notes) - [Mule SOAP Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-soap-release-notes) ## Anypoint Enterprise Security - [Anypoint Security Release Notes](https://docs.mulesoft.com/release-notes/anypoint-security/anypoint-security-rn-landing-page) ## See Also - [Known Issues](https://help.salesforce.com/s/issues) --- product: Mule Runtime version: 4.12 keywords: release notes, mule, 4.13, 4.12, 4.11, 4.9, 4.6, 4.4, 4.3 --- # Mule Runtime Release Notes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule follows semantic versioning to denote major, minor, and patch releases. MuleSoft releases enhance the quality, capabilities, and security of Mule runtime engine (Mule). To take advantage of these improvements, it’s important to adopt a strategy for upgrading your Mule version and to regularly update patches of your Mule deployments with the latest bug fixes and security enhancements. To upgrade to a new Mule version, see [Mule Upgrades and Patch Updates](#mule-upgrades). ## Mule 4 Release Notes - [Mule Runtime 4.13.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.13.0-release-notes) - [Mule Runtime 4.12.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.12.0-release-notes) - [Mule Runtime 4.11.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.11.0-release-notes) - [Mule Runtime 4.9.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.9.0-release-notes) - [Mule Runtime 4.6.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.6.0-release-notes) - [Mule Runtime 4.4.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.4.0-release-notes) (This version of the product has reached [End of Life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf).) - [Mule Runtime 4.3.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.3.0-release-notes) (This version of the product has reached [End of Life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf).) ## Mule Upgrades and Patch Updates For Mule 4 upgrades and patch updates: - [Java Adoption](https://docs.mulesoft.com/release-notes/mule-runtime/java-adoption) - [Edge and LTS Releases for Mule](https://docs.mulesoft.com/release-notes/mule-runtime/lts-edge-release-cadence) (for Mule versions 4.6 and later) - [Mule Upgrade Tool](https://docs.mulesoft.com/mule-runtime/latest/mule-upgrade-tool) (for upgrading standalone Mule 4 instances, including minor versions and patch updates) - [Mule Upgrades and Patch Updates](https://docs.mulesoft.com/release-notes/mule-runtime/upgrade-update-mule) (overview) - [Update Patches to Mule](https://docs.mulesoft.com/release-notes/mule-runtime/patching-mule-versions) - [Upgrading Mule Runtime Engine (Versions 4.x to 4.n)](https://docs.mulesoft.com/release-notes/mule-runtime/updating-mule-4-versions) ## Mule Troubleshooting Plugin - [Mule Troubleshooting Plugin](https://docs.mulesoft.com/mule-runtime/latest/mule-troubleshooting-plugin) ## Mule Services - [HTTP Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-http-release-notes) - [OAuth Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-oauth-release-notes) - [Scheduler Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-scheduler-release-notes) - [Mule SOAP Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-soap-release-notes) ## Anypoint Enterprise Security - [Anypoint Security Release Notes](https://docs.mulesoft.com/release-notes/anypoint-security/anypoint-security-rn-landing-page) ## See Also - [Known Issues](https://help.salesforce.com/s/issues) --- product: Mule Runtime version: 4.6 keywords: release notes, mule, 4.13, 4.12, 4.11, 4.9, 4.6, 4.4, 4.3 --- # Mule Runtime Release Notes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule follows semantic versioning to denote major, minor, and patch releases. MuleSoft releases enhance the quality, capabilities, and security of Mule runtime engine (Mule). To take advantage of these improvements, it’s important to adopt a strategy for upgrading your Mule version and to regularly update patches of your Mule deployments with the latest bug fixes and security enhancements. To upgrade to a new Mule version, see [Mule Upgrades and Patch Updates](#mule-upgrades). ## Mule 4 Release Notes - [Mule Runtime 4.13.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.13.0-release-notes) - [Mule Runtime 4.12.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.12.0-release-notes) - [Mule Runtime 4.11.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.11.0-release-notes) - [Mule Runtime 4.9.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.9.0-release-notes) - [Mule Runtime 4.6.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.6.0-release-notes) - [Mule Runtime 4.4.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.4.0-release-notes) (This version of the product has reached [End of Life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf).) - [Mule Runtime 4.3.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.3.0-release-notes) (This version of the product has reached [End of Life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf).) ## Mule Upgrades and Patch Updates For Mule 4 upgrades and patch updates: - [Java Adoption](https://docs.mulesoft.com/release-notes/mule-runtime/java-adoption) - [Edge and LTS Releases for Mule](https://docs.mulesoft.com/release-notes/mule-runtime/lts-edge-release-cadence) (for Mule versions 4.6 and later) - [Mule Upgrade Tool](https://docs.mulesoft.com/mule-runtime/latest/mule-upgrade-tool) (for upgrading standalone Mule 4 instances, including minor versions and patch updates) - [Mule Upgrades and Patch Updates](https://docs.mulesoft.com/release-notes/mule-runtime/upgrade-update-mule) (overview) - [Update Patches to Mule](https://docs.mulesoft.com/release-notes/mule-runtime/patching-mule-versions) - [Upgrading Mule Runtime Engine (Versions 4.x to 4.n)](https://docs.mulesoft.com/release-notes/mule-runtime/updating-mule-4-versions) ## Mule Troubleshooting Plugin - [Mule Troubleshooting Plugin](https://docs.mulesoft.com/mule-runtime/latest/mule-troubleshooting-plugin) ## Mule Services - [HTTP Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-http-release-notes) - [OAuth Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-oauth-release-notes) - [Scheduler Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-scheduler-release-notes) - [Mule SOAP Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-soap-release-notes) ## Anypoint Enterprise Security - [Anypoint Security Release Notes](https://docs.mulesoft.com/release-notes/anypoint-security/anypoint-security-rn-landing-page) ## See Also - [Known Issues](https://help.salesforce.com/s/issues) --- product: Mule Runtime version: 4.9 keywords: release notes, mule, 4.13, 4.12, 4.11, 4.9, 4.6, 4.4, 4.3 --- # Mule Runtime Release Notes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule follows semantic versioning to denote major, minor, and patch releases. MuleSoft releases enhance the quality, capabilities, and security of Mule runtime engine (Mule). To take advantage of these improvements, it’s important to adopt a strategy for upgrading your Mule version and to regularly update patches of your Mule deployments with the latest bug fixes and security enhancements. To upgrade to a new Mule version, see [Mule Upgrades and Patch Updates](#mule-upgrades). ## Mule 4 Release Notes - [Mule Runtime 4.13.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.13.0-release-notes) - [Mule Runtime 4.12.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.12.0-release-notes) - [Mule Runtime 4.11.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.11.0-release-notes) - [Mule Runtime 4.9.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.9.0-release-notes) - [Mule Runtime 4.6.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.6.0-release-notes) - [Mule Runtime 4.4.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.4.0-release-notes) (This version of the product has reached [End of Life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf).) - [Mule Runtime 4.3.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.3.0-release-notes) (This version of the product has reached [End of Life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf).) ## Mule Upgrades and Patch Updates For Mule 4 upgrades and patch updates: - [Java Adoption](https://docs.mulesoft.com/release-notes/mule-runtime/java-adoption) - [Edge and LTS Releases for Mule](https://docs.mulesoft.com/release-notes/mule-runtime/lts-edge-release-cadence) (for Mule versions 4.6 and later) - [Mule Upgrade Tool](https://docs.mulesoft.com/mule-runtime/latest/mule-upgrade-tool) (for upgrading standalone Mule 4 instances, including minor versions and patch updates) - [Mule Upgrades and Patch Updates](https://docs.mulesoft.com/release-notes/mule-runtime/upgrade-update-mule) (overview) - [Update Patches to Mule](https://docs.mulesoft.com/release-notes/mule-runtime/patching-mule-versions) - [Upgrading Mule Runtime Engine (Versions 4.x to 4.n)](https://docs.mulesoft.com/release-notes/mule-runtime/updating-mule-4-versions) ## Mule Troubleshooting Plugin - [Mule Troubleshooting Plugin](https://docs.mulesoft.com/mule-runtime/latest/mule-troubleshooting-plugin) ## Mule Services - [HTTP Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-http-release-notes) - [OAuth Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-oauth-release-notes) - [Scheduler Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-scheduler-release-notes) - [Mule SOAP Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-soap-release-notes) ## Anypoint Enterprise Security - [Anypoint Security Release Notes](https://docs.mulesoft.com/release-notes/anypoint-security/anypoint-security-rn-landing-page) ## See Also - [Known Issues](https://help.salesforce.com/s/issues) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: release notes, mule, 4.13, 4.12, 4.11, 4.9, 4.6, 4.4, 4.3 --- # Mule Runtime Release Notes > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule follows semantic versioning to denote major, minor, and patch releases. MuleSoft releases enhance the quality, capabilities, and security of Mule runtime engine (Mule). To take advantage of these improvements, it’s important to adopt a strategy for upgrading your Mule version and to regularly update patches of your Mule deployments with the latest bug fixes and security enhancements. To upgrade to a new Mule version, see [Mule Upgrades and Patch Updates](#mule-upgrades). ## Mule 4 Release Notes - [Mule Runtime 4.13.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.13.0-release-notes) - [Mule Runtime 4.12.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.12.0-release-notes) - [Mule Runtime 4.11.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.11.0-release-notes) - [Mule Runtime 4.9.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.9.0-release-notes) - [Mule Runtime 4.6.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.6.0-release-notes) - [Mule Runtime 4.4.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.4.0-release-notes) (This version of the product has reached [End of Life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf).) - [Mule Runtime 4.3.0 Release Notes](https://docs.mulesoft.com/release-notes/mule-runtime/mule-4.3.0-release-notes) (This version of the product has reached [End of Life](https://www.salesforce.com/en-us/wp-content/uploads/sites/4/documents/legal/Agreements/versioning-back-support-policy.pdf).) ## Mule Upgrades and Patch Updates For Mule 4 upgrades and patch updates: - [Java Adoption](https://docs.mulesoft.com/release-notes/mule-runtime/java-adoption) - [Edge and LTS Releases for Mule](https://docs.mulesoft.com/release-notes/mule-runtime/lts-edge-release-cadence) (for Mule versions 4.6 and later) - [Mule Upgrade Tool](https://docs.mulesoft.com/mule-runtime/latest/mule-upgrade-tool) (for upgrading standalone Mule 4 instances, including minor versions and patch updates) - [Mule Upgrades and Patch Updates](https://docs.mulesoft.com/release-notes/mule-runtime/upgrade-update-mule) (overview) - [Update Patches to Mule](https://docs.mulesoft.com/release-notes/mule-runtime/patching-mule-versions) - [Upgrading Mule Runtime Engine (Versions 4.x to 4.n)](https://docs.mulesoft.com/release-notes/mule-runtime/updating-mule-4-versions) ## Mule Troubleshooting Plugin - [Mule Troubleshooting Plugin](https://docs.mulesoft.com/mule-runtime/latest/mule-troubleshooting-plugin) ## Mule Services - [HTTP Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-http-release-notes) - [OAuth Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-oauth-release-notes) - [Scheduler Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-scheduler-release-notes) - [Mule SOAP Service Release Notes - Mule 4](https://docs.mulesoft.com/release-notes/mule-runtime/service-soap-release-notes) ## Anypoint Enterprise Security - [Anypoint Security Release Notes](https://docs.mulesoft.com/release-notes/anypoint-security/anypoint-security-rn-landing-page) ## See Also - [Known Issues](https://help.salesforce.com/s/issues) --- product: Mule Runtime version: 4.11 keywords: security, oauth, authentication, oauth provider, token, private key, secret key, access key --- # Mule Secure Token Service OAuth 2.0 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule runtime engine supports the OAuth 2.0 protocol. The way to configure OAuth 2.0 authorization differs, depending on the OAuth role and your objective: - Configure authentication in your client Mule app when sending requests to a service that requires authentication, such as the Github OAuth2 server. Use the [OAuth Module](https://docs.mulesoft.com/oauth-module/latest/oauth-module-reference) for the OAuth2 configuration. - Use the [Mule OAuth2 Provider Connector](https://docs.mulesoft.com/oauth2-provider-module/latest/oauth2-provider-module-reference) to create a Mule application that grants and validates the tokens needed to access a protected resource. To protect your API or app from receiving unauthorized requests, use an API Manager policy, such as the `OAuth 2.0 Access Token Enforcement Using External Provider` policy. To expose a web service protected by OAuth 2.0 security, see the [API Manager documentation](https://docs.mulesoft.com/api-manager/latest/mule-oauth-provider-landing-page). ## See Also - [OAuth Authorization Grant Types](https://docs.mulesoft.com/mule-runtime/4.11/authorization-grant-types) --- product: Mule Runtime version: 4.12 keywords: security, oauth, authentication, oauth provider, token, private key, secret key, access key --- # Mule Secure Token Service OAuth 2.0 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule runtime engine supports the OAuth 2.0 protocol. The way to configure OAuth 2.0 authorization differs, depending on the OAuth role and your objective: - Configure authentication in your client Mule app when sending requests to a service that requires authentication, such as the Github OAuth2 server. Use the [OAuth Module](https://docs.mulesoft.com/oauth-module/latest/oauth-module-reference) for the OAuth2 configuration. - Use the [Mule OAuth2 Provider Connector](https://docs.mulesoft.com/oauth2-provider-module/latest/oauth2-provider-module-reference) to create a Mule application that grants and validates the tokens needed to access a protected resource. To protect your API or app from receiving unauthorized requests, use an API Manager policy, such as the `OAuth 2.0 Access Token Enforcement Using External Provider` policy. To expose a web service protected by OAuth 2.0 security, see the [API Manager documentation](https://docs.mulesoft.com/api-manager/latest/mule-oauth-provider-landing-page). ## See Also - [OAuth Authorization Grant Types](https://docs.mulesoft.com/mule-runtime/4.12/authorization-grant-types) --- product: Mule Runtime version: 4.3 keywords: security, oauth, authentication, oauth provider, token, private key, secret key, access key --- # Mule Secure Token Service OAuth 2.0 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule runtime engine supports the OAuth 2.0 protocol. The way to configure OAuth 2.0 authorization differs, depending on the OAuth role and your objective: - Configure authentication in your client Mule app when sending requests to a service that requires authentication, such as the Github OAuth2 server. Use the [OAuth Module](https://docs.mulesoft.com/oauth-module/latest/oauth-module-reference) for the OAuth2 configuration. - Use the [Mule OAuth2 Provider Connector](https://docs.mulesoft.com/oauth2-provider-module/latest/oauth2-provider-module-reference) to create a Mule application that grants and validates the tokens needed to access a protected resource. To protect your API or app from receiving unauthorized requests, use an API Manager policy, such as the `OAuth 2.0 Access Token Enforcement Using External Provider` policy. To expose a web service protected by OAuth 2.0 security, see the [API Manager documentation](https://docs.mulesoft.com/api-manager/latest/mule-oauth-provider-landing-page). ## See Also - [OAuth Authorization Grant Types](https://docs.mulesoft.com/mule-runtime/4.3/authorization-grant-types) --- product: Mule Runtime version: 4.4 keywords: security, oauth, authentication, oauth provider, token, private key, secret key, access key --- # Mule Secure Token Service OAuth 2.0 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule runtime engine supports the OAuth 2.0 protocol. The way to configure OAuth 2.0 authorization differs, depending on the OAuth role and your objective: - Configure authentication in your client Mule app when sending requests to a service that requires authentication, such as the Github OAuth2 server. Use the [OAuth Module](https://docs.mulesoft.com/oauth-module/latest/oauth-module-reference) for the OAuth2 configuration. - Use the [Mule OAuth2 Provider Connector](https://docs.mulesoft.com/oauth2-provider-module/latest/oauth2-provider-module-reference) to create a Mule application that grants and validates the tokens needed to access a protected resource. To protect your API or app from receiving unauthorized requests, use an API Manager policy, such as the `OAuth 2.0 Access Token Enforcement Using External Provider` policy. To expose a web service protected by OAuth 2.0 security, see the [API Manager documentation](https://docs.mulesoft.com/api-manager/latest/mule-oauth-provider-landing-page). ## See Also - [OAuth Authorization Grant Types](https://docs.mulesoft.com/mule-runtime/4.4/authorization-grant-types) --- product: Mule Runtime version: 4.6 keywords: security, oauth, authentication, oauth provider, token, private key, secret key, access key --- # Mule Secure Token Service OAuth 2.0 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule runtime engine supports the OAuth 2.0 protocol. The way to configure OAuth 2.0 authorization differs, depending on the OAuth role and your objective: - Configure authentication in your client Mule app when sending requests to a service that requires authentication, such as the Github OAuth2 server. Use the [OAuth Module](https://docs.mulesoft.com/oauth-module/latest/oauth-module-reference) for the OAuth2 configuration. - Use the [Mule OAuth2 Provider Connector](https://docs.mulesoft.com/oauth2-provider-module/latest/oauth2-provider-module-reference) to create a Mule application that grants and validates the tokens needed to access a protected resource. To protect your API or app from receiving unauthorized requests, use an API Manager policy, such as the `OAuth 2.0 Access Token Enforcement Using External Provider` policy. To expose a web service protected by OAuth 2.0 security, see the [API Manager documentation](https://docs.mulesoft.com/api-manager/latest/mule-oauth-provider-landing-page). ## See Also - [OAuth Authorization Grant Types](https://docs.mulesoft.com/mule-runtime/4.6/authorization-grant-types) --- product: Mule Runtime version: 4.9 keywords: security, oauth, authentication, oauth provider, token, private key, secret key, access key --- # Mule Secure Token Service OAuth 2.0 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule runtime engine supports the OAuth 2.0 protocol. The way to configure OAuth 2.0 authorization differs, depending on the OAuth role and your objective: - Configure authentication in your client Mule app when sending requests to a service that requires authentication, such as the Github OAuth2 server. Use the [OAuth Module](https://docs.mulesoft.com/oauth-module/latest/oauth-module-reference) for the OAuth2 configuration. - Use the [Mule OAuth2 Provider Connector](https://docs.mulesoft.com/oauth2-provider-module/latest/oauth2-provider-module-reference) to create a Mule application that grants and validates the tokens needed to access a protected resource. To protect your API or app from receiving unauthorized requests, use an API Manager policy, such as the `OAuth 2.0 Access Token Enforcement Using External Provider` policy. To expose a web service protected by OAuth 2.0 security, see the [API Manager documentation](https://docs.mulesoft.com/api-manager/latest/mule-oauth-provider-landing-page). ## See Also - [OAuth Authorization Grant Types](https://docs.mulesoft.com/mule-runtime/4.9/authorization-grant-types) --- product: Mule Runtime version: 4.13 is-latest-version: true keywords: security, oauth, authentication, oauth provider, token, private key, secret key, access key --- # Mule Secure Token Service OAuth 2.0 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt The Mule runtime engine supports the OAuth 2.0 protocol. The way to configure OAuth 2.0 authorization differs, depending on the OAuth role and your objective: - Configure authentication in your client Mule app when sending requests to a service that requires authentication, such as the Github OAuth2 server. Use the [OAuth Module](https://docs.mulesoft.com/oauth-module/latest/oauth-module-reference) for the OAuth2 configuration. - Use the [Mule OAuth2 Provider Connector](https://docs.mulesoft.com/oauth2-provider-module/latest/oauth2-provider-module-reference) to create a Mule application that grants and validates the tokens needed to access a protected resource. To protect your API or app from receiving unauthorized requests, use an API Manager policy, such as the `OAuth 2.0 Access Token Enforcement Using External Provider` policy. To expose a web service protected by OAuth 2.0 security, see the [API Manager documentation](https://docs.mulesoft.com/api-manager/latest/mule-oauth-provider-landing-page). ## See Also - [OAuth Authorization Grant Types](https://docs.mulesoft.com/mule-runtime/latest/authorization-grant-types) --- product: Mule Runtime version: 4.11 --- # Mule Server Notifications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule provides an internal notification mechanism that you can use to access changes that occur on the Mule Server, such as adding a flow component, a request for authorization failing, or Mule starting. You can set up your agents or flow components to react to these notifications. ## Configuring Notifications Message notifications provide a snapshot of all information sent into and out of the Mule Server. Mule fire these notifications whenever it receives or sends a message. These additional notifications have some impact on performance, so they are disabled by default. To enable message notifications, you set the type of messages you want to enable using the `` element in your Mule configuration file. You also register the notification listeners and associate interfaces with specific notifications. For example, first you create beans for the notification listeners in your spring configuration file, specifying the class of the type of notification you want to receive: ```xml ``` And then, add the reference for your spring configuration: ```xml ``` Next, you specify the notifications you want to receive using the `` element, and then register the listeners using the `` element: ```xml ``` When you specify the MESSAGE-PROCESSOR notification, a notification is sent before and after a message processor is invoked. Because the listeners implement the interface for the type of notification they want to receive, the listeners receive the correct notifications. For example, the `ProcessorNotificationLogger` class would implement `org.mule.runtime.api.notification.MessageProcessorNotificationListener`: ```java public class ProcessorNotificationLogger implements MessageProcessorNotificationListener { @Override public void onNotification(MessageProcessorNotification notification) { // write here the logic to process the notification event } } ``` > [!IMPORTANT] Don’t forget to add the mule-api dependency in your pom file with `provided` as > scope, so the api classes will be available in your classpath. The dependency will then be > provided by mule in runtime. For a list of notification types, see [Notifications Configuration Reference](https://docs.mulesoft.com/mule-runtime/4.11/notifications-configuration-reference). For a list of notification listener interfaces, see [Notification Interfaces](#notification-interfaces) below. ### Specifying a Different Interface If you want to change the interface associated with a notification, you specify the new interface with the `interface-class` attribute: ```xml ``` ### Configuring a Custom Notification If you create a custom notification, you also specify the `event-class` attribute: ```xml ``` ### Disabling Notifications If you want to block a specific interface from receiving a notification, you specify it with the `` element. You can specify the notification type (event), event class, interface, and/or interface class to block. ```xml ``` ### Using Subscriptions When registering a listener, you can specify that it only receives notifications from a specific component using the `subscription` attribute. For example, to specify that the listener only receives notifications from a flow component called "MyService1", you would configure the listener as follows: ```xml ``` To register interest in notifications from all flow components with "Service" in the name, you would use a wildcard string as follows: For more information, see [Registering Listeners Programmatically](#registering-listeners-programmatically) below. ## Firing Custom Notifications Objects can fire custom notifications in Mule to notify custom listeners. For example, a discovery agent might fire a Client Found notification when a client connects. You fire a custom notification as follows: ```text CustomNotification n = new CustomNotification("Hello"); notificationDispatcher.dispatch(n); ``` Any objects implementing `CustomNotificationListener` will receive this notification. It’s a good idea to extend `CustomNotification` and define actions for your custom notification type. For example: ```text DiscoveryNotification n = new DiscoveryNotification(client, DiscoveryNotification.CLIENT_ADDED); notificationDispatcher.dispatch(n); ``` ## Notification Interfaces The following table describes the Mule server notifications and the interfaces in the `org.mule.runtime.api.notification` package. An object can implement one of these interfaces to become a listener for the associated notification. All listeners extend the `NotificationListener` interface.
NotificationDescriptionInterface

Connection Notification

Is fired when a connection is made or disconnected.

ConnectionNotificationListener

Custom Notification

Can be fired by components and other objects such as routers, transformers, agents to communicate a change of state to each other.

CustomNotificationListener

Exception Notification

An exception was thrown.

ExceptionNotificationListener

Management Notification

The state of the Mule instance or its resources have changed, such as internal queues reach capacity.

ManagementNotificationListener

Mule Context Notification

Can be fired when an event such as the mule context start occurs.

MuleContextNotificationListener

Routing Notification

Async-Reply routers use this when an event is received for an event group that has already been processed.

RoutingNotificationListener

Security Notification

Is fired when a request for authorization failed.

SecurityNotificationListener

Transaction Notification

Is fired after a transaction has begun, was committed, or was rolled back.

TransactionNotificationListener

Async-Message Notification

Can be fired when async work is scheduled and completed for a given flow.

AsyncMessageNotificationListener

Pipeline-Message Notification

Is fired at key steps in the processing of pipeline.

PipelineMessageNotificationListener

Message-Processor Notification

A message processor was invoked.

MessageProcessorNotificationListener

Exception Strategy Notification

An exception strategy was invoked.

ExceptionStrategyNotificationListener

Extension Notification

Can be fired by extensions, including custom data.

ExtensionNotificationListener

Connector-Message Notification

Is fired when a message is received or sent through a Connector.

ConnectorMessageNotificationListener

The listener interfaces all have a single method: ```java public void onNotification(T notification); ``` where T is a notification class (listener class without the 'Listener' at the end). Depending on the listener implemented, only certain notifications will be received. For example, if the object implements `ManagementNotificationListener`, only notifications of type `ManagementNotification` will be received. Objects can implement more than one listener to receive more types of notifications. ## Registering Listeners Programmatically You can register listeners as follows: notificationListenerRegistry.registerListener(listener); or: notificationListenerRegistry.registerListener(listener, selector); where `listener` is a `NotificationListener` instance and `selector` is a `Predicate` that works as a filter to apply on a fired notification before calling the listener with it. ## Notification Action Codes Each notification has an action code that determines the notification type. You can query the action code to determine its type. For example: **MyObject.java** ```java public class MyObject implements ConnectionNotificationListener { (...) public void onNotification(ConnectionNotification notification) { if (valueOf(ConnectionNotification.CONNECTION_FAILED).equals(notification.getAction().getIdentifier())) { // write here the logic to handle the connection failed notification } } } ``` ## Notification Payloads All notifications extend `java.util.EventObject`, and you can use the `getSource()` method to access the payload of the object. The following table describes the payloads for each type of notification.
NotificationPayload TypeResource IDDescription

Connection Notification

String

<connector-name>.receiver(<endpoint-uri>)

The message receiver or message dispatcher that was connected.

Custom Notification

Any object

Any String

The object type is custom to the object firing the notification.

Exception Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Management Notification

Object

The object ID

The monitored object that triggered this notification.

Mule Context Notification

MuleContext

Mule context ID

The Mule context instance. Equivalent to calling getMuleContext().

Routing Notification

Message

Message ID

The message sent or received.

Security Notification

SecurityException

The exception message

The security exception that occurred.

Transaction Notification

String

Transaction ID

The transaction that have triggered this notification.

Async-Message Notification

ComponentLocation

Component name

Component that has scheduled the async work.

Pipeline-Message Notification

String

Name

Pipeline name.

Message-Processor Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Exception Strategy Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Extension Notification

Object

Extension name

The payload can change from one extension to another.

Connector-Message Notification

ComponentLocation

Component name

The flow component that triggered this notification.

--- product: Mule Runtime version: 4.12 --- # Mule Server Notifications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule provides an internal notification mechanism that you can use to access changes that occur on the Mule Server, such as adding a flow component, a request for authorization failing, or Mule starting. You can set up your agents or flow components to react to these notifications. ## Configuring Notifications Message notifications provide a snapshot of all information sent into and out of the Mule Server. Mule fire these notifications whenever it receives or sends a message. These additional notifications have some impact on performance, so they are disabled by default. To enable message notifications, you set the type of messages you want to enable using the `` element in your Mule configuration file. You also register the notification listeners and associate interfaces with specific notifications. For example, first you create beans for the notification listeners in your spring configuration file, specifying the class of the type of notification you want to receive: ```xml ``` And then, add the reference for your spring configuration: ```xml ``` Next, you specify the notifications you want to receive using the `` element, and then register the listeners using the `` element: ```xml ``` When you specify the MESSAGE-PROCESSOR notification, a notification is sent before and after a message processor is invoked. Because the listeners implement the interface for the type of notification they want to receive, the listeners receive the correct notifications. For example, the `ProcessorNotificationLogger` class would implement `org.mule.runtime.api.notification.MessageProcessorNotificationListener`: ```java public class ProcessorNotificationLogger implements MessageProcessorNotificationListener { @Override public void onNotification(MessageProcessorNotification notification) { // write here the logic to process the notification event } } ``` > [!IMPORTANT] Don’t forget to add the mule-api dependency in your pom file with `provided` as > scope, so the api classes will be available in your classpath. The dependency will then be > provided by mule in runtime. For a list of notification types, see [Notifications Configuration Reference](https://docs.mulesoft.com/mule-runtime/4.12/notifications-configuration-reference). For a list of notification listener interfaces, see [Notification Interfaces](#notification-interfaces) below. ### Specifying a Different Interface If you want to change the interface associated with a notification, you specify the new interface with the `interface-class` attribute: ```xml ``` ### Configuring a Custom Notification If you create a custom notification, you also specify the `event-class` attribute: ```xml ``` ### Disabling Notifications If you want to block a specific interface from receiving a notification, you specify it with the `` element. You can specify the notification type (event), event class, interface, and/or interface class to block. ```xml ``` ### Using Subscriptions When registering a listener, you can specify that it only receives notifications from a specific component using the `subscription` attribute. For example, to specify that the listener only receives notifications from a flow component called "MyService1", you would configure the listener as follows: ```xml ``` To register interest in notifications from all flow components with "Service" in the name, you would use a wildcard string as follows: For more information, see [Registering Listeners Programmatically](#registering-listeners-programmatically) below. ## Firing Custom Notifications Objects can fire custom notifications in Mule to notify custom listeners. For example, a discovery agent might fire a Client Found notification when a client connects. You fire a custom notification as follows: ```text CustomNotification n = new CustomNotification("Hello"); notificationDispatcher.dispatch(n); ``` Any objects implementing `CustomNotificationListener` will receive this notification. It’s a good idea to extend `CustomNotification` and define actions for your custom notification type. For example: ```text DiscoveryNotification n = new DiscoveryNotification(client, DiscoveryNotification.CLIENT_ADDED); notificationDispatcher.dispatch(n); ``` ## Notification Interfaces The following table describes the Mule server notifications and the interfaces in the `org.mule.runtime.api.notification` package. An object can implement one of these interfaces to become a listener for the associated notification. All listeners extend the `NotificationListener` interface.
NotificationDescriptionInterface

Connection Notification

Is fired when a connection is made or disconnected.

ConnectionNotificationListener

Custom Notification

Can be fired by components and other objects such as routers, transformers, agents to communicate a change of state to each other.

CustomNotificationListener

Exception Notification

An exception was thrown.

ExceptionNotificationListener

Management Notification

The state of the Mule instance or its resources have changed, such as internal queues reach capacity.

ManagementNotificationListener

Mule Context Notification

Can be fired when an event such as the mule context start occurs.

MuleContextNotificationListener

Routing Notification

Async-Reply routers use this when an event is received for an event group that has already been processed.

RoutingNotificationListener

Security Notification

Is fired when a request for authorization failed.

SecurityNotificationListener

Transaction Notification

Is fired after a transaction has begun, was committed, or was rolled back.

TransactionNotificationListener

Async-Message Notification

Can be fired when async work is scheduled and completed for a given flow.

AsyncMessageNotificationListener

Pipeline-Message Notification

Is fired at key steps in the processing of pipeline.

PipelineMessageNotificationListener

Message-Processor Notification

A message processor was invoked.

MessageProcessorNotificationListener

Exception Strategy Notification

An exception strategy was invoked.

ExceptionStrategyNotificationListener

Extension Notification

Can be fired by extensions, including custom data.

ExtensionNotificationListener

Connector-Message Notification

Is fired when a message is received or sent through a Connector.

ConnectorMessageNotificationListener

The listener interfaces all have a single method: ```java public void onNotification(T notification); ``` where T is a notification class (listener class without the 'Listener' at the end). Depending on the listener implemented, only certain notifications will be received. For example, if the object implements `ManagementNotificationListener`, only notifications of type `ManagementNotification` will be received. Objects can implement more than one listener to receive more types of notifications. ## Registering Listeners Programmatically You can register listeners as follows: notificationListenerRegistry.registerListener(listener); or: notificationListenerRegistry.registerListener(listener, selector); where `listener` is a `NotificationListener` instance and `selector` is a `Predicate` that works as a filter to apply on a fired notification before calling the listener with it. ## Notification Action Codes Each notification has an action code that determines the notification type. You can query the action code to determine its type. For example: **MyObject.java** ```java public class MyObject implements ConnectionNotificationListener { (...) public void onNotification(ConnectionNotification notification) { if (valueOf(ConnectionNotification.CONNECTION_FAILED).equals(notification.getAction().getIdentifier())) { // write here the logic to handle the connection failed notification } } } ``` ## Notification Payloads All notifications extend `java.util.EventObject`, and you can use the `getSource()` method to access the payload of the object. The following table describes the payloads for each type of notification.
NotificationPayload TypeResource IDDescription

Connection Notification

String

<connector-name>.receiver(<endpoint-uri>)

The message receiver or message dispatcher that was connected.

Custom Notification

Any object

Any String

The object type is custom to the object firing the notification.

Exception Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Management Notification

Object

The object ID

The monitored object that triggered this notification.

Mule Context Notification

MuleContext

Mule context ID

The Mule context instance. Equivalent to calling getMuleContext().

Routing Notification

Message

Message ID

The message sent or received.

Security Notification

SecurityException

The exception message

The security exception that occurred.

Transaction Notification

String

Transaction ID

The transaction that have triggered this notification.

Async-Message Notification

ComponentLocation

Component name

Component that has scheduled the async work.

Pipeline-Message Notification

String

Name

Pipeline name.

Message-Processor Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Exception Strategy Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Extension Notification

Object

Extension name

The payload can change from one extension to another.

Connector-Message Notification

ComponentLocation

Component name

The flow component that triggered this notification.

--- product: Mule Runtime version: 4.3 --- # Mule Server Notifications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule provides an internal notification mechanism that you can use to access changes that occur on the Mule Server, such as adding a flow component, a request for authorization failing, or Mule starting. You can set up your agents or flow components to react to these notifications. ## Configuring Notifications Message notifications provide a snapshot of all information sent into and out of the Mule Server. Mule fire these notifications whenever it receives or sends a message. These additional notifications have some impact on performance, so they are disabled by default. To enable message notifications, you set the type of messages you want to enable using the `` element in your Mule configuration file. You also register the notification listeners and associate interfaces with specific notifications. For example, first you create beans for the notification listeners in your spring configuration file, specifying the class of the type of notification you want to receive: ```xml ``` And then, add the reference for your spring configuration: ```xml ``` Next, you specify the notifications you want to receive using the `` element, and then register the listeners using the `` element: ```xml ``` When you specify the MESSAGE-PROCESSOR notification, a notification is sent before and after a message processor is invoked. Because the listeners implement the interface for the type of notification they want to receive, the listeners receive the correct notifications. For example, the `ProcessorNotificationLogger` class would implement `org.mule.runtime.api.notification.MessageProcessorNotificationListener`: ```java public class ProcessorNotificationLogger implements MessageProcessorNotificationListener { @Override public void onNotification(MessageProcessorNotification notification) { // write here the logic to process the notification event } } ``` > [!CAUTION] Don’t forget to add the mule-api dependency in your pom file with `provided` as scope, > so the api classes will be available in your classpath. The dependency will then be provided by > mule in runtime. For a list of notification types, see [Notifications Configuration Reference](https://docs.mulesoft.com/mule-runtime/4.3/notifications-configuration-reference). For a list of notification listener interfaces, see [Notification Interfaces](#notification-interfaces) below. ### Specifying a Different Interface If you want to change the interface associated with a notification, you specify the new interface with the `interface-class` attribute: ```xml ``` ### Configuring a Custom Notification If you create a custom notification, you also specify the `event-class` attribute: ```xml ``` ### Disabling Notifications If you want to block a specific interface from receiving a notification, you specify it with the `` element. You can specify the notification type (event), event class, interface, and/or interface class to block. ```xml ``` ### Using Subscriptions When registering a listener, you can specify that it only receives notifications from a specific component using the `subscription` attribute. For example, to specify that the listener only receives notifications from a flow component called "MyService1", you would configure the listener as follows: ```xml ``` To register interest in notifications from all flow components with "Service" in the name, you would use a wildcard string as follows: For more information, see [Registering Listeners Programmatically](#registering-listeners-programmatically) below. ## Firing Custom Notifications Objects can fire custom notifications in Mule to notify custom listeners. For example, a discovery agent might fire a Client Found notification when a client connects. You fire a custom notification as follows: ```text CustomNotification n = new CustomNotification("Hello"); notificationDispatcher.dispatch(n); ``` Any objects implementing `CustomNotificationListener` will receive this notification. It’s a good idea to extend `CustomNotification` and define actions for your custom notification type. For example: ```text DiscoveryNotification n = new DiscoveryNotification(client, DiscoveryNotification.CLIENT_ADDED); notificationDispatcher.dispatch(n); ``` ## Notification Interfaces The following table describes the Mule server notifications and the interfaces in the `org.mule.runtime.api.notification` package. An object can implement one of these interfaces to become a listener for the associated notification. All listeners extend the `NotificationListener` interface.
NotificationDescriptionInterface

Connection Notification

Is fired when a connection is made or disconnected.

ConnectionNotificationListener

Custom Notification

Can be fired by components and other objects such as routers, transformers, agents to communicate a change of state to each other.

CustomNotificationListener

Exception Notification

An exception was thrown.

ExceptionNotificationListener

Management Notification

The state of the Mule instance or its resources have changed, such as internal queues reach capacity.

ManagementNotificationListener

Mule Context Notification

Can be fired when an event such as the mule context start occurs.

MuleContextNotificationListener

Routing Notification

Async-Reply routers use this when an event is received for an event group that has already been processed.

RoutingNotificationListener

Security Notification

Is fired when a request for authorization failed.

SecurityNotificationListener

Transaction Notification

Is fired after a transaction has begun, was committed, or was rolled back.

TransactionNotificationListener

Async-Message Notification

Can be fired when async work is scheduled and completed for a given flow.

AsyncMessageNotificationListener

Pipeline-Message Notification

Is fired at key steps in the processing of pipeline.

PipelineMessageNotificationListener

Message-Processor Notification

A message processor was invoked.

MessageProcessorNotificationListener

Exception Strategy Notification

An exception strategy was invoked.

ExceptionStrategyNotificationListener

Extension Notification

Can be fired by extensions, including custom data.

ExtensionNotificationListener

Connector-Message Notification

Is fired when a message is received or sent through a Connector.

ConnectorMessageNotificationListener

The listener interfaces all have a single method: ```java public void onNotification(T notification); ``` where T is a notification class (listener class without the 'Listener' at the end). Depending on the listener implemented, only certain notifications will be received. For example, if the object implements `ManagementNotificationListener`, only notifications of type `ManagementNotification` will be received. Objects can implement more than one listener to receive more types of notifications. ## Registering Listeners Programmatically You can register listeners as follows: notificationListenerRegistry.registerListener(listener); or: notificationListenerRegistry.registerListener(listener, selector); where `listener` is a `NotificationListener` instance and `selector` is a `Predicate` that works as a filter to apply on a fired notification before calling the listener with it. ## Notification Action Codes Each notification has an action code that determines the notification type. You can query the action code to determine its type. For example: **MyObject.java** ```java public class MyObject implements ConnectionNotificationListener { (...) public void onNotification(ConnectionNotification notification) { if (valueOf(ConnectionNotification.CONNECTION_FAILED).equals(notification.getAction().getIdentifier())) { // write here the logic to handle the connection failed notification } } } ``` ## Notification Payloads All notifications extend `java.util.EventObject`, and you can use the `getSource()` method to access the payload of the object. The following table describes the payloads for each type of notification.
NotificationPayload TypeResource IDDescription

Connection Notification

String

<connector-name>.receiver(<endpoint-uri>)

The message receiver or message dispatcher that was connected.

Custom Notification

Any object

Any String

The object type is custom to the object firing the notification.

Exception Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Management Notification

Object

The object ID

The monitored object that triggered this notification.

Mule Context Notification

MuleContext

Mule context ID

The Mule context instance. Equivalent to calling getMuleContext().

Routing Notification

Message

Message ID

The message sent or received.

Security Notification

SecurityException

The exception message

The security exception that occurred.

Transaction Notification

String

Transaction ID

The transaction that have triggered this notification.

Async-Message Notification

ComponentLocation

Component name

Component that has scheduled the async work.

Pipeline-Message Notification

String

Name

Pipeline name.

Message-Processor Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Exception Strategy Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Extension Notification

Object

Extension name

The payload can change from one extension to another.

Connector-Message Notification

ComponentLocation

Component name

The flow component that triggered this notification.

--- product: Mule Runtime version: 4.4 --- # Mule Server Notifications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule provides an internal notification mechanism that you can use to access changes that occur on the Mule Server, such as adding a flow component, a request for authorization failing, or Mule starting. You can set up your agents or flow components to react to these notifications. ## Configuring Notifications Message notifications provide a snapshot of all information sent into and out of the Mule Server. Mule fire these notifications whenever it receives or sends a message. These additional notifications have some impact on performance, so they are disabled by default. To enable message notifications, you set the type of messages you want to enable using the `` element in your Mule configuration file. You also register the notification listeners and associate interfaces with specific notifications. For example, first you create beans for the notification listeners in your spring configuration file, specifying the class of the type of notification you want to receive: ```xml ``` And then, add the reference for your spring configuration: ```xml ``` Next, you specify the notifications you want to receive using the `` element, and then register the listeners using the `` element: ```xml ``` When you specify the MESSAGE-PROCESSOR notification, a notification is sent before and after a message processor is invoked. Because the listeners implement the interface for the type of notification they want to receive, the listeners receive the correct notifications. For example, the `ProcessorNotificationLogger` class would implement `org.mule.runtime.api.notification.MessageProcessorNotificationListener`: ```java public class ProcessorNotificationLogger implements MessageProcessorNotificationListener { @Override public void onNotification(MessageProcessorNotification notification) { // write here the logic to process the notification event } } ``` > [!CAUTION] Don’t forget to add the mule-api dependency in your pom file with `provided` as scope, > so the api classes will be available in your classpath. The dependency will then be provided by > mule in runtime. For a list of notification types, see [Notifications Configuration Reference](https://docs.mulesoft.com/mule-runtime/4.4/notifications-configuration-reference). For a list of notification listener interfaces, see [Notification Interfaces](#notification-interfaces) below. ### Specifying a Different Interface If you want to change the interface associated with a notification, you specify the new interface with the `interface-class` attribute: ```xml ``` ### Configuring a Custom Notification If you create a custom notification, you also specify the `event-class` attribute: ```xml ``` ### Disabling Notifications If you want to block a specific interface from receiving a notification, you specify it with the `` element. You can specify the notification type (event), event class, interface, and/or interface class to block. ```xml ``` ### Using Subscriptions When registering a listener, you can specify that it only receives notifications from a specific component using the `subscription` attribute. For example, to specify that the listener only receives notifications from a flow component called "MyService1", you would configure the listener as follows: ```xml ``` To register interest in notifications from all flow components with "Service" in the name, you would use a wildcard string as follows: For more information, see [Registering Listeners Programmatically](#registering-listeners-programmatically) below. ## Firing Custom Notifications Objects can fire custom notifications in Mule to notify custom listeners. For example, a discovery agent might fire a Client Found notification when a client connects. You fire a custom notification as follows: ```text CustomNotification n = new CustomNotification("Hello"); notificationDispatcher.dispatch(n); ``` Any objects implementing `CustomNotificationListener` will receive this notification. It’s a good idea to extend `CustomNotification` and define actions for your custom notification type. For example: ```text DiscoveryNotification n = new DiscoveryNotification(client, DiscoveryNotification.CLIENT_ADDED); notificationDispatcher.dispatch(n); ``` ## Notification Interfaces The following table describes the Mule server notifications and the interfaces in the `org.mule.runtime.api.notification` package. An object can implement one of these interfaces to become a listener for the associated notification. All listeners extend the `NotificationListener` interface.
NotificationDescriptionInterface

Connection Notification

Is fired when a connection is made or disconnected.

ConnectionNotificationListener

Custom Notification

Can be fired by components and other objects such as routers, transformers, agents to communicate a change of state to each other.

CustomNotificationListener

Exception Notification

An exception was thrown.

ExceptionNotificationListener

Management Notification

The state of the Mule instance or its resources have changed, such as internal queues reach capacity.

ManagementNotificationListener

Mule Context Notification

Can be fired when an event such as the mule context start occurs.

MuleContextNotificationListener

Routing Notification

Async-Reply routers use this when an event is received for an event group that has already been processed.

RoutingNotificationListener

Security Notification

Is fired when a request for authorization failed.

SecurityNotificationListener

Transaction Notification

Is fired after a transaction has begun, was committed, or was rolled back.

TransactionNotificationListener

Async-Message Notification

Can be fired when async work is scheduled and completed for a given flow.

AsyncMessageNotificationListener

Pipeline-Message Notification

Is fired at key steps in the processing of pipeline.

PipelineMessageNotificationListener

Message-Processor Notification

A message processor was invoked.

MessageProcessorNotificationListener

Exception Strategy Notification

An exception strategy was invoked.

ExceptionStrategyNotificationListener

Extension Notification

Can be fired by extensions, including custom data.

ExtensionNotificationListener

Connector-Message Notification

Is fired when a message is received or sent through a Connector.

ConnectorMessageNotificationListener

The listener interfaces all have a single method: ```java public void onNotification(T notification); ``` where T is a notification class (listener class without the 'Listener' at the end). Depending on the listener implemented, only certain notifications will be received. For example, if the object implements `ManagementNotificationListener`, only notifications of type `ManagementNotification` will be received. Objects can implement more than one listener to receive more types of notifications. ## Registering Listeners Programmatically You can register listeners as follows: notificationListenerRegistry.registerListener(listener); or: notificationListenerRegistry.registerListener(listener, selector); where `listener` is a `NotificationListener` instance and `selector` is a `Predicate` that works as a filter to apply on a fired notification before calling the listener with it. ## Notification Action Codes Each notification has an action code that determines the notification type. You can query the action code to determine its type. For example: **MyObject.java** ```java public class MyObject implements ConnectionNotificationListener { (...) public void onNotification(ConnectionNotification notification) { if (valueOf(ConnectionNotification.CONNECTION_FAILED).equals(notification.getAction().getIdentifier())) { // write here the logic to handle the connection failed notification } } } ``` ## Notification Payloads All notifications extend `java.util.EventObject`, and you can use the `getSource()` method to access the payload of the object. The following table describes the payloads for each type of notification.
NotificationPayload TypeResource IDDescription

Connection Notification

String

<connector-name>.receiver(<endpoint-uri>)

The message receiver or message dispatcher that was connected.

Custom Notification

Any object

Any String

The object type is custom to the object firing the notification.

Exception Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Management Notification

Object

The object ID

The monitored object that triggered this notification.

Mule Context Notification

MuleContext

Mule context ID

The Mule context instance. Equivalent to calling getMuleContext().

Routing Notification

Message

Message ID

The message sent or received.

Security Notification

SecurityException

The exception message

The security exception that occurred.

Transaction Notification

String

Transaction ID

The transaction that have triggered this notification.

Async-Message Notification

ComponentLocation

Component name

Component that has scheduled the async work.

Pipeline-Message Notification

String

Name

Pipeline name.

Message-Processor Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Exception Strategy Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Extension Notification

Object

Extension name

The payload can change from one extension to another.

Connector-Message Notification

ComponentLocation

Component name

The flow component that triggered this notification.

--- product: Mule Runtime version: 4.6 --- # Mule Server Notifications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule provides an internal notification mechanism that you can use to access changes that occur on the Mule Server, such as adding a flow component, a request for authorization failing, or Mule starting. You can set up your agents or flow components to react to these notifications. ## Configuring Notifications Message notifications provide a snapshot of all information sent into and out of the Mule Server. Mule fire these notifications whenever it receives or sends a message. These additional notifications have some impact on performance, so they are disabled by default. To enable message notifications, you set the type of messages you want to enable using the `` element in your Mule configuration file. You also register the notification listeners and associate interfaces with specific notifications. For example, first you create beans for the notification listeners in your spring configuration file, specifying the class of the type of notification you want to receive: ```xml ``` And then, add the reference for your spring configuration: ```xml ``` Next, you specify the notifications you want to receive using the `` element, and then register the listeners using the `` element: ```xml ``` When you specify the MESSAGE-PROCESSOR notification, a notification is sent before and after a message processor is invoked. Because the listeners implement the interface for the type of notification they want to receive, the listeners receive the correct notifications. For example, the `ProcessorNotificationLogger` class would implement `org.mule.runtime.api.notification.MessageProcessorNotificationListener`: ```java public class ProcessorNotificationLogger implements MessageProcessorNotificationListener { @Override public void onNotification(MessageProcessorNotification notification) { // write here the logic to process the notification event } } ``` > [!CAUTION] Don’t forget to add the mule-api dependency in your pom file with `provided` as scope, > so the api classes will be available in your classpath. The dependency will then be provided by > mule in runtime. For a list of notification types, see [Notifications Configuration Reference](https://docs.mulesoft.com/mule-runtime/4.6/notifications-configuration-reference). For a list of notification listener interfaces, see [Notification Interfaces](#notification-interfaces) below. ### Specifying a Different Interface If you want to change the interface associated with a notification, you specify the new interface with the `interface-class` attribute: ```xml ``` ### Configuring a Custom Notification If you create a custom notification, you also specify the `event-class` attribute: ```xml ``` ### Disabling Notifications If you want to block a specific interface from receiving a notification, you specify it with the `` element. You can specify the notification type (event), event class, interface, and/or interface class to block. ```xml ``` ### Using Subscriptions When registering a listener, you can specify that it only receives notifications from a specific component using the `subscription` attribute. For example, to specify that the listener only receives notifications from a flow component called "MyService1", you would configure the listener as follows: ```xml ``` To register interest in notifications from all flow components with "Service" in the name, you would use a wildcard string as follows: For more information, see [Registering Listeners Programmatically](#registering-listeners-programmatically) below. ## Firing Custom Notifications Objects can fire custom notifications in Mule to notify custom listeners. For example, a discovery agent might fire a Client Found notification when a client connects. You fire a custom notification as follows: ```text CustomNotification n = new CustomNotification("Hello"); notificationDispatcher.dispatch(n); ``` Any objects implementing `CustomNotificationListener` will receive this notification. It’s a good idea to extend `CustomNotification` and define actions for your custom notification type. For example: ```text DiscoveryNotification n = new DiscoveryNotification(client, DiscoveryNotification.CLIENT_ADDED); notificationDispatcher.dispatch(n); ``` ## Notification Interfaces The following table describes the Mule server notifications and the interfaces in the `org.mule.runtime.api.notification` package. An object can implement one of these interfaces to become a listener for the associated notification. All listeners extend the `NotificationListener` interface.
NotificationDescriptionInterface

Connection Notification

Is fired when a connection is made or disconnected.

ConnectionNotificationListener

Custom Notification

Can be fired by components and other objects such as routers, transformers, agents to communicate a change of state to each other.

CustomNotificationListener

Exception Notification

An exception was thrown.

ExceptionNotificationListener

Management Notification

The state of the Mule instance or its resources have changed, such as internal queues reach capacity.

ManagementNotificationListener

Mule Context Notification

Can be fired when an event such as the mule context start occurs.

MuleContextNotificationListener

Routing Notification

Async-Reply routers use this when an event is received for an event group that has already been processed.

RoutingNotificationListener

Security Notification

Is fired when a request for authorization failed.

SecurityNotificationListener

Transaction Notification

Is fired after a transaction has begun, was committed, or was rolled back.

TransactionNotificationListener

Async-Message Notification

Can be fired when async work is scheduled and completed for a given flow.

AsyncMessageNotificationListener

Pipeline-Message Notification

Is fired at key steps in the processing of pipeline.

PipelineMessageNotificationListener

Message-Processor Notification

A message processor was invoked.

MessageProcessorNotificationListener

Exception Strategy Notification

An exception strategy was invoked.

ExceptionStrategyNotificationListener

Extension Notification

Can be fired by extensions, including custom data.

ExtensionNotificationListener

Connector-Message Notification

Is fired when a message is received or sent through a Connector.

ConnectorMessageNotificationListener

The listener interfaces all have a single method: ```java public void onNotification(T notification); ``` where T is a notification class (listener class without the 'Listener' at the end). Depending on the listener implemented, only certain notifications will be received. For example, if the object implements `ManagementNotificationListener`, only notifications of type `ManagementNotification` will be received. Objects can implement more than one listener to receive more types of notifications. ## Registering Listeners Programmatically You can register listeners as follows: notificationListenerRegistry.registerListener(listener); or: notificationListenerRegistry.registerListener(listener, selector); where `listener` is a `NotificationListener` instance and `selector` is a `Predicate` that works as a filter to apply on a fired notification before calling the listener with it. ## Notification Action Codes Each notification has an action code that determines the notification type. You can query the action code to determine its type. For example: **MyObject.java** ```java public class MyObject implements ConnectionNotificationListener { (...) public void onNotification(ConnectionNotification notification) { if (valueOf(ConnectionNotification.CONNECTION_FAILED).equals(notification.getAction().getIdentifier())) { // write here the logic to handle the connection failed notification } } } ``` ## Notification Payloads All notifications extend `java.util.EventObject`, and you can use the `getSource()` method to access the payload of the object. The following table describes the payloads for each type of notification.
NotificationPayload TypeResource IDDescription

Connection Notification

String

<connector-name>.receiver(<endpoint-uri>)

The message receiver or message dispatcher that was connected.

Custom Notification

Any object

Any String

The object type is custom to the object firing the notification.

Exception Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Management Notification

Object

The object ID

The monitored object that triggered this notification.

Mule Context Notification

MuleContext

Mule context ID

The Mule context instance. Equivalent to calling getMuleContext().

Routing Notification

Message

Message ID

The message sent or received.

Security Notification

SecurityException

The exception message

The security exception that occurred.

Transaction Notification

String

Transaction ID

The transaction that have triggered this notification.

Async-Message Notification

ComponentLocation

Component name

Component that has scheduled the async work.

Pipeline-Message Notification

String

Name

Pipeline name.

Message-Processor Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Exception Strategy Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Extension Notification

Object

Extension name

The payload can change from one extension to another.

Connector-Message Notification

ComponentLocation

Component name

The flow component that triggered this notification.

--- product: Mule Runtime version: 4.9 --- # Mule Server Notifications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule provides an internal notification mechanism that you can use to access changes that occur on the Mule Server, such as adding a flow component, a request for authorization failing, or Mule starting. You can set up your agents or flow components to react to these notifications. ## Configuring Notifications Message notifications provide a snapshot of all information sent into and out of the Mule Server. Mule fire these notifications whenever it receives or sends a message. These additional notifications have some impact on performance, so they are disabled by default. To enable message notifications, you set the type of messages you want to enable using the `` element in your Mule configuration file. You also register the notification listeners and associate interfaces with specific notifications. For example, first you create beans for the notification listeners in your spring configuration file, specifying the class of the type of notification you want to receive: ```xml ``` And then, add the reference for your spring configuration: ```xml ``` Next, you specify the notifications you want to receive using the `` element, and then register the listeners using the `` element: ```xml ``` When you specify the MESSAGE-PROCESSOR notification, a notification is sent before and after a message processor is invoked. Because the listeners implement the interface for the type of notification they want to receive, the listeners receive the correct notifications. For example, the `ProcessorNotificationLogger` class would implement `org.mule.runtime.api.notification.MessageProcessorNotificationListener`: ```java public class ProcessorNotificationLogger implements MessageProcessorNotificationListener { @Override public void onNotification(MessageProcessorNotification notification) { // write here the logic to process the notification event } } ``` > [!IMPORTANT] Don’t forget to add the mule-api dependency in your pom file with `provided` as > scope, so the api classes will be available in your classpath. The dependency will then be > provided by mule in runtime. For a list of notification types, see [Notifications Configuration Reference](https://docs.mulesoft.com/mule-runtime/4.9/notifications-configuration-reference). For a list of notification listener interfaces, see [Notification Interfaces](#notification-interfaces) below. ### Specifying a Different Interface If you want to change the interface associated with a notification, you specify the new interface with the `interface-class` attribute: ```xml ``` ### Configuring a Custom Notification If you create a custom notification, you also specify the `event-class` attribute: ```xml ``` ### Disabling Notifications If you want to block a specific interface from receiving a notification, you specify it with the `` element. You can specify the notification type (event), event class, interface, and/or interface class to block. ```xml ``` ### Using Subscriptions When registering a listener, you can specify that it only receives notifications from a specific component using the `subscription` attribute. For example, to specify that the listener only receives notifications from a flow component called "MyService1", you would configure the listener as follows: ```xml ``` To register interest in notifications from all flow components with "Service" in the name, you would use a wildcard string as follows: For more information, see [Registering Listeners Programmatically](#registering-listeners-programmatically) below. ## Firing Custom Notifications Objects can fire custom notifications in Mule to notify custom listeners. For example, a discovery agent might fire a Client Found notification when a client connects. You fire a custom notification as follows: ```text CustomNotification n = new CustomNotification("Hello"); notificationDispatcher.dispatch(n); ``` Any objects implementing `CustomNotificationListener` will receive this notification. It’s a good idea to extend `CustomNotification` and define actions for your custom notification type. For example: ```text DiscoveryNotification n = new DiscoveryNotification(client, DiscoveryNotification.CLIENT_ADDED); notificationDispatcher.dispatch(n); ``` ## Notification Interfaces The following table describes the Mule server notifications and the interfaces in the `org.mule.runtime.api.notification` package. An object can implement one of these interfaces to become a listener for the associated notification. All listeners extend the `NotificationListener` interface.
NotificationDescriptionInterface

Connection Notification

Is fired when a connection is made or disconnected.

ConnectionNotificationListener

Custom Notification

Can be fired by components and other objects such as routers, transformers, agents to communicate a change of state to each other.

CustomNotificationListener

Exception Notification

An exception was thrown.

ExceptionNotificationListener

Management Notification

The state of the Mule instance or its resources have changed, such as internal queues reach capacity.

ManagementNotificationListener

Mule Context Notification

Can be fired when an event such as the mule context start occurs.

MuleContextNotificationListener

Routing Notification

Async-Reply routers use this when an event is received for an event group that has already been processed.

RoutingNotificationListener

Security Notification

Is fired when a request for authorization failed.

SecurityNotificationListener

Transaction Notification

Is fired after a transaction has begun, was committed, or was rolled back.

TransactionNotificationListener

Async-Message Notification

Can be fired when async work is scheduled and completed for a given flow.

AsyncMessageNotificationListener

Pipeline-Message Notification

Is fired at key steps in the processing of pipeline.

PipelineMessageNotificationListener

Message-Processor Notification

A message processor was invoked.

MessageProcessorNotificationListener

Exception Strategy Notification

An exception strategy was invoked.

ExceptionStrategyNotificationListener

Extension Notification

Can be fired by extensions, including custom data.

ExtensionNotificationListener

Connector-Message Notification

Is fired when a message is received or sent through a Connector.

ConnectorMessageNotificationListener

The listener interfaces all have a single method: ```java public void onNotification(T notification); ``` where T is a notification class (listener class without the 'Listener' at the end). Depending on the listener implemented, only certain notifications will be received. For example, if the object implements `ManagementNotificationListener`, only notifications of type `ManagementNotification` will be received. Objects can implement more than one listener to receive more types of notifications. ## Registering Listeners Programmatically You can register listeners as follows: notificationListenerRegistry.registerListener(listener); or: notificationListenerRegistry.registerListener(listener, selector); where `listener` is a `NotificationListener` instance and `selector` is a `Predicate` that works as a filter to apply on a fired notification before calling the listener with it. ## Notification Action Codes Each notification has an action code that determines the notification type. You can query the action code to determine its type. For example: **MyObject.java** ```java public class MyObject implements ConnectionNotificationListener { (...) public void onNotification(ConnectionNotification notification) { if (valueOf(ConnectionNotification.CONNECTION_FAILED).equals(notification.getAction().getIdentifier())) { // write here the logic to handle the connection failed notification } } } ``` ## Notification Payloads All notifications extend `java.util.EventObject`, and you can use the `getSource()` method to access the payload of the object. The following table describes the payloads for each type of notification.
NotificationPayload TypeResource IDDescription

Connection Notification

String

<connector-name>.receiver(<endpoint-uri>)

The message receiver or message dispatcher that was connected.

Custom Notification

Any object

Any String

The object type is custom to the object firing the notification.

Exception Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Management Notification

Object

The object ID

The monitored object that triggered this notification.

Mule Context Notification

MuleContext

Mule context ID

The Mule context instance. Equivalent to calling getMuleContext().

Routing Notification

Message

Message ID

The message sent or received.

Security Notification

SecurityException

The exception message

The security exception that occurred.

Transaction Notification

String

Transaction ID

The transaction that have triggered this notification.

Async-Message Notification

ComponentLocation

Component name

Component that has scheduled the async work.

Pipeline-Message Notification

String

Name

Pipeline name.

Message-Processor Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Exception Strategy Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Extension Notification

Object

Extension name

The payload can change from one extension to another.

Connector-Message Notification

ComponentLocation

Component name

The flow component that triggered this notification.

--- product: Mule Runtime version: 4.13 is-latest-version: true --- # Mule Server Notifications > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Mule provides an internal notification mechanism that you can use to access changes that occur on the Mule Server, such as adding a flow component, a request for authorization failing, or Mule starting. You can set up your agents or flow components to react to these notifications. ## Configuring Notifications Message notifications provide a snapshot of all information sent into and out of the Mule Server. Mule fire these notifications whenever it receives or sends a message. These additional notifications have some impact on performance, so they are disabled by default. To enable message notifications, you set the type of messages you want to enable using the `` element in your Mule configuration file. You also register the notification listeners and associate interfaces with specific notifications. For example, first you create beans for the notification listeners in your spring configuration file, specifying the class of the type of notification you want to receive: ```xml ``` And then, add the reference for your spring configuration: ```xml ``` Next, you specify the notifications you want to receive using the `` element, and then register the listeners using the `` element: ```xml ``` When you specify the MESSAGE-PROCESSOR notification, a notification is sent before and after a message processor is invoked. Because the listeners implement the interface for the type of notification they want to receive, the listeners receive the correct notifications. For example, the `ProcessorNotificationLogger` class would implement `org.mule.runtime.api.notification.MessageProcessorNotificationListener`: ```java public class ProcessorNotificationLogger implements MessageProcessorNotificationListener { @Override public void onNotification(MessageProcessorNotification notification) { // write here the logic to process the notification event } } ``` > [!IMPORTANT] Don’t forget to add the mule-api dependency in your pom file with `provided` as > scope, so the api classes will be available in your classpath. The dependency will then be > provided by mule in runtime. For a list of notification types, see [Notifications Configuration Reference](https://docs.mulesoft.com/mule-runtime/latest/notifications-configuration-reference). For a list of notification listener interfaces, see [Notification Interfaces](#notification-interfaces) below. ### Specifying a Different Interface If you want to change the interface associated with a notification, you specify the new interface with the `interface-class` attribute: ```xml ``` ### Configuring a Custom Notification If you create a custom notification, you also specify the `event-class` attribute: ```xml ``` ### Disabling Notifications If you want to block a specific interface from receiving a notification, you specify it with the `` element. You can specify the notification type (event), event class, interface, and/or interface class to block. ```xml ``` ### Using Subscriptions When registering a listener, you can specify that it only receives notifications from a specific component using the `subscription` attribute. For example, to specify that the listener only receives notifications from a flow component called "MyService1", you would configure the listener as follows: ```xml ``` To register interest in notifications from all flow components with "Service" in the name, you would use a wildcard string as follows: For more information, see [Registering Listeners Programmatically](#registering-listeners-programmatically) below. ## Firing Custom Notifications Objects can fire custom notifications in Mule to notify custom listeners. For example, a discovery agent might fire a Client Found notification when a client connects. You fire a custom notification as follows: ```text CustomNotification n = new CustomNotification("Hello"); notificationDispatcher.dispatch(n); ``` Any objects implementing `CustomNotificationListener` will receive this notification. It’s a good idea to extend `CustomNotification` and define actions for your custom notification type. For example: ```text DiscoveryNotification n = new DiscoveryNotification(client, DiscoveryNotification.CLIENT_ADDED); notificationDispatcher.dispatch(n); ``` ## Notification Interfaces The following table describes the Mule server notifications and the interfaces in the `org.mule.runtime.api.notification` package. An object can implement one of these interfaces to become a listener for the associated notification. All listeners extend the `NotificationListener` interface.
NotificationDescriptionInterface

Connection Notification

Is fired when a connection is made or disconnected.

ConnectionNotificationListener

Custom Notification

Can be fired by components and other objects such as routers, transformers, agents to communicate a change of state to each other.

CustomNotificationListener

Exception Notification

An exception was thrown.

ExceptionNotificationListener

Management Notification

The state of the Mule instance or its resources have changed, such as internal queues reach capacity.

ManagementNotificationListener

Mule Context Notification

Can be fired when an event such as the mule context start occurs.

MuleContextNotificationListener

Routing Notification

Async-Reply routers use this when an event is received for an event group that has already been processed.

RoutingNotificationListener

Security Notification

Is fired when a request for authorization failed.

SecurityNotificationListener

Transaction Notification

Is fired after a transaction has begun, was committed, or was rolled back.

TransactionNotificationListener

Async-Message Notification

Can be fired when async work is scheduled and completed for a given flow.

AsyncMessageNotificationListener

Pipeline-Message Notification

Is fired at key steps in the processing of pipeline.

PipelineMessageNotificationListener

Message-Processor Notification

A message processor was invoked.

MessageProcessorNotificationListener

Exception Strategy Notification

An exception strategy was invoked.

ExceptionStrategyNotificationListener

Extension Notification

Can be fired by extensions, including custom data.

ExtensionNotificationListener

Connector-Message Notification

Is fired when a message is received or sent through a Connector.

ConnectorMessageNotificationListener

The listener interfaces all have a single method: ```java public void onNotification(T notification); ``` where T is a notification class (listener class without the 'Listener' at the end). Depending on the listener implemented, only certain notifications will be received. For example, if the object implements `ManagementNotificationListener`, only notifications of type `ManagementNotification` will be received. Objects can implement more than one listener to receive more types of notifications. ## Registering Listeners Programmatically You can register listeners as follows: notificationListenerRegistry.registerListener(listener); or: notificationListenerRegistry.registerListener(listener, selector); where `listener` is a `NotificationListener` instance and `selector` is a `Predicate` that works as a filter to apply on a fired notification before calling the listener with it. ## Notification Action Codes Each notification has an action code that determines the notification type. You can query the action code to determine its type. For example: **MyObject.java** ```java public class MyObject implements ConnectionNotificationListener { (...) public void onNotification(ConnectionNotification notification) { if (valueOf(ConnectionNotification.CONNECTION_FAILED).equals(notification.getAction().getIdentifier())) { // write here the logic to handle the connection failed notification } } } ``` ## Notification Payloads All notifications extend `java.util.EventObject`, and you can use the `getSource()` method to access the payload of the object. The following table describes the payloads for each type of notification.
NotificationPayload TypeResource IDDescription

Connection Notification

String

<connector-name>.receiver(<endpoint-uri>)

The message receiver or message dispatcher that was connected.

Custom Notification

Any object

Any String

The object type is custom to the object firing the notification.

Exception Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Management Notification

Object

The object ID

The monitored object that triggered this notification.

Mule Context Notification

MuleContext

Mule context ID

The Mule context instance. Equivalent to calling getMuleContext().

Routing Notification

Message

Message ID

The message sent or received.

Security Notification

SecurityException

The exception message

The security exception that occurred.

Transaction Notification

String

Transaction ID

The transaction that have triggered this notification.

Async-Message Notification

ComponentLocation

Component name

Component that has scheduled the async work.

Pipeline-Message Notification

String

Name

Pipeline name.

Message-Processor Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Exception Strategy Notification

ComponentLocation

Component name

The flow component that triggered this notification.

Extension Notification

Object

Extension name

The payload can change from one extension to another.

Connector-Message Notification

ComponentLocation

Component name

The flow component that triggered this notification.

# Mule Troubleshooting Plugin Use the Mule Troubleshooting plugin to generate structured diagnostic information, simplify troubleshooting, and provide consistent data for Mule runtime support. The Mule Troubleshooting plugin provides a unified way to collect diagnostic data from Mule runtime environments. It generates a structured diagnostic archive called the Diagnostic Information Analysis File (DIAF), which consolidates Mule runtime information, application metrics, and system data into a single, standardized output. This Java-based plugin provides an extensible, environment-agnostic solution that simplifies troubleshooting for Mule runtime engineers, MuleSoft Support teams, customers running self-service diagnostics, and AI-assisted analysis. ## [](#before-you-begin)Before You Begin Before using the plugin, make sure that you have these prerequisites: - Supported Mule runtime distributions include version 4.10 and later, or LTS versions 4.9 (with patch 4.9.10 or later) and 4.6 (with patch 4.6.23 or later). - Java 8 or later, matching the Mule runtime version requirements. - Access to the `$MULE_HOME` directory. The CLI script `diag` automatically locates the Mule home directory. The plugin works out-of-the-box in the Standalone, CloudHub, and CloudHub 2.0 deployment models without installing additional dependencies. For details about CloudHub 2.0 diagnostics, see [Generating Apps Diagnostics and Analyzing with Einstein](https://docs.mulesoft.com/cloudhub-2/ch2-view-diag). ## [](#using-the-mule-troubleshooting-plugin)Using the Mule Troubleshooting Plugin Run this command from your Mule runtime installation at `$MULE_HOME/tools/diag` to generate the DIAF and a thread dump. By default, the tool saves the files unzipped in the `logs` directory of the distribution. Use the `./diag --extended` command to generate a heap dump. Use `./diag --output some/dir/name/` to create the directories if they don’t exist and save unzipped files there. Use `./diag --output some/dir/name` (without a trailing `/`) to create a ZIP file at that path containing all output files. On Windows, run `diag.bat`. The `--stdout` option isn’t supported. The plugin’s help output lists the available commands and options. ```bash ➜ mule-enterprise-standalone-4.6.23 ./tools/diag help Mule Troubleshooting Tool ========================= Usage: ./diag [options] [command] [command-options] Commands: diaf Generate a complete Mule diagnostic dump (default) help Show this help message Execute a specific troubleshooting operation Global Options: --stdout Output the diagnostic dump to standard output --output Specify custom output directory or file path --extended Enable extended mode (includes heap dump) --debug Enable debug mode with remote debugging on port 5005 Examples: ./diag # Generate diagnostic dump to logs directory ./diag --stdout # Output diagnostic dump to stdout ./diag --extended # Include heap dump in diagnostic ./diag --output /tmp/mule.zip # Save to specific file ./diag --output /tmp/ # Save to specific directory ./diag # Execute specific operation Output: By default, the tool creates a ZIP file containing: - mule_dump_.diaf # Diagnostic information - thread_dump_.txt # Thread dump - heap_dump_.hprof # Heap dump (if --extended is used) The ZIP file is saved to the 'logs' directory by default. ``` ## [](#understanding-diagnostic-information-analysis-file-diaf)Understanding Diagnostic Information Analysis File (DIAF) The Diagnostic Information Analysis File (DIAF) organizes all diagnostic data collected by the Mule Troubleshooting plugin into structured sections. Use this reference to understand the content of each section: - [Title](#diaf-title) - [Basic Information](#diaf-basic-info) - [System Info](#diaf-system-info) - [JVM Agents](#diaf-jvm-agents) - [Statistics](#diaf-statistics) - [Alerts](#diaf-alerts) - [Event Dump](#diaf-event-dump) - [Schedulers](#diaf-schedulers) - [CPU Usage](#diaf-cpu-usage) - [Deployments](#diaf-deployments) - [Connectors State](#diaf-connectors-state) - [Cluster Info](#diaf-cluster-info) ### [](#diaf-title)Title This section shows the report generation timestamp.
Field Description

Report Generation Timestamp

The report generation time, expressed in the local time zone.

### [](#diaf-basic-info)Basic Information This section shows details about the environment where the Mule runtime instance is running.

Available in Mule runtime 4.11.6 and later. The JVM resource metrics in this section appear under the JVM Resources block and use the jvm. prefix (for example, jvm.memory.used). In earlier patch versions, these metrics appear at the top level without the prefix (for example, memory.used). The metrics have the same meaning in both formats. Operating system details and the system-wide CPU load no longer appear in this section. See System Info for those metrics.

Field Description

Mule Product/version

Product (CE/EE), version, and build number of the Mule runtime. Formatted as [productName] [version] (build [buildNumber]).

mule_home

Absolute path to MULE_HOME for the Mule runtime.

mule_base

Absolute path to MULE_BASE for the Mule runtime.

mule.* System Properties

All system properties starting with mule., including those defined by DataWeave and API Gateway. Listed with values and sorted alphabetically.

Java Version

Version of the JVM running the Mule runtime.

Java Vendor

Vendor of the JVM running the Mule runtime.

Java VM Name

Full name of the JVM running the Mule runtime.

JAVA_HOME

Location of the JVM running the Mule runtime.

Running Time

Total time the Mule runtime has been running.

PID

Process ID of the JVM running the Mule runtime.

Report Millis Time

Report generation time in milliseconds since epoch (System.currentTimeMillis).

Report Nano Time

Report generation time in nanoseconds (System.nanoTime).

memory.used (jvm.memory.used)

Amount of used memory in the JVM.

memory.free (jvm.memory.free)

Amount of available memory in the JVM.

memory.total (jvm.memory.total)

Total amount of memory in the JVM.

memory.max (jvm.memory.max)

Maximum amount of memory the JVM attempts to use.

memory.used/total (jvm.memory.used/total)

Percentage of used memory compared to the total allocated memory.

memory.used/max (jvm.memory.used/max)

Percentage of used memory compared to the maximum available memory.

processors.available (jvm.processors.available)

Number of processors available to the JVM process.

load.process (jvm.load.process)

Percentage of recent CPU usage for the JVM process; negative value if unavailable.

License

(Enterprise Edition only) License information for Enterprise Edition distributions appears under the License block. This block doesn’t appear in Community Edition or when no Enterprise license is registered. When present, it can include:

  • valid: Indicates whether the license is valid.

  • validationError: Indicates the reason the license is not valid, when applicable.

  • evaluation: Indicates whether the license is an evaluation license.

  • expirationDate: The license expiration date.

  • licenseFile: The license file in use.

  • contact: Contact information, including name, email, telephone, company, and country.

  • entitlements: The list of entitlements granted by the license.

In Mule runtime patches earlier than 4.11.6, this section also reports OS Name, OS Version, OS Arch, load.system, and load.systemAverage. Starting with Mule 4.11.6, the operating system details (host.os.) and the host CPU load (host.cpu.load.) are reported in the System Info section instead.

### [](#diaf-system-info)System Info

Available in Mule runtime 4.11.6 and later.

This section shows host-level diagnostics for the machine, container, or pod where the Mule runtime instance is running. The diagnostics are collected from the host operating system. Unlike [Basic Information](#diaf-basic-info), which reports JVM-level metrics, this section reports host-level information. CPU load percentages are sampled over a short interval. Some fields are only populated on Linux hosts. On other operating systems, these fields can be absent or display `n/a`. If the runtime can’t collect host information, the report shows `Host info not available` instead. #### [](#operating-system)Operating System
Field Description

host.os.name

Name of the host operating system.

host.os.version

Version of the host operating system.

host.os.arch

Architecture of the host operating system (for example, amd64 or aarch64).

#### [](#cpu)CPU
Field Description

host.cpu.model

Processor model name.

host.cpu.cores.physical

Number of physical CPU cores on the host.

host.cpu.cores.logical

Number of logical CPUs (hardware threads) on the host.

host.cpu.load.user

Percentage of CPU time spent in user space during the sampling interval.

host.cpu.load.system

Percentage of CPU time spent in kernel or system space during the sampling interval.

host.cpu.load.idle

Percentage of idle CPU time during the sampling interval.

host.cpu.load.iowait

(Linux only) Percentage of CPU time spent waiting for input or output operations to complete. High values indicate disk or network I/O bottlenecks rather than CPU saturation.

host.cpu.load.steal

(Linux only) Percentage of CPU time taken by the hypervisor to serve other tenants. High values indicate a noisy-neighbor or over-committed virtualized host.

#### [](#memory)Memory This section reports host physical memory, not the JVM heap.
Field Description

host.memory.total

Total physical RAM on the host.

host.memory.available

Physical RAM currently available.

host.memory.used

Physical RAM currently in use (total minus available).

host.memory.page.size

Memory page size, in bytes.

host.memory.swap.total

Total swap space configured on the host.

host.memory.swap.used

Swap space currently in use. Non-zero swap usage often indicates memory pressure.

host.memory.virtual.max

Maximum virtual memory (RAM plus swap) available.

host.memory.virtual.in.use

Virtual memory currently in use.

#### [](#disk-input-and-output)Disk Input and Output (Linux only) For each physical disk device, the report includes information about the device. The report excludes pseudo-devices such as `loop`, `ram`, and `dm-`, and zero-size devices. A device can show `(stats unavailable)` if the runtime can’t read its per-device counters.
Field Description

model

Disk model.

size

Total size of the disk.

reads / writes

Number of read or write operations the device has served since the runtime started.

read.bytes / write.bytes

Total amount of bytes the device has read or written since the runtime started.

transfer.time.ms

Total time spent on transfers, in milliseconds.

### [](#diaf-jvm-agents)JVM Agents

Available in Mule runtime 4.11.6 and later.

This section lists the JVM agents attached at JVM startup through the `-javaagent`, `-agentpath`, or `-agentlib` arguments. JVM agents can instrument the runtime, intercept class loading, redefine classes, and add overhead. Use this information to identify third-party, APM, and observability agents such as profilers, monitoring, security, and bytecode instrumentation agents, that can affect runtime behavior or interfere with the Mule runtime. The report doesn’t include agents attached dynamically after the JVM starts by using the Attach API. If no agents were attached at startup, the report shows `No JVM agents detected.` instead. Option values that appear to contain secrets, such as license keys, tokens, and passwords, are masked as `******` in both the report and the debug logs. #### [](#java-agents)Java Agents Jar-based agents attached with `-javaagent`. For each agent, the report shows the JAR path, the option string, and metadata read from the JAR’s `META-INF/MANIFEST.MF`. If the JAR is missing or has no usable manifest, the report shows `(no manifest metadata available)`.
Field Description

Path

Absolute path to the agent JAR.

Options

Option string passed to the agent. The report shows (none) if no options are given or (empty) if an empty option string is given. Sensitive values are masked.

Premain-Class

Class with the premain method that runs before the application’s main method, when the agent is attached at startup.

Agent-Class

Class with the agentmain method, used when the agent is attached to a running JVM.

Launcher-Agent-Class

Class used to launch the agent from an executable JAR.

Can-Redefine-Classes

Indicates whether the agent can redefine classes.

Can-Retransform-Classes

Indicates whether the agent can retransform classes.

Can-Set-Native-Method-Prefix

Indicates whether the agent can set a native method prefix.

Boot-Class-Path

Paths the agent adds to the bootstrap class loader search.

Implementation-Title

Title of the agent implementation.

Implementation-Vendor

Vendor of the agent implementation.

Implementation-Version

Version of the agent implementation.

#### [](#native-agents)Native Agents Agents attached through `-agentpath` or `-agentlib` are native libraries, which don’t carry a manifest.
Field Description

Name

Name (for -agentlib) or path (for -agentpath) of the native agent.

Flag

Argument used to attach the agent through -agentpath or -agentlib.

Options

Option string passed to the agent. The report shows (none) if no options are given or (empty) if an empty option string is given. Sensitive values are masked.

File exists

Whether the native library is found on disk. Shown only for agents attached through -agentpath.

### [](#diaf-statistics)Statistics This section shows detailed statistics information about deployed Mule applications and their performance metrics. Metrics reflect the runtime state since the last start or redeployment. They reset after redeployments and don’t capture complete historical data. Note that this information represents a snapshot, or point in time, of the runtime behavior and can differ from the information in the Anypoint Platform usage report, which reflects a period of time. Set the `mule.enable.statistics` system property to collect General Application Metrics and Flow Statistics. #### [](#flow-summary-statistics)Flow Summary Statistics
Field Description

Private Flows Declared

Total number of private flows declared in the application. A private flow doesn’t contain a MessageSource and isn’t used by an APIkit router.

Private Flows Active

Number of private flows that are currently in a started state.

Trigger Flows Declared

Total number of trigger flows declared in the application. A trigger flow contains a MessageSource.

Trigger Flows Active

Number of trigger flows currently in a started state.

API Kit Flows Declared

Total number of APIkit flows declared in the application. An APIkit router uses an APIkit flow, but the flow doesn’t contain a MessageSource.

API Kit Flows Active

Number of APIkit flows currently in a started state.

#### [](#general-application-metrics)General Application Metrics This section shows counter metrics for the application or flow. Counter metrics include cumulative totals and rolling counts for the last 1, 5, 15, and 60 minutes (shown next to the total as `(rolling) 1m: …​ 5m: …​ 15m: …​ 60m: …​`).
Field Description

Events Received

Number of events received by the application or flow.

Events Processed

Number of events processed by the application or flow.

Messages Dispatched

Total number of messages dispatched from message sources within the application.

Execution Errors

Number of execution errors encountered.

Fatal Errors

Number of fatal errors that cause the application to fail or stop processing.

Connection Errors

Number of connection-related errors that occur.

Average Processing Time

Average time (in milliseconds) required to process an event.

Min Processing Time

Minimum time (in milliseconds) required to process an event.

Max Processing Time

Maximum time (in milliseconds) required to process an event.

Total Processing Time

Cumulative time (in milliseconds) spent processing all events.

Processing Time (rolling)

Aggregated processing-time figures for rolling windows of the last 1, 5, 15, and 60 minutes. Each window reports min, max, avg, and count (number of processed events that contributed to the window). When count is 0, min, max, and avg are reported as 0.

#### [](#flow-statistics)Flow Statistics This section shows counter metrics for the flow. Counter metrics include cumulative totals and rolling counts for the last 1, 5, 15, and 60 minutes (shown next to the total as `(rolling) 1m: …​ 5m: …​ 15m: …​ 60m: …​`).
Field Description

Events Received

Total number of events received by the application since it started.

Events Processed

Total number of events successfully processed by the application.

Messages Dispatched

Total number of messages dispatched from message sources within the application.

Execution Errors

Number of execution errors that occur during event processing.

Fatal Errors

Number of fatal errors that cause the application to fail or stop processing.

Connection Errors

Number of connection-related errors that occur.

Average Processing Time

Average time (in milliseconds) required to process an event.

Processing Time (rolling)

Aggregated processing-time figures for rolling windows of the last 1, 5, 15, and 60 minutes. Each window reports min, max, avg, and count (number of processed events that contributed to the window). When count is 0, min, max, and avg are reported as 0.

### [](#diaf-alerts)Alerts This section shows alerts for known Mule runtime issues. The report lists how many times each alert triggers during the last 1, 5, 15, and 60 minutes along with the context of the alert at the time of triggering. Some alerts, like the backpressure alert, trigger multiple times with the same context, so the plugin shows the context once and indicates how many times it happens to avoid flooding the report. Alerts that don’t trigger in any of the time intervals aren’t included in the report.
Field Description

MULE:UNKNOWN error raised

The runtime generated MULE:UNKNOWN errors, which go unhandled. If such an error raises or appears in the app log, it indicates an error in the Mule runtime. The context shows the details of the errors categorized as MULE:UNKNOWN.

Reactor discarded event

A discarded event is one that a component explicitly filters in a flow. This cuts the processing of such an event, causing the execution to hang. The context shows the correlation ID of each discarded event.

Reactor dropped event

A dropped event doesn’t pass to the following component in a flow through a reactor chain and doesn’t complete. Its symptom is that the event is “hanged”. The alert doesn’t show context because the event dump provides the information.

Reactor dropped error

A dropped error doesn’t pass to the corresponding error handler in a flow through a reactor chain, and so doesn’t complete. Its symptom is that the event is “hanged” when an error occurs. The context shows the string representation of each dropped error.

Not consumed stream

A stream that is garbage collected before being completely consumed can provoke leaks on certain conditions (the most common one is connections from a DB connection pool that remain taken until the data is fully read). The context shows the originating location of the components that generated the streams.

Backpressure triggered

Backpressure is the mechanism that rejects incoming events that exceed the current capacity. This happens because of a spike of incoming events or a longer than usual processing time of the flows. A common sign is when backpressure triggers on systems that have a CPU and memory capacity. The context shows the flow or component that exceeded capacity and the reason for backpressure.

XA recovery start error

Triggered if recovery of an XA connection fails to start. The context shows the unique name (including the configuration name) of the connection for which recovery fails.

Async logger ringbuffer full

When a log appender writes logs slower than the log entries are generated, the logger ringbuffer fills up. When full, threads attempting to log either wait for space in the ringbuffer or log synchronously, depending on the configuration. In either case, a thread that shouldn’t block or wait does so, causing performance issues in the Mule runtime. No context is available for this alert because it always means the same, the buffer is full.

Event dispatched after flow stop

If a source dispatches an event after the flow stops, the graceful shutdown period extends unnecessarily. The context shows the connector that owns the flow’s source, and a thread dump helps you identify why the source doesn’t finish stopping.

OTel export queue full

If OpenTelemetry export queues fill up, Mule runtime either drops the exceeding spans and logs or blocks the thread that tries to add them to the export queue until space is available. Dropping these resources results in missing data, while blocking threads can cause performance issues. System logs specify which spans or logs were affected and whether they were dropped or blocked.

The report provides hints about potential issues. For details on a specific alert, query the log. This report isn’t intended to replace the log for detailed analysis.

### [](#diaf-event-dump)Event Dump This section shows a hierarchical listing of in-flight events. For each event hierarchy executing through a flow in Mule has at least one entry in the report. For each child context for the event, a nested entry appears, sorted in a stack order: children on top, parents on bottom. If an event is dropped, the legend `DROPPED` appears next to it.
Field Description

eventId

A unique identifier for the event. For child events, it has the ID of the parent event context as prefix.

runningTime

How long the event has been running. For child events, this time refers to the execution of this child context. The format is “mm:ss”.

eventContextState

  • PENDING: Event has been created but not yet accepted by the flow for processing.

  • EXECUTING: Event is being executing by the flow or executable component, or has finished but the response is still being processed.

  • WAITING_NON_BLOCKING: Event is waiting for a non-blocking operation to complete.

  • RESPONSE_PROCESSED: Event execution is complete and the response is handled.

  • COMPLETE: Same as RESPONSE_PROCESSED, and all child events are RESPONSE_PROCESSED.

  • TERMINATED: After COMPLETE, and all completion callbacks of the context execute.

flowStack

flowStack contains zero-to-many lines, each with this format.

at [componentId]@[componentLocation](https://docs.mulesoft.com/mule-runtime/4.11/[muleFileName]:[muleFileLineNumber]) [timeInLocation] ms

flowStack.componentId

Identifier of the component (for example, http:request).

flowStack.componentLocation

Unique identifier of a component within a Mule application. The first part is the flow or policy name, followed by the index and chains that nests the component.

flowStack.muleFileName

Name of the Mule configuration file that contains the component.

flowStack.muleFileLineNumber

Line number in the Mule configuration file that contains the component.

flowStack.timeInLocation

Duration in milliseconds the event spends at the flowStack entry.

### [](#diaf-schedulers)Schedulers This section shows the status and metrics of schedulers provided by the scheduler service, which the Mule runtime manages internally, not the [source components](https://docs.mulesoft.com/mule-runtime/4.11/scheduler-concept) themselves. For Mule runtime instances with multiple deployed applications, entries are grouped by application.
Field Description

schedulerName

Name assigned to the scheduler when created, showing where in the code it happened.

threadType

Type of tasks the scheduler runs:

  • IO: A task that spends most of its execution waiting for I/O operations to complete.

  • CPU_INTENSIVE: A task that runs longer than 10 milliseconds, with less than 20% of time blocked.

  • CPU_LIGHT: A task that never blocks and runs is less than 10 milliseconds.

  • CUSTOM: Threads that aren’t managed by Mule runtime or shared among schedulers. Used when a thread pool needs exclusive use (for example, NIO selectors).

shutdown

A shutdown scheduler doesn’t accept new tasks. Tasks still running are allowed a graceful period to complete.

terminated

A terminated scheduler is shut down and all in progress tasks are completed or forcefully terminated after a graceful shutdown period.

activeTasks

Number of tasks currently executing by the scheduler.

queuedTasks

Number of tasks waiting in a queue. Not shown if there’s no queue, the queue size can’t be queried, or no tasks are queued.

rejections

Number of tasks rejected because the scheduler is at capacity. Shows rejections in the last 1, 5, 15, and 60 minutes. If there aren’t any in those intervals, the alert isn’t shown.

throttles

Number of tasks throttled because the scheduler is at capacity. Shows throttles in the last 1, 5, 15, and 60 minutes. If there aren’t any in those intervals, the alert isn’t shown.

### [](#diaf-cpu-usage)CPU Usage This section shows the CPU usage for each thread in the Mule runtime process. Use it to identify high CPU consumption that can affect application performance. The data is sorted by current CPU usage to highlight the most active threads.
Field Description

Thread ID

Unique identifier of the thread within the Mule runtime process.

%CPU

Percentage of CPU consumed by the thread during the last three-second sampling interval, calculated like the Linux top command. This metric provides a short-term view of CPU activity instead of a lifetime average.

Thread Name

Name of the thread as reported by the JVM.

State

Current execution state of the thread (for example, RUNNABLE, WAITING, TIMED_WAITING, or BLOCKED).

CPU Time (3s)

Total CPU time the thread consumed during the most recent three-second measurement interval, in milliseconds.

Total CPU Time

Total CPU time the thread has consumed since the Mule runtime process started, in milliseconds.

### [](#diaf-deployments)Deployments This section shows the status and metadata of all artifacts currently deployed in the Mule runtime instance: applications, domains, policy templates, and policies applied to applications. It also shows undeployed artifacts still present in memory, which can indicate possible leaks. #### [](#applications)Applications For each application, the report includes this information:
Field Description

Artifact Name

Name of the application.

Artifact Type

APPLICATION.

State

Current state of the application:

  • INITIAL

  • DEPLOYED

  • STARTED

  • STOPPED

  • UNDEPLOYED

  • FAILED

Domain

Name of the domain the application uses. Shown only if the application uses a non-default domain.

Policies

List of policy IDs applied to the application. Shown only if the application has policies.

Plugins

List of all plugins available in the application’s deployment.

Time since Last State Update

Timestamp of the most recent state update, formatted as yyyy-MM-dd HH:mm:ss.

Feature Flags

List of all enabled feature flags for the application, sorted alphabetically. Shown only for DEPLOYED, STARTED, or STOPPED applications.

#### [](#domains)Domains For each domain (excluding the default domain), the report includes this information:
Field Description

Artifact Name

Name of the domain.

Artifact Type

DOMAIN.

State

Current state of the domain:

  • INITIAL

  • DEPLOYED

  • STARTED

  • STOPPED

  • UNDEPLOYED

  • FAILED

Plugins

List of all plugins available in the domain’s deployment.

Time since Last State Update

Timestamp of the most recent state update, formatted as yyyy-MM-dd HH:mm:ss.

#### [](#policy-templates)Policy Templates Policy templates appear as separate top-level entries. Each entry represents a unique policy template used by one or more applications.
Field Description

Template Name/ID

Name or identifier of the policy template.

Artifact Type

POLICY_TEMPLATE.

Version

Version of the policy template.

Plugins

List of all plugins available in the policy template.

### [](#diaf-connectors-state)Connectors State

Available in Mule runtime 4.11.6 and later.

This section reports the state of each connector configuration in the deployed applications, including the connection lifecycle, connection pool information, recent errors, and TLS details. When more than one application is deployed, the report groups connector configurations by application. If an application isn’t started, the report shows `Application is not started — no artifact context available.`. If an application has no connector configurations, the report shows `No connector configurations found.`. For each connector configuration, the report includes a header with the name, the `Extension` it belongs to, and whether the configuration is `Dynamic` (resolved per event from expressions). The report fields depend on whether the configuration is static or dynamic.
Field Description

Connection Provider

Class name of the resolved connection provider. If the configuration doesn’t declare one, the report shows (configuration does not declare a connection provider).

TLS details

TLS context information for the connection provider, including certificate validity where applicable. The report shows this information only for providers that use TLS.

Connection State

A block of connection statistics for the configuration, shown as (no statistics available) when none have been recorded. When present, the block contains:

  • Last Used: Timestamp of the most recent use of the connection.

  • Active Components: Number of components currently using this configuration.

  • Last Connection Attempt: Timestamp of the most recent connection attempt.

  • Last Successful Conn.: Timestamp of the most recent successful connection.

  • Pool Info: For pooling connection providers, the connection pool state: active, idle, maxTotal, maxIdle, created, borrowed, returned, and destroyed connection counts. An active count at or near maxTotal indicates the pool is saturated.

  • Last Error: Timestamp and details of the most recent connection error, when one has occurred.

Usages

(Static configurations) Component locations that reference this configuration, or (not referenced by any component) / (no usages created yet) if there are none.

Last Resolution Failure

(Dynamic configurations) Timestamp and details of the most recent failure to resolve the dynamic configuration, or Not available if there are none.

Last Successful Creation

(Dynamic configurations) Timestamp of the most recent successful resolution of a configuration instance, or Not available if there are none.

Active Usages

(Dynamic configurations) Currently active resolved instances, each with its own Connection State block, or (no active dynamic usages) if there are none.

### [](#diaf-cluster-info)Cluster Info

This section applies to Enterprise Edition only and is available in Mule runtime 4.11.6 and later.

This section reports the clustering configuration of the local node. When lock diagnostics are enabled, it also reports the distributed locks currently held across the cluster. This section isn’t available in Community Edition or non-clustered runtimes. If the node isn’t part of an active cluster, the report shows `Cluster is not active. No cluster information available.`. #### [](#cluster-configuration)Cluster Configuration The report mirrors the cluster configuration of the local node.
Field Description

clusterId

Identifier of the cluster the node belongs to.

clusterNodeId

Identifier of the local node in the cluster.

clusterSize

Number of nodes currently in the cluster.

clusterSchema

Cluster schema in use.

multicastEnabled

Indicates whether multicast is enabled for cluster discovery.

tcpInboundPort

TCP port the node uses for inbound cluster communication.

nodes

IP addresses of the nodes in the cluster.

networkInterfaces

Network interfaces used for cluster communication.

#### [](#lock-diagnostics)Lock Diagnostics Available only when lock diagnostics are enabled on the runtime. Reports the local member, the number of reporting members, and the distributed locks currently held. For each held lock, the report includes the `lockId` and the lock holder details.
Field Description

holder.nodeId

Node holding the lock, shown as LOCAL or REMOTE.

holder.thread

Name of the thread that holds the lock.

holder.threadId

Identifier of the thread holding the lock.

holder.threadState

State of the holding thread, or n/a for remote nodes.

holder.acquiredAt

Timestamp when the lock was acquired.

holder.heldFor

How long the lock has been held.

holder.callerClass

(When acquisition stack capture is enabled) Class that acquired the lock.

holder.acquireStack

(When acquisition stack capture is enabled) Stack frames captured when the lock was acquired.

hz.isLocked

Hazelcast-level lock state, or hz.state: unavailable if it can’t be queried.

The report also lists orphan locks, which are held locks that have no owning node in any member’s registry, for example, the holding node stopped before releasing the lock. If acquisition stack traces aren’t enabled, the report includes a note explaining how to enable them. ## [](#considerations)Considerations - DIAF provides investigation hints. Check the logs for complete details. - Heap dumps can contain sensitive data. Enable the `--extended` option only in secure environments. - In Mule runtime instances with multiple applications, DIAF sections are grouped by application. - Use DIAF for initial troubleshooting before collecting heap or thread dumps manually. - Correlate events in the event dump section with logs by using the `eventId` for deeper analysis. - Collect scheduled diagnostics during maintenance windows in production environments. - To verify if all the hosts defined in your deployable artifacts (domains, applications, policies) support TLS 1.2 and 1.3 connectivity, enable the `mule.extractConnectionData.enable` system property. On UNIX, the tool generates `_tls_results.csv` along with DIAF output. Enable the `mule.extractConnectionData.silentErrors` system property to log errors without failing deployment. Not available for Windows. ## [](#see-also)See Also - [Known Issues](https://help.salesforce.com/s/issues) # Mule Troubleshooting Plugin Use the Mule Troubleshooting plugin to generate structured diagnostic information, simplify troubleshooting, and provide consistent data for Mule runtime support. The Mule Troubleshooting plugin provides a unified way to collect diagnostic data from Mule runtime environments. It generates a structured diagnostic archive called the Diagnostic Information Analysis File (DIAF), which consolidates Mule runtime information, application metrics, and system data into a single, standardized output. This Java-based plugin provides an extensible, environment-agnostic solution that simplifies troubleshooting for Mule runtime engineers, MuleSoft Support teams, customers running self-service diagnostics, and AI-assisted analysis. ## [](#before-you-begin)Before You Begin Before using the plugin, make sure that you have these prerequisites: - Supported Mule runtime distributions include version 4.10 and later, or LTS versions 4.9 (with patch 4.9.10 or later) and 4.6 (with patch 4.6.23 or later). - Java 8 or later, matching the Mule runtime version requirements. - Access to the `$MULE_HOME` directory. The CLI script `diag` automatically locates the Mule home directory. The plugin works out-of-the-box in the Standalone, CloudHub, and CloudHub 2.0 deployment models without installing additional dependencies. For details about CloudHub 2.0 diagnostics, see [Generating Apps Diagnostics and Analyzing with Einstein](https://docs.mulesoft.com/cloudhub-2/ch2-view-diag). ## [](#using-the-mule-troubleshooting-plugin)Using the Mule Troubleshooting Plugin Run this command from your Mule runtime installation at `$MULE_HOME/tools/diag` to generate the DIAF and a thread dump. By default, the tool saves the files unzipped in the `logs` directory of the distribution. Use the `./diag --extended` command to generate a heap dump. Use `./diag --output some/dir/name/` to create the directories if they don’t exist and save unzipped files there. Use `./diag --output some/dir/name` (without a trailing `/`) to create an archive at that path containing all output files. The tool uses ZIP format when the `zip` command is available and falls back to TAR.GZ otherwise. On Windows, run `diag.bat`. The `--stdout` option isn’t supported. The plugin’s help output lists the available commands and options. ```bash ➜ mule-enterprise-standalone-4.12.3 ./tools/diag help Mule Troubleshooting Tool ========================= Usage: ./diag [options] [command] [command-options] Commands: diaf Generate a complete Mule diagnostic dump (default) help Show this help message Execute a specific troubleshooting operation Global Options: --stdout Output the diagnostic dump to standard output --output Specify custom output directory or file path --extended Enable extended mode (heap dump + file artifacts: conf, logs, server-plugins, apps, domains, policies) --logsmaxage Maximum age in days for logs collected with --extended (default 7, 0 disables) --logsmaxtotalsize Maximum total size in MB for logs collected with --extended (default 100, 0 disables) --debug Enable debug mode with remote debugging on port 5005 Watch Mode (generate dumps automatically when a condition is met): --watch Poll runtime metrics and fire a diagnostic dump when a --trigger condition is met --trigger Trigger condition (repeatable; a dump fires when any one matches). Forms: cpu>N / cpuN / heapN / thread on a Quartz cron schedule (e.g. cron=0 0/5 * * * ?) script= when exits with a non-zero status --occurrences Number of dumps to fire before stopping (default 1; 0 or negative = unlimited) --checkperiod How often to check the triggers, in seconds (default 30; a lower time=N trigger takes precedence) Examples: ./diag # Generate diagnostic dump to logs directory ./diag --stdout # Output diagnostic dump to stdout ./diag --extended # Include heap dump and file artifacts in diagnostic ./diag --output /tmp/mule # Save to specific file (see Archive Format below) ./diag --output /tmp/ # Save to specific directory ./diag # Execute specific operation ./diag --watch --trigger heap>90 # Dump once when heap usage exceeds 90% ./diag --watch --trigger cpu>80 --trigger time=300 --occurrences 0 --checkperiod 10 # Dump every time CPU exceeds 80% or every 300s, checking every 10s, forever ./diag --watch --trigger 'cron=0 0/5 * * * ?' --extended # Extended dump every 5 minutes on a cron schedule Output: The tool creates an archive file containing: - mule_dump_.diaf # Diagnostic information - thread_dump_.txt # Thread dump - heap_dump_.hprof # Heap dump (if --extended is used) - tls_support/ # TLS introspection results (if available) If --extended is used, the following are also included: - conf/, logs/, server-plugins/, apps/, domains/, policies/ # logs/ capped at 100MB / 7 days by default # configurable via --logsmaxtotalsize / --logsmaxage Archive Format: - Uses ZIP format when 'zip' command is available - Falls back to TAR.GZ format when only 'tar' is available ``` ### [](#command-line-options)Command-Line Options The previous output lists every option and its default. These behaviors aren’t mentioned in that summary: - `--output `: when `` is an existing directory or ends with a trailing slash (`/`), the tool writes the individual output files into that directory. Any other `` is treated as the archive to create, with the format taken from the extension (for example, `.zip` or `.tar.gz`). - `--stdout`: streams the archive to standard output instead of writing a file, so you can’t combine it with `--output`. It isn’t supported on Windows. - `--debug`: the JVM listens for a remote debugger on port `5005` and suspends until one attaches, so use it only to troubleshoot the tool itself. #### [](#watch-mode)Watch Mode Watch mode (`--watch`) keeps the tool running and generates a diagnostic dump automatically whenever a `--trigger` condition is met, which is useful for capturing state at the moment an intermittent problem occurs. The `help` output lists the watch options and trigger forms. These behaviors aren’t covered there: - Watch mode runs in the foreground and blocks the terminal until it reaches the number of successful dumps specified by `--occurrences`, or you stop it with `kbd:[Ctrl+C]`. - Watch mode wraps the default full diagnostic dump, so you can’t combine it with a single named operation. You can combine it with `--extended`. - A trigger whose metric can’t be sampled on the current host never fires, so it doesn’t produce false dumps.

Watch mode and the --logsmaxage and --logsmaxtotalsize options are available in Mule runtime 4.12.3 and later.

#### [](#run-a-single-troubleshooting-operation)Run a Single Troubleshooting Operation Use `./diag ` to run only one troubleshooting operation instead of generating the full DIAF. The tool logs the operation result and also saves it to a file named `_.txt`. The `` value is in milliseconds since epoch. A single-operation run doesn’t generate the `mule_dump_.diaf` or `thread_dump_.txt` files. The `--output` option works the same way as it does for the DIAF: - Without `--output`, the tool saves the result file in the `logs` directory of the distribution. - With `--output some/dir/name/` (an existing directory or a path that ends with `/`), the tool saves the result file in that directory. If the directory doesn’t exist, the tool creates it. - With any other `--output` path, the tool creates an archive at that path that contains the result file, using the same ZIP or TAR.GZ format as the DIAF archive. For example, this command runs the `threadDump` operation and saves the result to `/tmp/diag/threadDump_.txt`: ```bash ./diag --output /tmp/diag/ threadDump ``` ## [](#understanding-diagnostic-information-analysis-file-diaf)Understanding Diagnostic Information Analysis File (DIAF) The Diagnostic Information Analysis File (DIAF) organizes all diagnostic data collected by the Mule Troubleshooting plugin into structured sections. Use this reference to understand the content of each section: - [Title](#diaf-title) - [Basic Information](#diaf-basic-info) - [System Info](#diaf-system-info) - [Health Signals](#diaf-health-signals) - [Memory Detail](#diaf-memory-detail) - [Network Info](#diaf-network-info) - [JVM Agents](#diaf-jvm-agents) - [Statistics](#diaf-statistics) - [Alerts](#diaf-alerts) - [Event Dump](#diaf-event-dump) - [Schedulers](#diaf-schedulers) - [CPU Usage](#diaf-cpu-usage) - [Deployments](#diaf-deployments) - [Connectors State](#diaf-connectors-state) - [Cluster Info](#diaf-cluster-info) - [Agent Info](#diaf-agent-info) - [Platform Connectivity](#diaf-platform-connectivity) - [Known Issues](#diaf-known-issues) ### [](#diaf-title)Title This section shows the report generation timestamp.
Field Description

Report Generation Timestamp

The report generation time, expressed in the local time zone.

### [](#diaf-basic-info)Basic Information This section shows details about the environment where the Mule runtime instance is running.

Available in Mule runtime 4.12.1 and later. The JVM resource metrics in this section appear under the JVM Resources block and use the jvm. prefix (for example, jvm.memory.used). In earlier patch versions, these metrics appear at the top level without the prefix (for example, memory.used). The metrics have the same meaning in both formats. Operating system details and the system-wide CPU load no longer appear in this section. See System Info for those metrics.

Field Description

Mule Product/version

Product (CE/EE), version, and build number of the Mule runtime. Formatted as [productName] [version] (build [buildNumber]).

mule_home

Absolute path to MULE_HOME for the Mule runtime.

mule_base

Absolute path to MULE_BASE for the Mule runtime.

mule.* System Properties

All system properties starting with mule., including those defined by DataWeave and API Gateway. Listed with values and sorted alphabetically.

Java Version

Version of the JVM running the Mule runtime.

Java Vendor

Vendor of the JVM running the Mule runtime.

Java VM Name

Full name of the JVM running the Mule runtime.

JAVA_HOME

Location of the JVM running the Mule runtime.

Running Time

Total time the Mule runtime has been running.

PID

Process ID of the JVM running the Mule runtime.

Report Millis Time

Report generation time in milliseconds since epoch (System.currentTimeMillis).

Report Nano Time

Report generation time in nanoseconds (System.nanoTime).

memory.used (jvm.memory.used)

Amount of used memory in the JVM.

memory.free (jvm.memory.free)

Amount of available memory in the JVM.

memory.total (jvm.memory.total)

Total amount of memory in the JVM.

memory.max (jvm.memory.max)

Maximum amount of memory the JVM attempts to use.

memory.used/total (jvm.memory.used/total)

Percentage of used memory compared to the total allocated memory.

memory.used/max (jvm.memory.used/max)

Percentage of used memory compared to the maximum available memory.

processors.available (jvm.processors.available)

Number of processors available to the JVM process.

load.process (jvm.load.process)

Percentage of recent CPU usage for the JVM process; negative value if unavailable.

License

(Enterprise Edition only) License information for Enterprise Edition distributions appears under the License block. This block doesn’t appear in Community Edition or when no Enterprise license is registered. When present, it can include:

  • valid: Indicates whether the license is valid.

  • validationError: Indicates the reason the license is not valid, when applicable.

  • evaluation: Indicates whether the license is an evaluation license.

  • expirationDate: The license expiration date.

  • licenseFile: The license file in use.

  • contact: Contact information, including name, email, telephone, company, and country.

  • entitlements: The list of entitlements granted by the license.

In Mule runtime patches earlier than 4.12.1, this section also reports OS Name, OS Version, OS Arch, load.system, and load.systemAverage. Starting with Mule 4.12.1, the operating system details (host.os.) and the host CPU load (host.cpu.load.) are reported in the System Info section instead.

### [](#diaf-system-info)System Info

Available in Mule runtime 4.12.1 and later.

This section shows host-level diagnostics for the machine, container, or pod where the Mule runtime instance is running. The diagnostics are collected from the host operating system. Unlike [Basic Information](#diaf-basic-info), which reports JVM-level metrics, this section reports host-level information. CPU load percentages are sampled over a short interval. Some fields are only populated on Linux hosts. On other operating systems, these fields can be absent or display `n/a`. If the runtime can’t collect host information, the report shows `Host info not available` instead. #### [](#operating-system)Operating System
Field Description

host.os.name

Name of the host operating system.

host.os.version

Version of the host operating system.

host.os.arch

Architecture of the host operating system (for example, amd64 or aarch64).

#### [](#cpu)CPU
Field Description

host.cpu.model

Processor model name.

host.cpu.cores.physical

Number of physical CPU cores on the host.

host.cpu.cores.logical

Number of logical CPUs (hardware threads) on the host.

host.cpu.load.user

Percentage of CPU time spent in user space during the sampling interval.

host.cpu.load.system

Percentage of CPU time spent in kernel or system space during the sampling interval.

host.cpu.load.idle

Percentage of idle CPU time during the sampling interval.

host.cpu.load.iowait

(Linux only) Percentage of CPU time spent waiting for input or output operations to complete. High values indicate disk or network I/O bottlenecks rather than CPU saturation.

host.cpu.load.steal

(Linux only) Percentage of CPU time taken by the hypervisor to serve other tenants. High values indicate a noisy-neighbor or over-committed virtualized host.

#### [](#memory)Memory This section reports host physical memory, not the JVM heap.
Field Description

host.memory.total

Total physical RAM on the host.

host.memory.available

Physical RAM currently available.

host.memory.used

Physical RAM currently in use (total minus available).

host.memory.page.size

Memory page size, in bytes.

host.memory.swap.total

Total swap space configured on the host.

host.memory.swap.used

Swap space currently in use. Non-zero swap usage often indicates memory pressure.

host.memory.virtual.max

Maximum virtual memory (RAM plus swap) available.

host.memory.virtual.in.use

Virtual memory currently in use.

#### [](#disk-input-and-output)Disk Input and Output (Linux only) For each physical disk device, the report includes information about the device. The report excludes pseudo-devices such as `loop`, `ram`, and `dm-`, and zero-size devices. A device can show `(stats unavailable)` if the runtime can’t read its per-device counters.
Field Description

model

Disk model.

size

Total size of the disk.

reads / writes

Number of read or write operations the device has served since the runtime started.

read.bytes / write.bytes

Total amount of bytes the device has read or written since the runtime started.

transfer.time.ms

Total time spent on transfers, in milliseconds.

### [](#diaf-health-signals)Health Signals

Available in Mule runtime 4.12.3 and later.

This section evaluates a small set of fast host- and JVM-level health signals and reports only the ones that fired. The inputs come from JMX and the host operating system, plus a check for a JVM crash log. No log-file contents are read. On a healthy host, the section shows `None`. Each fired signal is listed on its own line with a short description and, where available, the measured values. These are the possible signals:
Signal Meaning

Low Available Memory

Available physical memory is below 10% of total memory.

No Swap

The host has no swap memory configured, which is a risk on a low-memory host.

Low storage

A mounted file system has less than 10% usable space. Reported per affected mount.

High CPU Steal

CPU steal time is high, which can indicate low CPU credits on the host (Linux only).

High CPU IOWait

CPU I/O wait time is high, which can indicate I/O problems or excessive disk usage (Linux only).

JVM was restarted

The JVM process is much younger than the host, which can indicate an unexpected restart.

JVM crash log present

A JVM fatal-error log (hs_err_pid<PID>.log) is present in the runtime logs directory or the JVM error-file location, indicating a previous JVM crash.

### [](#diaf-memory-detail)Memory Detail

Available in Mule runtime 4.12.3 and later.

This section shows the JVM memory-pool breakdown and garbage-collector statistics of the running Mule runtime, read in-process from JMX. It has four blocks: aggregate `Heap` usage, aggregate `Non-Heap` usage, one entry per memory pool under `Memory Pools`, and one entry per collector under `Garbage Collectors`. The `Heap`, `Non-Heap`, and each `Memory Pools` entry report these usage fields:
Field Description

init

Initial amount of memory the JVM requested for the pool. Shown as n/a when the JVM doesn’t define it.

used

Amount of memory currently in use.

committed

Amount of memory guaranteed to be available to the JVM.

max

Maximum amount of memory that can be used. Shown as n/a for an unbounded pool.

used/committed

Ratio of used to committed memory, as a percentage. Omitted when committed memory isn’t positive.

used/max

Ratio of used to maximum memory, as a percentage. Omitted when maximum memory isn’t defined.

Each `Memory Pools` entry also reports its `type` (`HEAP` or `NON_HEAP`). Each `Garbage Collectors` entry reports:
Field Description

count

Number of collections the collector has performed. Shown as n/a when the collector doesn’t support the counter.

time.ms

Accumulated collection time, in milliseconds. Shown as n/a when the collector doesn’t support the field.

pools

Names of the memory pools the collector manages, separated by |.

### [](#diaf-network-info)Network Info

Available in Mule runtime 4.12.2 and later.

This section shows host-level network diagnostics for the machine, container, or pod where the Mule runtime instance is running: the hostname, the network interfaces with their assigned IP addresses and I/O counters, and the active and listening network connections. Interface counters and connection tables are collected from the host operating system. #### [](#host)Host
Field Description

host.network.hostname

Hostname of the machine running the Mule runtime.

#### [](#interfaces)Interfaces Each network interface is reported under its own name (for example, `eth0:`, `lo:`), including loopback, physical, virtual, and tunnel interfaces. For each interface, the report includes these fields:
Field Description

mtu

Maximum transmission unit of the interface, in bytes.

mac

MAC address of the interface, or None for interfaces that don’t have one (for example, loopback).

flags

Interface flags, such as UP, LOOPBACK, POINTOPOINT, VIRTUAL, and MULTICAST, or None.

addrs

IP addresses (IPv4 and IPv6) assigned to the interface, or None.

bytes.recv / bytes.sent

Cumulative number of bytes received or sent on the interface since the host started. These are raw counters intended for computing rates by comparing two reports.

packets.recv / packets.sent

Cumulative number of packets received or sent on the interface.

errors.in / errors.out

Cumulative number of inbound or outbound errors on the interface.

drops.in

Cumulative number of inbound packets dropped on the interface.

#### [](#connections)Connections The report includes three connection tables, each preceded by its own header. Each connection line has the format `type= state= local=
: foreign=
:`, where `type` is one of `tcp4`, `tcp6`, `udp4`, or `udp6` and `state` is a TCP connection state (for example, `ESTABLISHED`, `LISTEN`, or `TIME_WAIT`). A wildcard address or port is shown as `*`. IPv6 addresses are shown in compressed form and enclosed in brackets (for example, `[::1]:8081`).
Table Description

Connections (Mule pid=<pid>)

Connections owned by the Mule runtime process.

Listening ports

Host-wide sockets in the LISTEN state. Each line also includes the owning pid.

Connections (all, count=<n>)

Full host-wide connection table, with the total count in the header. Each line also includes the owning pid.

### [](#diaf-jvm-agents)JVM Agents

Available in Mule runtime 4.12.1 and later.

This section lists the JVM agents attached at JVM startup through the `-javaagent`, `-agentpath`, or `-agentlib` arguments. JVM agents can instrument the runtime, intercept class loading, redefine classes, and add overhead. Use this information to identify third-party, APM, and observability agents such as profilers, monitoring, security, and bytecode instrumentation agents, that can affect runtime behavior or interfere with the Mule runtime. The report doesn’t include agents attached dynamically after the JVM starts by using the Attach API. If no agents were attached at startup, the report shows `No JVM agents detected.` instead. Option values that appear to contain secrets, such as license keys, tokens, and passwords, are masked as `******` in both the report and the debug logs. #### [](#java-agents)Java Agents Jar-based agents attached with `-javaagent`. For each agent, the report shows the JAR path, the option string, and metadata read from the JAR’s `META-INF/MANIFEST.MF`. If the JAR is missing or has no usable manifest, the report shows `(no manifest metadata available)`.
Field Description

Path

Absolute path to the agent JAR.

Options

Option string passed to the agent. The report shows (none) if no options are given or (empty) if an empty option string is given. Sensitive values are masked.

Premain-Class

Class with the premain method that runs before the application’s main method, when the agent is attached at startup.

Agent-Class

Class with the agentmain method, used when the agent is attached to a running JVM.

Launcher-Agent-Class

Class used to launch the agent from an executable JAR.

Can-Redefine-Classes

Indicates whether the agent can redefine classes.

Can-Retransform-Classes

Indicates whether the agent can retransform classes.

Can-Set-Native-Method-Prefix

Indicates whether the agent can set a native method prefix.

Boot-Class-Path

Paths the agent adds to the bootstrap class loader search.

Implementation-Title

Title of the agent implementation.

Implementation-Vendor

Vendor of the agent implementation.

Implementation-Version

Version of the agent implementation.

#### [](#native-agents)Native Agents Agents attached through `-agentpath` or `-agentlib` are native libraries, which don’t carry a manifest.
Field Description

Name

Name (for -agentlib) or path (for -agentpath) of the native agent.

Flag

Argument used to attach the agent through -agentpath or -agentlib.

Options

Option string passed to the agent. The report shows (none) if no options are given or (empty) if an empty option string is given. Sensitive values are masked.

File exists

Whether the native library is found on disk. Shown only for agents attached through -agentpath.

### [](#diaf-statistics)Statistics This section shows detailed statistics information about deployed Mule applications and their performance metrics. Metrics reflect the runtime state since the last start or redeployment. They reset after redeployments and don’t capture complete historical data. Note that this information represents a snapshot, or point in time, of the runtime behavior and can differ from the information in the Anypoint Platform usage report, which reflects a period of time. Set the `mule.enable.statistics` system property to collect General Application Metrics and Flow Statistics. #### [](#flow-summary-statistics)Flow Summary Statistics
Field Description

Private Flows Declared

Total number of private flows declared in the application. A private flow doesn’t contain a MessageSource and isn’t used by an APIkit router.

Private Flows Active

Number of private flows that are currently in a started state.

Trigger Flows Declared

Total number of trigger flows declared in the application. A trigger flow contains a MessageSource.

Trigger Flows Active

Number of trigger flows currently in a started state.

API Kit Flows Declared

Total number of APIkit flows declared in the application. An APIkit router uses an APIkit flow, but the flow doesn’t contain a MessageSource.

API Kit Flows Active

Number of APIkit flows currently in a started state.

#### [](#general-application-metrics)General Application Metrics This section shows counter metrics for the application or flow. Counter metrics include cumulative totals and rolling counts for the last 1, 5, 15, and 60 minutes (shown next to the total as `(rolling) 1m: …​ 5m: …​ 15m: …​ 60m: …​`).
Field Description

Events Received

Number of events received by the application or flow.

Events Processed

Number of events processed by the application or flow.

Messages Dispatched

Total number of messages dispatched from message sources within the application.

Execution Errors

Number of execution errors encountered.

Fatal Errors

Number of fatal errors that cause the application to fail or stop processing.

Connection Errors

Number of connection-related errors that occur.

Average Processing Time

Average time (in milliseconds) required to process an event.

Min Processing Time

Minimum time (in milliseconds) required to process an event.

Max Processing Time

Maximum time (in milliseconds) required to process an event.

Total Processing Time

Cumulative time (in milliseconds) spent processing all events.

Processing Time (rolling)

Aggregated processing-time figures for rolling windows of the last 1, 5, 15, and 60 minutes. Each window reports min, max, avg, and count (number of processed events that contributed to the window). When count is 0, min, max, and avg are reported as 0.

#### [](#flow-statistics)Flow Statistics This section shows counter metrics for the flow. Counter metrics include cumulative totals and rolling counts for the last 1, 5, 15, and 60 minutes (shown next to the total as `(rolling) 1m: …​ 5m: …​ 15m: …​ 60m: …​`).
Field Description

Events Received

Total number of events received by the application since it started.

Events Processed

Total number of events successfully processed by the application.

Messages Dispatched

Total number of messages dispatched from message sources within the application.

Execution Errors

Number of execution errors that occur during event processing.

Fatal Errors

Number of fatal errors that cause the application to fail or stop processing.

Connection Errors

Number of connection-related errors that occur.

Average Processing Time

Average time (in milliseconds) required to process an event.

Processing Time (rolling)

Aggregated processing-time figures for rolling windows of the last 1, 5, 15, and 60 minutes. Each window reports min, max, avg, and count (number of processed events that contributed to the window). When count is 0, min, max, and avg are reported as 0.

### [](#diaf-alerts)Alerts This section shows alerts for known Mule runtime issues. The report lists how many times each alert triggers during the last 1, 5, 15, and 60 minutes along with the context of the alert at the time of triggering. Some alerts, like the backpressure alert, trigger multiple times with the same context, so the plugin shows the context once and indicates how many times it happens to avoid flooding the report. Alerts that don’t trigger in any of the time intervals aren’t included in the report.
Field Description

MULE:UNKNOWN error raised

The runtime generated MULE:UNKNOWN errors, which go unhandled. If such an error raises or appears in the app log, it indicates an error in the Mule runtime. The context shows the details of the errors categorized as MULE:UNKNOWN.

Reactor discarded event

A discarded event is one that a component explicitly filters in a flow. This cuts the processing of such an event, causing the execution to hang. The context shows the correlation ID of each discarded event.

Reactor dropped event

A dropped event doesn’t pass to the following component in a flow through a reactor chain and doesn’t complete. Its symptom is that the event is “hanged”. The alert doesn’t show context because the event dump provides the information.

Reactor dropped error

A dropped error doesn’t pass to the corresponding error handler in a flow through a reactor chain, and so doesn’t complete. Its symptom is that the event is “hanged” when an error occurs. The context shows the string representation of each dropped error.

Not consumed stream

A stream that is garbage collected before being completely consumed can provoke leaks on certain conditions (the most common one is connections from a DB connection pool that remain taken until the data is fully read). The context shows the originating location of the components that generated the streams.

Backpressure triggered

Backpressure is the mechanism that rejects incoming events that exceed the current capacity. This happens because of a spike of incoming events or a longer than usual processing time of the flows. A common sign is when backpressure triggers on systems that have a CPU and memory capacity. The context shows the flow or component that exceeded capacity and the reason for backpressure.

XA recovery start error

Triggered if recovery of an XA connection fails to start. The context shows the unique name (including the configuration name) of the connection for which recovery fails.

Async logger ringbuffer full

When a log appender writes logs slower than the log entries are generated, the logger ringbuffer fills up. When full, threads attempting to log either wait for space in the ringbuffer or log synchronously, depending on the configuration. In either case, a thread that shouldn’t block or wait does so, causing performance issues in the Mule runtime. No context is available for this alert because it always means the same, the buffer is full.

Event dispatched after flow stop

If a source dispatches an event after the flow stops, the graceful shutdown period extends unnecessarily. The context shows the connector that owns the flow’s source, and a thread dump helps you identify why the source doesn’t finish stopping.

OTel export queue full

If OpenTelemetry export queues fill up, Mule runtime either drops the exceeding spans and logs or blocks the thread that tries to add them to the export queue until space is available. Dropping these resources results in missing data, while blocking threads can cause performance issues. System logs specify which spans or logs were affected and whether they were dropped or blocked.

The report provides hints about potential issues. For details on a specific alert, query the log. This report isn’t intended to replace the log for detailed analysis.

### [](#diaf-event-dump)Event Dump This section shows a hierarchical listing of in-flight events. For each event hierarchy executing through a flow in Mule has at least one entry in the report. For each child context for the event, a nested entry appears, sorted in a stack order: children on top, parents on bottom. If an event is dropped, the legend `DROPPED` appears next to it.
Field Description

eventId

A unique identifier for the event. For child events, it has the ID of the parent event context as prefix.

runningTime

How long the event has been running. For child events, this time refers to the execution of this child context. The format is “mm:ss”.

eventContextState

  • PENDING: Event has been created but not yet accepted by the flow for processing.

  • EXECUTING: Event is being executing by the flow or executable component, or has finished but the response is still being processed.

  • WAITING_NON_BLOCKING: Event is waiting for a non-blocking operation to complete.

  • RESPONSE_PROCESSED: Event execution is complete and the response is handled.

  • COMPLETE: Same as RESPONSE_PROCESSED, and all child events are RESPONSE_PROCESSED.

  • TERMINATED: After COMPLETE, and all completion callbacks of the context execute.

flowStack

flowStack contains zero-to-many lines, each with this format.

at [componentId]@[componentLocation](https://docs.mulesoft.com/mule-runtime/4.12/[muleFileName]:[muleFileLineNumber]) [timeInLocation] ms

flowStack.componentId

Identifier of the component (for example, http:request).

flowStack.componentLocation

Unique identifier of a component within a Mule application. The first part is the flow or policy name, followed by the index and chains that nests the component.

flowStack.muleFileName

Name of the Mule configuration file that contains the component.

flowStack.muleFileLineNumber

Line number in the Mule configuration file that contains the component.

flowStack.timeInLocation

Duration in milliseconds the event spends at the flowStack entry.

### [](#diaf-schedulers)Schedulers This section shows the status and metrics of schedulers provided by the scheduler service, which the Mule runtime manages internally, not the [source components](https://docs.mulesoft.com/mule-runtime/4.12/scheduler-concept) themselves. For Mule runtime instances with multiple deployed applications, entries are grouped by application.
Field Description

schedulerName

Name assigned to the scheduler when created, showing where in the code it happened.

threadType

Type of tasks the scheduler runs:

  • IO: A task that spends most of its execution waiting for I/O operations to complete.

  • CPU_INTENSIVE: A task that runs longer than 10 milliseconds, with less than 20% of time blocked.

  • CPU_LIGHT: A task that never blocks and runs is less than 10 milliseconds.

  • CUSTOM: Threads that aren’t managed by Mule runtime or shared among schedulers. Used when a thread pool needs exclusive use (for example, NIO selectors).

shutdown

A shutdown scheduler doesn’t accept new tasks. Tasks still running are allowed a graceful period to complete.

terminated

A terminated scheduler is shut down and all in progress tasks are completed or forcefully terminated after a graceful shutdown period.

activeTasks

Number of tasks currently executing by the scheduler.

queuedTasks

Number of tasks waiting in a queue. Not shown if there’s no queue, the queue size can’t be queried, or no tasks are queued.

rejections

Number of tasks rejected because the scheduler is at capacity. Shows rejections in the last 1, 5, 15, and 60 minutes. If there aren’t any in those intervals, the alert isn’t shown.

throttles

Number of tasks throttled because the scheduler is at capacity. Shows throttles in the last 1, 5, 15, and 60 minutes. If there aren’t any in those intervals, the alert isn’t shown.

### [](#diaf-cpu-usage)CPU Usage This section shows the CPU usage for each thread in the Mule runtime process. Use it to identify high CPU consumption that can affect application performance. The data is sorted by current CPU usage to highlight the most active threads.
Field Description

Thread ID

Unique identifier of the thread within the Mule runtime process.

%CPU

Percentage of CPU consumed by the thread during the last three-second sampling interval, calculated like the Linux top command. This metric provides a short-term view of CPU activity instead of a lifetime average.

Thread Name

Name of the thread as reported by the JVM.

State

Current execution state of the thread (for example, RUNNABLE, WAITING, TIMED_WAITING, or BLOCKED).

CPU Time (3s)

Total CPU time the thread consumed during the most recent three-second measurement interval, in milliseconds.

Total CPU Time

Total CPU time the thread has consumed since the Mule runtime process started, in milliseconds.

### [](#diaf-deployments)Deployments This section shows the status and metadata of all artifacts currently deployed in the Mule runtime instance: applications, domains, policy templates, and policies applied to applications. It also shows undeployed artifacts still present in memory, which can indicate possible leaks. #### [](#applications)Applications For each application, the report includes this information:
Field Description

Artifact Name

Name of the application.

Artifact Type

APPLICATION.

State

Current state of the application:

  • INITIAL

  • DEPLOYED

  • STARTED

  • STOPPED

  • UNDEPLOYED

  • FAILED

Domain

Name of the domain the application uses. Shown only if the application uses a non-default domain.

Policies

List of policy IDs applied to the application. Shown only if the application has policies.

Plugins

List of all plugins available in the application’s deployment.

Time since Last State Update

Timestamp of the most recent state update, formatted as yyyy-MM-dd HH:mm:ss.

Feature Flags

List of all enabled feature flags for the application, sorted alphabetically. Shown only for DEPLOYED, STARTED, or STOPPED applications.

#### [](#domains)Domains For each domain (excluding the default domain), the report includes this information:
Field Description

Artifact Name

Name of the domain.

Artifact Type

DOMAIN.

State

Current state of the domain:

  • INITIAL

  • DEPLOYED

  • STARTED

  • STOPPED

  • UNDEPLOYED

  • FAILED

Plugins

List of all plugins available in the domain’s deployment.

Time since Last State Update

Timestamp of the most recent state update, formatted as yyyy-MM-dd HH:mm:ss.

#### [](#policy-templates)Policy Templates Policy templates appear as separate top-level entries. Each entry represents a unique policy template used by one or more applications.
Field Description

Template Name/ID

Name or identifier of the policy template.

Artifact Type

POLICY_TEMPLATE.

Version

Version of the policy template.

Plugins

List of all plugins available in the policy template.

### [](#diaf-connectors-state)Connectors State

Available in Mule runtime 4.12.1 and later.

This section reports the state of each connector configuration in the deployed applications, including the connection lifecycle, connection pool information, recent errors, and TLS details. When more than one application is deployed, the report groups connector configurations by application. If an application isn’t started, the report shows `Application is not started — no artifact context available.`. If an application has no connector configurations, the report shows `No connector configurations found.`. For each connector configuration, the report includes a header with the name, the `Extension` it belongs to, and whether the configuration is `Dynamic` (resolved per event from expressions). The report fields depend on whether the configuration is static or dynamic.
Field Description

Connection Provider

Class name of the resolved connection provider. If the configuration doesn’t declare one, the report shows (configuration does not declare a connection provider).

TLS details

TLS context information for the connection provider, including certificate validity where applicable. The report shows this information only for providers that use TLS.

Connection State

A block of connection statistics for the configuration, shown as (no statistics available) when none have been recorded. When present, the block contains:

  • Last Used: Timestamp of the most recent use of the connection.

  • Active Components: Number of components currently using this configuration.

  • Last Connection Attempt: Timestamp of the most recent connection attempt.

  • Last Successful Conn.: Timestamp of the most recent successful connection.

  • Pool Info: For pooling connection providers, the connection pool state: active, idle, maxTotal, maxIdle, created, borrowed, returned, and destroyed connection counts. An active count at or near maxTotal indicates the pool is saturated.

  • Last Error: Timestamp and details of the most recent connection error, when one has occurred.

Usages

(Static configurations) Component locations that reference this configuration, or (not referenced by any component) / (no usages created yet) if there are none.

Last Resolution Failure

(Dynamic configurations) Timestamp and details of the most recent failure to resolve the dynamic configuration, or Not available if there are none.

Last Successful Creation

(Dynamic configurations) Timestamp of the most recent successful resolution of a configuration instance, or Not available if there are none.

Active Usages

(Dynamic configurations) Currently active resolved instances, each with its own Connection State block, or (no active dynamic usages) if there are none.

### [](#diaf-cluster-info)Cluster Info

This section applies to Enterprise Edition only and is available in Mule runtime 4.12.1 and later.

This section reports the clustering configuration of the local node. When lock diagnostics are enabled, it also reports the distributed locks currently held across the cluster. This section isn’t available in Community Edition or non-clustered runtimes. If the node isn’t part of an active cluster, the report shows `Cluster is not active. No cluster information available.`. #### [](#cluster-configuration)Cluster Configuration The report mirrors the cluster configuration of the local node.
Field Description

clusterId

Identifier of the cluster the node belongs to.

clusterNodeId

Identifier of the local node in the cluster.

clusterSize

Number of nodes currently in the cluster.

clusterSchema

Cluster schema in use.

multicastEnabled

Indicates whether multicast is enabled for cluster discovery.

tcpInboundPort

TCP port the node uses for inbound cluster communication.

nodes

IP addresses of the nodes in the cluster.

networkInterfaces

Network interfaces used for cluster communication.

#### [](#lock-diagnostics)Lock Diagnostics Available only when lock diagnostics are enabled on the runtime. Reports the local member, the number of reporting members, and the distributed locks currently held. For each held lock, the report includes the `lockId` and the lock holder details.
Field Description

holder.nodeId

Node holding the lock, shown as LOCAL or REMOTE.

holder.thread

Name of the thread that holds the lock.

holder.threadId

Identifier of the thread holding the lock.

holder.threadState

State of the holding thread, or n/a for remote nodes.

holder.acquiredAt

Timestamp when the lock was acquired.

holder.heldFor

How long the lock has been held.

holder.callerClass

(When acquisition stack capture is enabled) Class that acquired the lock.

holder.acquireStack

(When acquisition stack capture is enabled) Stack frames captured when the lock was acquired.

hz.isLocked

Hazelcast-level lock state, or hz.state: unavailable if it can’t be queried.

The report also lists orphan locks, which are held locks that have no owning node in any member’s registry, for example, the holding node stopped before releasing the lock. If acquisition stack traces aren’t enabled, the report includes a note explaining how to enable them. ### [](#diaf-agent-info)Agent Info

Available in Mule runtime 4.12.2 and later. This section is available only in Enterprise Edition runtimes that have the Mule agent installed.

The Agent Info section reports the installation and health of the Mule agent that pairs this runtime with Anypoint Platform: whether the agent is installed, its version, key configuration values, keystore certificate details, and the most recent connection status. Use it to diagnose agent pairing and platform-connectivity issues. The first line reports whether the agent is installed:
Field Description

installed

true if the Mule agent plugin is present, or false if it isn’t. When false, the report shows a message directing you to run ./bin/amc_setup to install and pair the runtime, and no further fields are reported.

version

Version of the installed agent, read from the mule-agent-api JAR file name, or n/a if it can’t be determined.

#### [](#configuration)Configuration Key values read from the agent descriptor file (`conf/mule-agent.yml`). If the file isn’t present, the report shows a note indicating the agent hasn’t been configured. Fields that can’t be read are shown as `n/a`.
Field Description

websocket.enabled

Whether the WebSocket transport is enabled.

websocket.consoleUri

WebSocket connection URI to Anypoint Platform.

rest.enabled

Whether the REST transport is enabled.

rest.port

Port configured for the REST transport.

#### [](#keystore)Keystore Certificate details read from the agent keystore (`conf/mule-agent.jks`). If the file isn’t present, can’t be loaded, or has no certificates, the report shows a note describing which of those cases applies. Otherwise, the report shows one entry per certificate.
Field Description

alias

Alias of the certificate entry in the keystore.

subjectDN

Subject distinguished name of the certificate.

issuerDN

Issuer distinguished name of the certificate.

validFrom

Date from which the certificate is valid.

validUntil

Date until which the certificate is valid.

validity

Current validity status of the certificate: valid (with days until expiry), expired, or not yet valid.

#### [](#connectivity)Connectivity Connection status derived from the certificate and the agent log file (`logs/mule-agent.log`). If the log file isn’t present, the report notes that the connection history is unavailable.
Field Description

serverId

Server ID that identifies this runtime to Anypoint Platform, read from the common name of the agent certificate, or n/a if it can’t be determined.

log

Path to the agent log file inspected for connection events.

status

Latest connection status found in the log: CONNECTED, DISCONNECTED, DELETED (the runtime was deleted from the platform), or UNKNOWN if no connection events are found.

lastSuccessfulConnection

Timestamp of the most recent successful connection to the platform, or n/a if none is found.

recentHistory

The most recent connection events, each shown as a timestamp and status, up to the last five events.

### [](#diaf-platform-connectivity)Platform Connectivity

Available in Mule runtime 4.12.2 and later. This operation runs on demand only. Because it performs outbound network connections, it isn’t included in the default diagnostic dump. Run it explicitly by name with ./diag platformConnectivity.

This operation checks TCP connectivity from the Mule runtime host to the Anypoint Platform endpoints and dumps the TLS certificate chain presented by the platform. Use it to diagnose connectivity or TLS issues between a runtime and the control, data, and monitoring planes. The report has two subsections. #### [](#connectivity-2)Connectivity For each endpoint, the operation resolves the host and attempts a TCP connection, reporting one line per endpoint. The operation probes a fixed list of US, EU, and monitoring-plane endpoints, plus any endpoints derived from this runtime’s `anypoint.platform.base_uri` and `anypoint.platform.analytics_base_uri` configuration. Endpoints that share the same host and port are probed only once. A reachable endpoint is reported as: ```text OK plane=