public class QueryBuilderTest extends DroolsTestCase {
@Test
public void testRuleWithQuery() throws Exception {
final KnowledgeBuilderImpl builder = new KnowledgeBuilderImpl();
final PackageDescr packageDescr = new PackageDescr( "p1" );
QueryDescr queryDescr = new QueryDescr( "query1" );
queryDescr.addParameter( "String",
"$name" );
queryDescr.addParameter( "int",
"$age" );
queryDescr.addParameter( "String",
"$likes" );
packageDescr.addRule( queryDescr );
AndDescr lhs = new AndDescr();
queryDescr.setLhs( lhs );
PatternDescr pattern = new PatternDescr( Person.class.getName() );
lhs.addDescr( pattern );
pattern.addConstraint( new BindingDescr( "$name", "name", true ) );
pattern.addConstraint( new BindingDescr( "$age", "age", true ) );
pattern.addConstraint( new BindingDescr( "$likes", "likes", true ) );
RuleDescr ruleDescr = new RuleDescr( "rule-1" );
packageDescr.addRule( ruleDescr );
lhs = new AndDescr();
ruleDescr.setLhs( lhs );
pattern = new PatternDescr( Cheese.class.getName() );
lhs.addDescr( pattern );
pattern.addConstraint( new BindingDescr( "$type",
"type" ) );
pattern = new PatternDescr( "query1" );
pattern.setQuery( true );
lhs.addDescr( pattern );
ExprConstraintDescr expr = new ExprConstraintDescr("'bobba'");
expr.setPosition( 0 );
expr.setType( Type.POSITIONAL );
pattern.addConstraint(expr);
expr = new ExprConstraintDescr("$age");
expr.setPosition( 1 );
expr.setType( Type.POSITIONAL );
pattern.addConstraint( expr );
expr = new ExprConstraintDescr("$type");
expr.setPosition( 2 );
expr.setType( Type.POSITIONAL );
pattern.addConstraint( expr );
ruleDescr.setConsequence( "System.out.println(\"age: \" + $age);" );
builder.addPackage( packageDescr );
assertLength( 0,
builder.getErrors().getErrors() );
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages(Arrays.asList( new KnowledgePackage[] { builder.getPackage() } ));
final KieSession session = kbase.newStatefulKnowledgeSession();
session.insert( new Person( "bobba",
"stilton",
90 ) );