Friday, September 2, 2011

Input validation of data services

Input validation is a new feature included in the latest version of WSO2 Data Services Server (WSO2 DSS). With this, the further processing of a data service request message can be stopped at the service layer without reaching the backend data source based on a pre-defined input validation logic.
This is achieved either using a set of built in validators or custom validator implemented by the service author.

There are four different built-in validators.

1. Long range validator
This can be used to validate an integer input parameter value as follows.

<param name="id" paramType="SCALAR" sqlType="INTEGER" type="IN" ordinal="1">
<validateLongRange minimum="1" maximum="40" />

2. Double range validator
This is useful when a validity of a float value has to be checked.

<param name="distance" paramType="SCALAR" sqlType="DOUBLE" type="IN" ordinal="2">
<validateDoubleRange minimum="1.5" maximum="850.45" />

3. Length validator
This can be used to check whether the input parameter value conform to the speficied string length.

<param name="name" paramType="SCALAR" sqlType="STRING" type="IN" ordinal="3">
<validateLength minimum="2" maximum="20" />

4. Pattern validator
This validates the string value of the input parameter against a given regular expression.

<param name="indexno" paramType="SCALAR" sqlType="STRING" type="IN" ordinal="4">
<validatePattern pattern="(?:[a-z0-9]" />

Finally, you can write your own validator based on your requirements and use it in the data service query definition. In order to do that, you must implementorg.wso2.carbon.dataservices.core.validation.Validator interface in your custom validator class as follows.

import org.wso2.carbon.dataservices.core.validation.Validator;
import org.wso2.carbon.dataservices.core.validation.ValidationContext;
import org.wso2.carbon.dataservices.core.validation.ValidationException;
import org.wso2.carbon.dataservices.core.engine.ParamValue;

public class MyCustomValidator implements Validator {
public void validate(ValidationContext validationContext, String s, ParamValue paramValue)
throws ValidationException {
if (!paramValue.getScalarValue().startsWith("2")) {
throw new ValidationException("Not starting with 2!!",s,paramValue);


Then, you can build a jar with the custom validator class and place it in CARBON_HOME/repository/components/lib directory. After restarting the server, you can use it inside query definition as follows.

<param name="id" paramType="SCALAR" sqlType="STRING" type="IN" ordinal="1">
<validateCustom class="org.test.MyCustomValidator" />

No comments:

Post a Comment