Custom Policy in Mule 4

DZone 's Guide to

Custom Policy in Mule 4

In this article, explore custom policies in Mule 4.

· Integration Zone ·
Free Resource

Two donkeys

Custom Policy in Mule 4

Mule 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:

It adds the Maven archetype required to create the project structure for custom policy application(s). To create the project, run the following command:
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

The project structure created will be as follows:
custom-policy#Project Name. Corresponds to the artifactID given in maven command
  --custom-policy.yaml#same as project name

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.

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

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

Configurable properties can be of different types like
  • 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

<logger message="Started Policy execution" /><!--Logger 1 -->
<http-policy:execute-next />
<logger message="Completed Policy execution" />      <!--Logger 2 -->

Logger 1 will be executed before the application flow is called by http-policy:execute-next element. Once the flow completes, logger 2 will be executed before the response is returned to the client.
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.

<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 -->
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.

<logger message="Started Policy execution" />
<raise-error type="ANY" description="Raised error" />
<http-policy:execute-next />
<logger message="Completed Policy execution" />
<logger message="Caught Error" />

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!" />

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, run mvn deploy from the project directory. To upload a newer version of policy, change the version in pom and upload.

Further Reading

Creating Custom Policies in MuleSoft

Custom Policy Creation in Mule 4: Part 1

api manager, custom policy, intergration, mule 4, tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}