Contents > 9 Extending the Metrics and Rule Engine > 9.2 Set Procedures

9.2 Set Procedures

Defining set procedures is very similar to defining metric procedures. In the following example, we will implement a "conditional" set procedure that yields one of two possible sets based on a condition. The set procedure takes three required attributes "condition", "set", and "alt". If the "condition" expression evaluates to true, the set procedure returns the result of the "set" expression, otherwise the value of the "alt" expression.
   packacke com.acme;
   import java.util.Collection;
   import com.sdmetrics.math.ExpressionNode;
   import com.sdmetrics.metrics.*;
   import com.sdmetrics.model.ModelElement;
   
01 public class SetProcedureCondition extends SetProcedure {

    @Override
02  public Collection<?> calculate(ModelElement element, Set set)
         throws SDMetricsException {

03    ProcedureAttributes attributes = set.getAttributes();
04    ExpressionNode condexp = attributes.getRequiredExpression("condition");
05    ExpressionNode setExpr = attributes.getRequiredExpression("set");
06    ExpressionNode altExpr = attributes.getRequiredExpression("alt");

07    Variables vars = new Variables(element);
08    boolean condition = evalBooleanExpression(element, condexp, vars);
09    if (condition)
         return evalSetExpression(element, setExpr, vars);

10    return evalSetExpression(element, altExpr, vars);
    }
}
Some of the metrics engine API used here we already know from (Section 9.1.2 "Implementation of the Metric Procedure"), so we focus the discussion of this implementation on new features: The return value of a set procedure can be a regular set (instance of java.util.HashSet), or a multiset (instance of com.sdmetrics.math.HashMultiSet). An "element set" (see Section 8.2 "Definition of Sets") will contain only instances of ModelElement. A "value set" will contain instances of java.lang.Number (Integer or Float), or strings. This set procedure can return either value sets or element sets, depending on the types of sets specified via the "set" and "alt" attributes.

For further examples on how to programmatically manipulate regular and multisets, see Section 9.6 "Set Functions".

To use our new set procedure, we register it with the metrics engine as follows:

<setprocedure name="conditionalset" 
   class="com.acme.SetProcedureCondition" />
Again, we deploy the class file of the procedure class in the "bin" folder of our SDMetrics installation (path com/acme/SetProcedureCondition.class). After that, we can write set definitions using the new set procedure. For example:
<set name="InterestingObjects" domain="class">
<conditionalset condition="'DataStore' in StereoTypeNames" set="AttributeSet" 
    alt="OperationSet" />
</set>
Note: every set procedure can also be used to define relation matrices (cf. Section 8.4 "Definition of Relation Matrices"). This includes custom set procedures you defined yourself.