Customizing
Although the validation framework provides all constraints from the JSR 303 specification, sometimes other constraint types may be needed. This chapter presents how to create a custom constraint type.
Creating Constraint Types
See the examples of how to create constraint types, including parameterized constraints.
New constraint types can be defined in the <extension_name>-items.xml file in your extension. You may decide which basic classes the new constraint types should extend:
-
AttributeConstraint: If you wish to add constraints to a specified attribute.
-
TypeConstraint: If you wish to add constraints to a type (a group of attributes).
Custom constraint type creation consists of the following steps:
-
Define a constraint type in the <extension_name> -items.xml file in your extension.
-
Create an annotation class that links the constraint type with a constraint validator.
-
Create the constraint validator class with a custom validation logic.
-
Add a constraint violation message template to the resources/ <extension_name> /ValidationMessages.properties file.
Example of Simple Constraint
Learn how to create a simple NotEmptyConstraint, which not only checks if a string is null, but also whether a validated string is not empty.
Constraint Type Definition
First it is necessary to create the constraint type definition in the <extension_name> -items.xml file. The definition consists of:
-
code property: The constraint name
-
extends property: A base type name
-
jaloclass property: The name of the Jalo item class (gets generated at first build).
-
annotation attribute with defaultValue property set to the name of the annotation class. Annotation is a link between the constraint type and a constraint validator that is used to validate data. To get more information about how to create an annotation, see the Annotation section. The constraint validator contains code that is executed when a constrained field or type is being validated.
items.xml
<itemtype code="NotEmptyConstraint" autocreate="true" generate="true"
extends="AttributeConstraint"
jaloclass="<YourPackage>.NotEmptyConstraint">
<description>Custom constraint which checks for empty strings
(Apache commons implementation)</description>
<attributes>
<attribute qualifier="annotation" type="java.lang.Class"
redeclare="true">
<modifiers write="false" initial="true" optional="false"/>
<defaultvalue>
<YourPackage>.NotEmpty.class
</defaultvalue>
</attribute>
</attributes>
</itemtype>
Annotation
The next step is to create an annotation class to link the created constraint type with the constraint validator. The annotation class presented below may be used as a template for creating annotations. An annotation type is defined using the @interface keyword. All attributes of an annotation type are declared in a method-like manner. The JSR 303 specification demands, that any constraint annotation defines:
-
The message attribute: Returns the default key for creating error messages if the constraint is violated.
-
The groups attribute: Allows the specification of validation groups, to which this constraint belongs. The default value is an empty array of type Class<?>.
-
The payload attribute: Can be used to assign custom payload objects to a constraint. This attribute is not used by the API itself.
Moreover, there are some rules that should be obeyed:
-
The value of @Target annotation should be set to FIELD when creating the AttributeConstraint.
-
The value of @Target annotation should be set to TYPE when creating the TypeConstraint.
-
The default value of message() method should be set to key from the resources/ <extension_name> /ValidationMessages.properties file of your extension.
NotEmpty.java
@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = NotEmptyValidator.class)
@Documented
public @interface NotEmpty
{
String message() default "{<YourPackage>.NotEmpty.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Constraint Validator
The constraint validator contains the validation logic. Its isValid method inherited from the ConstraintValidator interface from the JSR 303 specification is invoked whenever a Model containing constrained value is validated. Constraint validator definition consists of the annotation class, in our case NotEmpty, and a class of attribute being validated, in that case String. The same class is used in isValid method.
NotEmptyValidator.java
public class NotEmptyValidator implements ConstraintValidator<NotEmpty, String>
{
@Override
public void initialize(final NotEmpty constraintAnnotation)
{
// empty
}
@Override
public boolean isValid(final String value,
final ConstraintValidatorContext context)
{
return !StringUtils.isEmpty(value);
}
}
Error Message
Insert an error message to the resources/ <extension_name> /ValidationMessages.properties file of your extension. It is displayed by default for every instance of a constraint type. There is also a possibility to override this message, but it should be done for each instance separately. The common practice is to use a fully qualified class name with .message suffix as a default value.
ValidationMessages.properties
<YourPackage>.NotEmpty.message='{type}.{field}' can not be empty.
Example of Parametrized Constraint
Learn how to add a parametrized StringLengthConstraint that checks if a given string length is in specified range.
The procedure is the same as for creating simple constraints but this time the new constraint type brings own attributes. Furthermore, a configuration for managing these attributes should be added for the Administration Cockpit additionally.
Constraint Type Definition
Parametrized constraint definition extends the definition of a simple constraint type from the previous example with additional attributes: min and max.
items.xml
<itemtype code="StringLengthConstraint" autocreate="true" generate="true"
extends="AttributeConstraint"
jaloclass="<YourPackage>.StringLengthConstraint">
<description>Custom constraint which checks if string's length is
in specified range.</description>
<attributes>
<attribute type="java.lang.Integer" qualifier="min">
<description>Underflow value</description>
<modifiers read="true" write="true" search="true" optional="false"
initial="true" />
<persistence type="property" />
</attribute>
<attribute type="java.lang.Integer" qualifier="max">
<description>Overflow value</description>
<modifiers read="true" write="true" search="true" optional="false"
initial="true" />
<persistence type="property" />
</attribute>
<attribute qualifier="annotation" type="java.lang.Class" redeclare="true">
<modifiers write="false" initial="true" optional="false"/>
<defaultvalue>
<YourAnnotationsPackage>.StringLength.class
</defaultvalue>
</attribute>
</attributes>
</itemtype>
Annotation
Annotation definition from the previous example is extended with methods for additional parameters. These additional parameters are then used by the ConstraintValidator described below. Note that in annotation definition only primitive types like String, Class, annotations, enumerations, or 1-dimensional arrays are allowed. You can also configure here default values.
StringLength.java
@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = StringLengthValidator.class)
@Documented
public @interface StringLength
{
String message() default "{<YourPackage>.StringLength.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int min() default 0;
int max() default Integer.MAX_VALUE;
}
Constraint Validator
Constraint validator definition from the section Example of Simple Constraint is extended with:
-
Additional parameters
-
initialize method to gather parameters from the constraintAnnotation
-
Optional validateParameters method
StringLengthValidator.java
public class StringLengthValidator implements ConstraintValidator<StringLength,String>
{
private int min;
private int max;
@Override
public void initialize(final StringLength constraintAnnotation)
{
min = constraintAnnotation.min();
max = constraintAnnotation.max();
validateParameters();
}
@Override
public boolean isValid(final String value, final ConstraintValidatorContext
constraintValidatorContext)
{
if (value == null) // According to the JSR 303 null values are valid
{
return true;
}
final int length = value.length();
return length >= min && length <= max;
}
private void validateParameters()
{
if (min < 0)
{
throw new IllegalArgumentException("The min parameter cannot be negative.");
}
if (max < 0)
{
throw new IllegalArgumentException("The max parameter cannot be negative.");
}
if (max < min)
{
throw new IllegalArgumentException("The length cannot be negative.");
}
}
}
Error Message
In error messages, you can address constraint parameters using their names.
ValidationMessages.properties
<YourPackage>.StringLength.message='{type}.{field}' length must be between
{min} and {max}.
Configuration in the Administration Cockpit
An additional XML file is needed for Administration Cockpit to properly display new constraint types. The configuration file should be located in the /resources/admincockpit/config directory:
Editor_StringLengthConstraint_Admin.xml
<editor> <group qualifier="AttributeConstraint" visible="true" initially-opened="true"> <label lang="de">Obligatorische Daten</label> <label lang="en">Mandatory data</label> <property qualifier="AbstractConstraint.id" /> <property qualifier="AttributeConstraint.descriptor" /> <property qualifier="AbstractConstraint.active" /> <property qualifier="AbstractConstraint.severity" /> <property qualifier="StringLengthConstraint.min" /> <property qualifier="StringLengthConstraint.max" /> <property qualifier="AbstractConstraint.defaultMessage" /> <property qualifier="AbstractConstraint.message" /> </group> <group qualifier="admin" visible="true" initially-opened="false"> <label lang="de">Andere Daten</label> <label lang="en">Other data</label> <property qualifier="AbstractConstraint.type" /> <property qualifier="AbstractConstraint.target" editor="class" /> <property qualifier="AttributeConstraint.qualifier" /> <property qualifier="AbstractConstraint.constraintGroups" > <parameter> <name>allowCreate</name> <value>true</value> </parameter> <parameter> <name>defaultEmptyLabelKey</name> <value>ea.constrain_group_default_label</value> </parameter> </property> <property qualifier="AbstractConstraint.annotation" editor="class"/> <property qualifier="Item.pk" /> <property qualifier="Item.creationTime" /> <property qualifier="Item.modifiedtime" /> </group> </editor>
Creating Constraint Groups
Constraint groups may be created using Java code.
Each constraint group should have a unique ID. Thus, each instance of the ConstraintGroup should use a unique interface as a marker. The interface is automatically generated during runtime basing on the unique group ID. However, it is possible to provide the interface name that should be used. It can be an existing interface class or a nonexisting class, because it can be generated. There exists a default constraint group, which can’t be modified, removed, or assigned to constraints. Each constraint that is not assigned to any other group belongs to the default group.
To get constraints that are in the default group, use validationService.getDefaultconstraintGroup() method, as in the example.
AssertTrueConstraintModel constraint = modelService.create(AssertTrueConstraintModel.class)
constraint.setId("trueconstraint");
//set attribute descriptor but no group here!
modelService.save(constraint);
constraint.getConstraintGroups(); //returns an empty set
validationService.getDefaultconstraintGroup().getConstraints(); //return a collection with the AssertTrue constraint
constraint.setConstraintGroups(SelfDefinedGroup);
validationService.getDefaultconstraintGroup().getConstraints(); //now it returns an empty collection!
The following code snippet presents how to create constraint groups in Java code.
Set<AbstractConstraintModel> constraints;
// add desired constraints to set;
ConstraintGroupModel group1 = new ConstraintGroupModel();
group1.setId("group1");
group1.setConstraints(constraints);
modelService.save(group1);
ConstraintGroupModel group2 = new ConstraintGroupModel();
group2.setId("group2");
group2.setInterfaceName("non.existing.Interface"); // it is important to use
// different interface marker for each group
group2.setConstraints(constraints);
modelService.save(group2);
For details see the Constraint Groups section above.
Creating Dynamic Constraints
The main advantage of the DynamicConstraint is that validation business logic can be written in Java dynamically without a need for recompilation. This is possible thanks to the BeanShell interpreter that can execute Java source code at runtime.
To create a DynamicConstraint, you may use the SAP Commerce Administration Cockpit.
For more information, see Administration Cockpit Tutorial - Chapter (2): section Dynamic Constraints.
The script body for the DynamicConstraint attached to the Product checks if the Code is equal to the attribute Name for the current context language:
return getCode().equals(getName());
An instance, which gets validated is implicitly in context. It means that in our example getName() and getCode() methods are executed directly on the validated Product instance. A result of dynamic constraint validation depends on values of attributes of instance being validated.
Hints for writing BeanShell snippet:
-
General regulation to write DynamicConstraint script, is that the expression must return object, which somehow can be evaluated as a boolean true or false value (logic or textual).
-
Implicitly script is performed when the validation object is passed as the this object in Java meaning. All methods from the constrained Model can be invoked as get(Property), is(Property).
-
You can also access implicit context object ctx, which is an instance of the org.springframework.context.ApplicationContext. It gives the possibility to access Spring-based beans, services.
-
Be aware of runtime exceptions, for example NullPointerException when invoking method of the null object.
Another example of BeanShell expression uses the ServiceLayer's I18Nservice. It compares the isocode of LanguageModel with the Locale's language of the current session:
java.util.Locale loc = ctx.getBean(de.hybris.platform.servicelayer.i18n.I18NService.class).getCurrentLocale(); return !loc.getLanguage().equals(getIsocode());
The code snippet below shows how to create DynamicConstraint using Java:
DynamicConstraintModel constraint = new DynamicConstraintModel();
constraint.setActive(true);
constraint.setLanguage(ValidatorLanguage.BEANSHELL);
constraint.setExpression("return false;");