Custom Filter in Mule
Consider an example of a user-implemented custom filter. The minimum configuration needed is related to the particular class where filter is being implemented. With Use of a Custom filter to reference a user-applied filter. Note that the reference is to a class implementing the Filter interface. The Filter Class is essential if this has been a global filter.
In custom filter we can perform any filtering operation by writing any custom java code.Here in our example i have written a simple java code for email validation.
Configuration of custom filter :
we need to give path of Custom java class
A custom java class is written in src/main/java for email validation
package test_customfilter;
import org.mule.api.MuleMessage;
import org.mule.api.routing.filter.Filter;
public class CustomFilter implements Filter {
/**
* This class implements a custom Mule filter.
*/
@Override
public boolean accept(MuleMessage input) {
boolean msgValidated = false;
try {
String payloadStr = input.getPayloadAsString();
if (payloadStr != null && (payloadStr.trim().length() > 0)) {
if (payloadStr.contains("@")) {
msgValidated = true;
} else
return false;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
msgValidated = false;
}
return msgValidated;
}
}
URL : http://localhost:8085/api/customfilter
Input :
Output :
XML project code :
<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd">
<http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8085" basePath="/api" doc:name="HTTP Listener Configuration"/>
<flow name="test_customfilterFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/customfilter" doc:name="HTTP"/>
<object-to-string-transformer doc:name="Object to String"/>
<custom-filter class="test_customfilter.CustomFilter" doc:name="Custom"/>
<set-payload value="#[payload]" doc:name="Set Payload"/>
</flow>
</mule>