Custom Policy in Mule 4
In this article, explore custom policies in Mule 4.
Join the DZone community and get the full member experience.
Join For FreeMule provides a set of policies beforehand, but there might be a requirement that is not covered by predefined policies. In such cases, a custom policy can be developed. The process is a three-step workflow:
- Developing the policy
- Deploying/Uploading the policy to exchange
- Applying the policy on API
You might also like: Working With Custom Policy in Mule 4
Setting up and Creating the Project
Before diving into the development, setup Maven to create the required project structure.In settings.xml , under the profiles section, add the below profile:
<profile>
<id>archetype-repository</id>
<repositories>
<repository>
<id>archetype</id>
<name>MuleRepository</name>
<url>https://repository-master.mulesoft.org/nexus/content/repositories/public</url>
<releases>
<enabled>true</enabled>
<checksumPolicy>fail</checksumPolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<checksumPolicy>warn</checksumPolicy>
</snapshots>
</repository>
</repositories>
</profile>
mvn -Parchetype-repository archetype:generate -DarchetypeGroupId=org.mule.tools -DarchetypeArtifactId=api-gateway-custom-policy-archetype -DarchetypeVersion=1.1.0 -DgroupId=<Anypoint orgId> -DartifactId=<policyName> -Dversion=<version> -Dpackage=mule-policy
custom-policy#Project Name. Corresponds to the artifactID given in maven command
--src
--main
--mule
template.xml
--custom-policy.yaml#same as project name
--mule-artifact.json
--pom.xml
File | Description |
---|---|
template.xml | Defines the policy implementation logic. |
custom-policy.yaml | Defines the policy metadata and configurable parameters. Used to render the UI. |
pom.xml | Contains the plugins, dependencies required by the project. Defines the distributionManagement element telling maven where to upload the JAR. |
mule-artifact.json | Describes the app, configuration settings, the required Mule version, and the class loader configuration. |
To upload the application to the exchange, add the Exchange credentials in settings.xml
<server>
<id>exchange-server</id>
<username>username</username>
<password>password</password>
</server>
Developing the Policy
YAML Configuration File
A YAML configuration file is used to store policy metadata and user parameters.
id: Custom Policy ID#Policy ID
name: Custom Policy#Policy Name displayed on API Manager's UI
description: Testing Custom Policy#Policy Description to be shown on API Manager's UI
category: Custom#Policy Category, used to filter policies
type: custom
resourceLevelSupported: true#Whether the policy can be applied at resource level also
encryptionSupported: false
standalone: true#Mandatory to set to true
requiredCharacteristics: []#Deprecated. Leave default value
providedCharacteristics: []#Deprecated. Leave default value
configuration:#Contains array of Policy Parameters to be provided by user when applying policy.
- propertyName: StringProperty#Unique name of property
name: String Property#Name to be displayed on API Manager's UI
description: Property Description#Description of the property. Displayed on API Manager's UI
type: string#Property Type
optional: true#Whether property is mandatory or not
defaultValue: This is default#Default value to be used when no value is provided by user
sensitive: false#Whether the property will be masked in the UI or not
allowMultiple: true#If multiple values are supported or not
- Expression A Dataweave expression
- propertyName: ExpressionProperty name: Expression Property description: Property Description type: expression optional: true sensitive: false
- Boolean
- propertyName: BooleanProperty name: Boolean Property description: Property Description type: boolean optional: true defaultValue: true allowMultiple: false
- Radio Button
- propertyName: RadioButtons name: Radio Buttons description: Property Description type: radio options:#Defines radio button group - name: Option1 value: Option1 value - name: Option2 value: Option2 value optional: true sensitive: false
- Integer
- propertyName: IntProperty name: Int Property description: Property Description type: int minimumValue: 10#Minimum value of the property maximumValue: 20#Maximum value of the property optional: true sensitive: false allowMultiple: false
Implementation File
This file contains the logic/instructions to execute the policy. The policy definition starts with http:policy-proxy element and it can have 2 child elements.- http-policy:source This block can be called as inbound policies block, as it contains instructions for the policy to execute before the flow starts and after the flow finishes.
- http-policy:operation The instructions defined in this block applies to any HTTP Requester within the flow.
Anatomy of http-policy:source element
<http-policy:source>
<logger message="Started Policy execution" /><!--Logger 1 -->
<http-policy:execute-next />
<logger message="Completed Policy execution" /> <!--Logger 2 -->
</http-policy:source>
The execution order is Logger 1 > Flow > Logger 2
Error Handling
A policy implementation can have its own error handler. The concepts and error flow will be the same as in an application. Consider the below scenario where Policy throws an exception before the application is called.<http-policy:source>
<logger message="Started Policy execution" /><!--Logger 1 -->
<raise-error type="ANY" description="Raised error" />
<http-policy:execute-next />
<logger message="Completed Policy execution" /> <!--Logger 2 -->
</http-policy:source>
Logger 1 is executed and then the error is raised. Since there is no error handler, the default handler will be called and the execution stops.
The execution order is Logger 1 > Error >Default error handler or Policy Error Handler (if configured)
Policy implementation With Error Handler
Error handler element(s) should be child of try element, otherwise, Mule will throw an exception when applying the policy.
<http-policy:source>
<try>
<logger message="Started Policy execution" />
<raise-error type="ANY" description="Raised error" />
<http-policy:execute-next />
<logger message="Completed Policy execution" />
<error-handler>
<on-error-continue>
<logger message="Caught Error" />
</on-error-continue>
</error-handler>
</try>
</http-policy:source>
Payload Propagation
Payload is propagated differently by http-policy:source and http-policy:operation, depending on if payload is changed before or after http-policy:execute-next.
In http-policy:source, if payload is changed before http-policy:execute-next, changes will not be propagated to the application. But if changed after http-policy:execute-next, the changes will be propagated. However, changes to the payload before http-policy:execute-next can be propagated to the flow by setting propagateMessageTransformations attribute to true.
<http-policy:source propagateMessageTransformations="true">
<logger message="Started Policy execution" /> <!--Logger 1 -->
<set-payload value="Hello World!" />
<http-policy:execute-next />
<logger message="Completed Policy execution" /> <!--Logger 2 -->
<set-payload value="Bye World!" />
</http-policy:source>
Accessing the Configurable Parameters
The configurable parameters can be accessed in XML using handlebars {{{}}}. Consider the below configurable parameter:
- propertyName: ExpressionProperty
name: Expression Property
description: Property Description
type: expression
optional: true
sensitive: false
It can be accessed in XML using the propertyName within handlebars, {{{ExpressionProperty}}}.
Uploading the Policy to Exchange
To upload the policy to exchange, runmvn deploy
from the project directory. To upload a newer version of policy, change the version in pom and upload.
Further Reading
Opinions expressed by DZone contributors are their own.
Comments