DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • JavaFX Goes Mobile
  • Building and Deploying Microservices With Spring Boot and Docker
  • Security Challenges for Microservice Applications in Multi-Cloud Environments
  • Conditional Breakpoints: A Guide to Effective Debugging
  1. DZone
  2. Coding
  3. Java
  4. Custom Policy in Mule 4

Custom Policy in Mule 4

In this article, explore custom policies in Mule 4.

Abhay Yadav user avatar by
Abhay Yadav
·
Dec. 03, 19 · Tutorial
Like (6)
Save
Tweet
Share
10.19K Views

Join the DZone community and get the full member experience.

Join For Free

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


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


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

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


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.


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

Flow (web browser) application Element Upload Payload (computing) Implementation Execution (computing) Blocks Apache Maven

Opinions expressed by DZone contributors are their own.

Trending

  • JavaFX Goes Mobile
  • Building and Deploying Microservices With Spring Boot and Docker
  • Security Challenges for Microservice Applications in Multi-Cloud Environments
  • Conditional Breakpoints: A Guide to Effective Debugging

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: