Implementing ValidatorGenerator
The interface ValidatorGenerator writes the validation files of a rules file, for example in Schematron. Only the
EfxRulesTranslator needs it. The toolkit provides SchematronGenerator, so you write your own only when you
validate notices with another technology, such as JavaScript in a browser, or when you need the rules in another
form.
Overview
The rules translator reads a rules file (see Rules file), checks
it, and translates every expression with your script generator. It does not write any validation file itself.
Instead, it builds a model of the rules, a ValidationPlan, and passes it to your validator generator, which turns it
into files.
The interface has a single method:
Map<String, String> generateOutput(ValidationPlan validationPlan);
It returns the files to write, as a map from their names, which can include folders, to their content. The rules translator returns this map to its caller as it is.
Your class receives the TranslatorOptions in its constructor, as the other generators do, and your
TranslatorDependencyFactory returns it from createValidatorGenerator (see
Assembling and running a translator).
The validation model
The classes of the model are in the package eu.europa.ted.efx.model.rules. They follow the structure of a rules
file: a plan holds stages, a stage holds rule-sets, and a rule-set holds rules.
ValidationPlan
The whole rules file, after its #include directives are processed.
getStages()-
The validation stages, in the order of the file (see Validation stages).
getNoticeSubtypes()-
All the notice subtypes that the rules apply to, in order.
getVariables(),getDynamicVariables()-
The global variables, and the global variables that call a dynamic function.
getEndpoints()-
The API endpoints that dynamic functions call, from their name to their URL. The URL can be empty when the validator sets it while it runs (see API endpoint declaration).
ValidationStage
getName()-
The name of the stage, such as
1a. getRuleSets()-
The rule-sets of the stage, in order.
getVariables(),getAllVariables()-
The variables declared in the stage, and those variables together with the global ones.
getNoticeSubtypes()-
The notice subtypes that the
INclauses of the rules of the stage name, fallback rules included. The rules withIN *do not add any: a stage whose rules all haveIN *gives an empty set. containsUniversalRules()-
Whether some rules of the stage apply to every notice subtype (
IN *).
RuleSet
A WITH clause and its rules (see Rule-sets).
getRuleContextPath()-
The path of the XML elements for which the validation checks the rules, already translated by your script generator.
getPromotedVariables()-
The variables that the
WITHclause declares before the context. The context can depend on them, so evaluate them before you select the elements of the context. getLocalVariables()-
The variables that the
WITHclause declares after the context. Evaluate them for each element of the context. getAllVariables()-
All the variables that the rules of the rule-set can use: those of the plan and the stage, and the promoted and local variables of the rule-set.
- Iteration over the rule-set (
for (ValidationRule rule : ruleSet), orstream()) -
Its rules, in order, without the fallback rule.
getFallbackRule()-
The rule that starts with
OTHERWISE, ornull(seeOTHERWISEclause).
ValidationRule
A rule is an AssertRule or a ReportRule. Both have the same properties:
getId(),getSeverity()-
The rule identifier, and
ERROR,WARNINGorINFO(seeASclause). getSubject()-
The
FORtarget of the rule, where a finding is reported. getNoticeSubtypeRange()-
The notice subtypes of the
INclause.asList()returns them, andisUniversal()says whether the clause wasIN *. getScope()-
PREorPOSTfrom theSCOPEclause, orANYwhen the rule has none (seeSCOPEclause). getFlag()-
The flag of the rule, or
null. getNature()-
DYNAMICfor a rule that calls a dynamic function itself, in its test, andSTATICotherwise. A rule can also depend on a dynamic function through a variable, and remainSTATIC(see Dynamic rules). getAutoGeneratedVariables()-
The variables that the translator creates for the calls of dynamic functions in the test of the rule. Each one holds the result of one call.
findReferencedDynamicVariables()-
The declared dynamic variables that the test of the rule uses, directly or through other variables.
getBehaviour()-
The semantic assertion of the rule, or
nullwhen it asserts an expression (see Semantic assertions).
The model gives the test of the rule in several forms, already translated by your script generator:
getCondition()-
The condition of the
WHENclause, ornull. For a fallback rule, the condition that none of the preconditions of the rule-set is true. getExpression()-
The expression of the
ASSERTorREPORTclause, or the test into which the translator turns a semantic assertion. getInvertedConditionOrExpressionCombination()-
For an
ASSERT, the complete test. For a rule with a condition, it isexpression or not(condition). For a rule without a condition, it is the expression alone. The test is true when the notice meets the rule, so it is what a Schematronassertchecks.
For a REPORT, the validation records a finding when the condition and the expression are both true.
SchematronGenerator writes (condition) and (expression).
Writing a generator
A generator goes through the plan and writes the output that your validator needs. The example below writes one text file for each stage, with one line for each rule: its identifier, severity, kind, context, test, notice subtypes and semantic assertion.
public class RuleListGenerator implements ValidatorGenerator {
public RuleListGenerator(TranslatorOptions options) {
}
@Override
public Map<String, String> generateOutput(ValidationPlan plan) {
Map<String, String> files = new LinkedHashMap<>();
for (ValidationStage stage : plan.getStages()) {
StringBuilder out = new StringBuilder();
for (RuleSet ruleSet : stage.getRuleSets()) {
String context = ruleSet.getRuleContextPath().getScript();
for (ValidationRule rule : ruleSet) {
out.append(line(context, rule));
}
if (ruleSet.getFallbackRule() != null) {
out.append(line(context, ruleSet.getFallbackRule()));
}
}
files.put("stage-" + stage.getName() + ".txt", out.toString());
}
return files;
}
private static String line(String context, ValidationRule rule) {
String kind = rule instanceof ReportRule ? "report" : "assert";
String test;
if (rule instanceof ReportRule) {
// A report records a finding when the condition and the expression are both true.
test = rule.getCondition() == null
? rule.getExpression().getScript()
: "(" + rule.getCondition().getScript() + ") and (" + rule.getExpression().getScript() + ")";
} else {
test = rule.getInvertedConditionOrExpressionCombination().getScript();
}
String behaviour = rule.getBehaviour() == null ? "" : " " + rule.getBehaviour().getKind();
return String.join("\t", rule.getId(), rule.getSeverity().toString(), kind, context, test,
String.join(",", rule.getNoticeSubtypeRange().asList())) + behaviour + "\n";
}
}
For a report with a condition, the example writes the test with and and parentheses, as XPath does. Write the
operators of your target language instead.
For a complete validator, also take into account:
-
Variables. The tests refer by name to the variables of the plan, the stage and the rule-set, and to the variables of each rule from
getAutoGeneratedVariables(). Declare them in your output, in a place where the tests can see them, and evaluate the promoted variables of a rule-set before its context. For a variable of a rule, checkinCondition(). A call in theWHENcondition always runs, because the condition needs its result. A call in the expression must run only when the condition is true: otherwise, the variable takes the value0, and the service is not called.SchematronGeneratordoes this. -
Notice subtypes. A validator usually checks a notice only against the rules of its subtype. Group the rules by subtype, or test the subtype while the validator runs.
-
Stages and scope. Decide whether your validator runs the stages one by one, and how it uses
SCOPE. -
Dynamic rules. Some rules call external services (see Dynamic rules).
Dynamic rules
A rule depends on an external service in two cases:
-
its test calls a dynamic function itself. The translator then puts the result of each call in a variable of the rule, which
getAutoGeneratedVariables()gives, andgetNature()returnsDYNAMIC; -
its test uses a declared variable that calls a dynamic function, directly or through other variables.
findReferencedDynamicVariables()gives these variables, butgetNature()can still returnSTATIC.
So check both: a rule is dynamic when getNature() returns DYNAMIC, or when findReferencedDynamicVariables()
returns any variable. SchematronGenerator does this. It also adds, for each of these variables, a test that
reports when the call to the service has failed, and leaves out the test of the rule in that case. A validator
that cannot call external services can leave the dynamic rules out, as the static files of SchematronGenerator
do.
findReferencedDynamicVariables() finds the variables by their names in the translated test (see
Variables in the scripts of rules). With a
script generator that writes variables in another way than XPath, find them in another way.
Semantic assertions
A rule written with a semantic assertion, such as ASSERT IS NOT EMPTY, keeps it in getBehaviour(), next to the
test into which the translator turns it (see
Semantic assertion). A generator of
validation code, such as SchematronGenerator, needs only the test, and ignores the behaviour. A generator for an
application in which users fill in notices reads the behaviour. It tells the application how to set up the form
field of the target of the rule, so that the application prevents mistakes while the user enters the data.
A Behaviour has a kind, getKind(), from the enumeration BehaviourKind: MANDATORY, FORBIDDEN,
NOT_REPEATED, NOT_MODIFIED, NOT_ADDED, NOT_REMOVED, LIMIT_COUNT, LIMIT_SIZE, LIMIT_RANGE, LIMIT_VALUES
and MATCH_PATTERN. Its other properties are the arguments that the author of the rule wrote:
-
for the three limits, a comparison and a number, or a lower and an upper limit, which you read with
getComparison()andgetNumber(), orgetLowerBound()andgetUpperBound(); -
for
LIMIT_VALUES, the codelist, which you read withgetCodelist(); -
for
MATCH_PATTERN, the pattern, which you read withgetPattern().
When the rule has a WHEN clause, its condition, from getCondition(), shows when the behaviour applies.
For example, the rule-set below gives two rules, of the kinds MANDATORY and FORBIDDEN, with the condition
BT-01-notice == 'other' and its opposite:
---- STAGE 2a ----
WITH ND-Root
WHEN BT-01-notice == 'other' ASSERT IS NOT EMPTY AS ERROR R-K7P-M2Q FOR BT-01(d)-Procedure IN *;
OTHERWISE ASSERT IS NOT PRESENT AS ERROR R-K7P-M2R FOR BT-01(d)-Procedure IN *;
Reference: SchematronGenerator
SchematronGenerator, in the package eu.europa.ted.eforms.sdk.schematron, writes the Schematron of the SDK. It
works in two steps. It first turns the plan into a Schematron model (SchematronSchema, SchematronPattern,
SchematronRule, SchematronAssert and the other classes of the package). It then fills FreeMarker templates with
that model.
Its output is organised as follows:
-
One pattern file for each stage with the rules that apply to every notice subtype, such as
validation-stage-1a.sch, and one for each stage and notice subtype with the other rules, such asvalidation-stage-1a-E2.sch. -
A
complete-validation.sch. It declares the endpoints as parameters (apiUrl-<name>) and the global variables, includes all pattern files, and has one phase for each notice subtype, with the patterns that apply to it. -
These files in two variants: under
dynamic/with all rules, and understatic/without the dynamic rules, for a validation without external services. A pattern file whose rules are all dynamic exists only underdynamic/. Each variant has its owncomplete-validation.sch. -
A
schematrons.jsonthat lists the Schematron files, each with its name, type (staticordynamic) and file name. The entries of the pattern files also give their stage. The entries of thecomplete-validation.schfiles have no stage.
Each rule-set becomes a Schematron rule with the context path. Each rule becomes an assert or a report, with
the rule identifier, and with the severity as its role. The FOR target becomes a diagnostic of the finding.
See also: