@Test
public void testGraphIterationToFindLeafs() {
String drl = "import " + Datum.class.getCanonicalName() + ";\n" +
"import java.util.List;\n" +
"query findLeafs(Datum datum, List results)\n" +
" ( eval( datum.getChildren().size() == 0 ) and \n" +
" eval( results.add ( datum ) ) )\n" +
" or \n" +
" ( eval( datum.getChildren().size() != 0 ) and \n" +
" child : Datum( ) from datum.children and\n" +
" findLeafs( child, results; ) ) \n" +
"end\n";
System.out.println( drl );
KnowledgeBase knowledgeBase = loadKnowledgeBaseFromString( drl );
StatefulKnowledgeSession ksession = knowledgeBase.newStatefulKnowledgeSession();
List<Datum> list = new ArrayList<Datum>();
Datum d1 = new Datum("d1");
Datum d2 = new Datum("d2");
Datum d3 = new Datum("d3");
Datum d4 = new Datum("d4");
Datum d5 = new Datum("d5");
Datum d6 = new Datum("d6");
Datum d7 = new Datum("d7");
d1.getChildren().add( d2 );
d1.getChildren().add( d3 );
d3.getChildren().add( d4 );
d3.getChildren().add( d5 ) ;
d5.getChildren().add( d6 ) ;
d6.getChildren().add( d7 ) ;
ksession.getQueryResults("findLeafs", d1, list);
System.out.println( list );
}
public static class Datum {
private String description;
private List<Datum> children;
public Datum(String description) {
this.description = description;
children = new ArrayList<Datum>();
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Datum> getChildren() {
return children;
}
@Override
public String toString() {
return "Datum{" +
"description='" + description + '\'' +
'}';
}
}