@Test
  public void testSimpleReturnValueConstraintEvaluator() throws Exception {
    final InternalKnowledgePackage pkg = new KnowledgePackageImpl("pkg1");

    ProcessDescr processDescr = new ProcessDescr();
    processDescr.setClassName("Process1");
    processDescr.setName("Process1");

    WorkflowProcessImpl process = new WorkflowProcessImpl();
    process.setName("Process1");
    process.setPackageName("pkg1");

    ReturnValueDescr descr = new ReturnValueDescr();
    descr.setText("return value;");

    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg);
    DialectCompiletimeRegistry dialectRegistry =
        pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    JavaDialect javaDialect = (JavaDialect) dialectRegistry.getDialect("java");

    ProcessBuildContext context =
        new ProcessBuildContext(
            pkgBuilder, pkg, process, processDescr, dialectRegistry, javaDialect);

    pkgBuilder.addPackageFromDrl(new StringReader("package pkg1;\nglobal Boolean value;"));

    ReturnValueConstraintEvaluator node = new ReturnValueConstraintEvaluator();

    final JavaReturnValueEvaluatorBuilder builder = new JavaReturnValueEvaluatorBuilder();
    builder.build(context, node, descr, null);

    ProcessDialectRegistry.getDialect(JavaDialect.ID).addProcess(context);
    javaDialect.compileAll();
    assertEquals(0, javaDialect.getResults().size());

    final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    List<KnowledgePackage> packages = new ArrayList<KnowledgePackage>();
    packages.add(pkgBuilder.getPackage());
    kbase.addKnowledgePackages(packages);
    final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    ksession.setGlobal("value", true);

    RuleFlowProcessInstance processInstance = new RuleFlowProcessInstance();
    processInstance.setKnowledgeRuntime((InternalKnowledgeRuntime) ksession);

    SplitInstance splitInstance = new SplitInstance();
    splitInstance.setProcessInstance(processInstance);

    assertTrue(node.evaluate(splitInstance, null, null));

    ksession.setGlobal("value", false);

    assertFalse(node.evaluate(splitInstance, null, null));
  }
  @Test
  public void testMVELDebugSymbols() throws DroolsParserException {

    MVELDebugHandler.setDebugMode(true);

    try {
      final DrlParser parser = new DrlParser(LanguageLevelOption.DRL5);
      final PackageDescr pkgDescr =
          parser.parse(new InputStreamReader(getClass().getResourceAsStream("mvel_rule.drl")));

      // just checking there is no parsing errors
      assertFalse(parser.getErrors().toString(), parser.hasErrors());

      InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.drools");

      final RuleDescr ruleDescr = pkgDescr.getRules().get(0);

      final RuleBuilder builder = new RuleBuilder();

      final KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg);
      final KnowledgeBuilderConfigurationImpl conf = pkgBuilder.getBuilderConfiguration();
      DialectCompiletimeRegistry dialectRegistry =
          pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
      Dialect dialect = dialectRegistry.getDialect("mvel");

      RuleBuildContext context =
          new RuleBuildContext(pkgBuilder, ruleDescr, dialectRegistry, pkg, dialect);

      builder.build(context);

      assertTrue(context.getErrors().toString(), context.getErrors().isEmpty());

      final RuleImpl rule = context.getRule();

      MVELConsequence mvelCons = (MVELConsequence) rule.getConsequence();
      mvelCons.compile(
          (MVELDialectRuntimeData)
              pkgBuilder
                  .getPackageRegistry(pkg.getName())
                  .getDialectRuntimeRegistry()
                  .getDialectData("mvel"));
      String s = DebugTools.decompile(mvelCons.getCompExpr());

      int fromIndex = 0;
      int count = 0;
      while ((fromIndex = s.indexOf("DEBUG_SYMBOL", fromIndex + 1)) > -1) {
        count++;
      }
      assertEquals(4, count);
    } finally {
      MVELDebugHandler.setDebugMode(false);
    }
  }
예제 #3
0
  public BuildContext createContext() {

    RuleBaseConfiguration conf = new RuleBaseConfiguration();

    KnowledgeBaseImpl rbase = new KnowledgeBaseImpl("ID", conf);
    BuildContext buildContext = new BuildContext(rbase, rbase.getReteooBuilder().getIdGenerator());

    RuleImpl rule = new RuleImpl("rule1", "org.pkg1", null);
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.pkg1");
    pkg.getDialectRuntimeRegistry().setDialectData("mvel", new MVELDialectRuntimeData());
    pkg.addRule(rule);
    buildContext.setRule(rule);

    return buildContext;
  }
  private void setupTest(String consequence, Map<String, Object> namedConsequences) {
    builder = new MVELConsequenceBuilder();

    InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.drools.compiler.test");
    pkg.addImport(new ImportDeclaration(Cheese.class.getCanonicalName()));

    KnowledgeBuilderConfigurationImpl conf = new KnowledgeBuilderConfigurationImpl();
    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg, conf);

    ruleDescr = new RuleDescr("test consequence builder");
    ruleDescr.setConsequence(consequence);
    ruleDescr.addAttribute(new AttributeDescr("dialect", "mvel"));

    for (Entry<String, Object> entry : namedConsequences.entrySet()) {
      ruleDescr.addNamedConsequences(entry.getKey(), entry.getValue());
    }

    RuleImpl rule = new RuleImpl(ruleDescr.getName());
    rule.addPattern(new Pattern(0, new ClassObjectType(Cheese.class), "$cheese"));

    rule.addPattern(new Pattern(0, new ClassObjectType(Map.class), "$map"));

    PackageRegistry pkgRegistry = pkgBuilder.getPackageRegistry(pkg.getName());
    DialectCompiletimeRegistry reg =
        pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    context =
        new RuleBuildContext(
            pkgBuilder, ruleDescr, reg, pkg, reg.getDialect(pkgRegistry.getDialect()));
    context.getBuildStack().push(rule.getLhs());

    context.getDialect().getConsequenceBuilder().build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);
    for (String name : namedConsequences.keySet()) {
      context.getDialect().getConsequenceBuilder().build(context, name);
    }

    context.getDialect().addRule(context);
    pkgRegistry.getPackage().addRule(context.getRule());
    pkgBuilder.compileAll();
    pkgBuilder.reloadAll();
    if (pkgBuilder.hasErrors()) {
      fail(pkgBuilder.getErrors().toString());
    }
  }
  /* (non-Javadoc)
   * @see junit.framework.TestCase#setUp()
   */
  @Before
  public void setUp() throws Exception {
    kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    listener1 = new TestRuleBaseListener("(listener-1) ");
    listener2 = new TestRuleBaseListener("(listener-2) ");
    kBase.addEventListener(listener1);
    kBase.addEventListener(listener2);

    final RuleImpl rule1 = new RuleImpl("test1");
    final ClassObjectType cheeseObjectType = new ClassObjectType(Cheese.class);
    final Pattern pattern = new Pattern(0, cheeseObjectType);

    ClassFieldAccessorStore store = new ClassFieldAccessorStore();
    store.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    store.setEagerWire(true);

    final ClassFieldReader extractor = store.getReader(Cheese.class, "type");

    final FieldValue field = FieldFactory.getInstance().getFieldValue("cheddar");

    final MvelConstraint constraint =
        new MvelConstraintTestUtil("type == \"cheddar\"", field, extractor);

    pattern.addConstraint(constraint);
    rule1.addPattern(pattern);

    rule1.setConsequence(
        new Consequence() {
          private static final long serialVersionUID = 510l;

          public void evaluate(
              final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory)
              throws Exception {}

          public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {}

          public void writeExternal(ObjectOutput out) throws IOException {}

          public String getName() {
            return "default";
          }
        });

    final RuleImpl rule2 = new RuleImpl("test2");
    final ClassObjectType cheeseObjectType2 = new ClassObjectType(Cheese.class);
    final Pattern pattern2 = new Pattern(0, cheeseObjectType2);

    final FieldValue field2 = FieldFactory.getInstance().getFieldValue("stilton");

    final MvelConstraint constraint2 =
        new MvelConstraintTestUtil("type == \"stilton\"", field, extractor);

    pattern2.addConstraint(constraint2);
    rule2.addPattern(pattern2);

    rule2.setConsequence(
        new Consequence() {
          private static final long serialVersionUID = 510l;

          public void evaluate(
              final KnowledgeHelper knowledgeHelper, final WorkingMemory workingMemory)
              throws Exception {}

          public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {}

          public void writeExternal(ObjectOutput out) throws IOException {}

          public String getName() {
            return "default";
          }
        });

    pkg = new KnowledgePackageImpl("org.drools.test1");
    pkg.addRule(rule1);
    pkg.addRule(rule2);
  }
예제 #6
0
  @Test
  public void testProcessEventListener() throws Exception {
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

    // create a simple package with one process to test the events
    final InternalKnowledgePackage pkg = new KnowledgePackageImpl("org.drools.test");
    RuleFlowProcess process = new RuleFlowProcess();
    process.setId("org.drools.core.process.event");
    process.setName("Event Process");

    StartNode startNode = new StartNode();
    startNode.setName("Start");
    startNode.setId(1);
    process.addNode(startNode);

    ActionNode actionNode = new ActionNode();
    actionNode.setName("Print");
    DroolsAction action = new DroolsConsequenceAction("java", null);
    action.setMetaData(
        "Action",
        new Action() {
          public void execute(ProcessContext context) throws Exception {
            logger.info("Executed action");
          }
        });
    actionNode.setAction(action);
    actionNode.setId(2);
    process.addNode(actionNode);
    new ConnectionImpl(
        startNode, Node.CONNECTION_DEFAULT_TYPE,
        actionNode, Node.CONNECTION_DEFAULT_TYPE);

    EndNode endNode = new EndNode();
    endNode.setName("End");
    endNode.setId(3);
    process.addNode(endNode);
    new ConnectionImpl(
        actionNode, Node.CONNECTION_DEFAULT_TYPE,
        endNode, Node.CONNECTION_DEFAULT_TYPE);

    pkg.addProcess(process);
    List<KnowledgePackage> pkgs = new ArrayList<KnowledgePackage>();
    pkgs.add(pkg);
    kbase.addKnowledgePackages(pkgs);

    StatefulKnowledgeSession session = kbase.newStatefulKnowledgeSession();
    final List<ProcessEvent> processEventList = new ArrayList<ProcessEvent>();
    final ProcessEventListener processEventListener =
        new ProcessEventListener() {

          public void afterNodeLeft(ProcessNodeLeftEvent event) {
            processEventList.add(event);
          }

          public void afterNodeTriggered(ProcessNodeTriggeredEvent event) {
            processEventList.add(event);
          }

          public void afterProcessCompleted(ProcessCompletedEvent event) {
            processEventList.add(event);
          }

          public void afterProcessStarted(ProcessStartedEvent event) {
            processEventList.add(event);
          }

          public void beforeNodeLeft(ProcessNodeLeftEvent event) {
            processEventList.add(event);
          }

          public void beforeNodeTriggered(ProcessNodeTriggeredEvent event) {
            processEventList.add(event);
          }

          public void beforeProcessCompleted(ProcessCompletedEvent event) {
            processEventList.add(event);
          }

          public void beforeProcessStarted(ProcessStartedEvent event) {
            processEventList.add(event);
          }

          public void beforeVariableChanged(ProcessVariableChangedEvent event) {
            processEventList.add(event);
          }

          public void afterVariableChanged(ProcessVariableChangedEvent event) {
            processEventList.add(event);
          }
        };
    session.addEventListener(processEventListener);

    // execute the process
    session.startProcess("org.drools.core.process.event");
    assertEquals(16, processEventList.size());
    assertEquals(
        "org.drools.core.process.event",
        ((ProcessStartedEvent) processEventList.get(0)).getProcessInstance().getProcessId());
    assertEquals(
        "Start",
        ((ProcessNodeTriggeredEvent) processEventList.get(1)).getNodeInstance().getNodeName());
    assertEquals(
        "Start", ((ProcessNodeLeftEvent) processEventList.get(2)).getNodeInstance().getNodeName());
    assertEquals(
        "Print",
        ((ProcessNodeTriggeredEvent) processEventList.get(3)).getNodeInstance().getNodeName());
    assertEquals(
        "Print", ((ProcessNodeLeftEvent) processEventList.get(4)).getNodeInstance().getNodeName());
    assertEquals(
        "End",
        ((ProcessNodeTriggeredEvent) processEventList.get(5)).getNodeInstance().getNodeName());
    assertEquals(
        "End", ((ProcessNodeLeftEvent) processEventList.get(6)).getNodeInstance().getNodeName());
    assertEquals(
        "org.drools.core.process.event",
        ((ProcessCompletedEvent) processEventList.get(7)).getProcessInstance().getProcessId());
    assertEquals(
        "org.drools.core.process.event",
        ((ProcessCompletedEvent) processEventList.get(8)).getProcessInstance().getProcessId());
    assertEquals(
        "End", ((ProcessNodeLeftEvent) processEventList.get(9)).getNodeInstance().getNodeName());
    assertEquals(
        "End",
        ((ProcessNodeTriggeredEvent) processEventList.get(10)).getNodeInstance().getNodeName());
    assertEquals(
        "Print", ((ProcessNodeLeftEvent) processEventList.get(11)).getNodeInstance().getNodeName());
    assertEquals(
        "Print",
        ((ProcessNodeTriggeredEvent) processEventList.get(12)).getNodeInstance().getNodeName());
    assertEquals(
        "Start", ((ProcessNodeLeftEvent) processEventList.get(13)).getNodeInstance().getNodeName());
    assertEquals(
        "Start",
        ((ProcessNodeTriggeredEvent) processEventList.get(14)).getNodeInstance().getNodeName());
    assertEquals(
        "org.drools.core.process.event",
        ((ProcessStartedEvent) processEventList.get(15)).getProcessInstance().getProcessId());
  }
  @Test
  public void testSimpleExpression() throws Exception {
    PackageDescr pkgDescr = new PackageDescr("pkg1");
    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl();
    pkgBuilder.addPackage(pkgDescr);

    InternalKnowledgePackage pkg = pkgBuilder.getPackageRegistry("pkg1").getPackage();
    final RuleDescr ruleDescr = new RuleDescr("rule 1");
    ruleDescr.setNamespace("pkg1");
    ruleDescr.setConsequence("modify (cheese) {price = 5 };\nretract (cheese)");

    DialectCompiletimeRegistry dialectRegistry =
        pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();

    MVELDialect mvelDialect = (MVELDialect) dialectRegistry.getDialect("mvel");

    final InstrumentedBuildContent context =
        new InstrumentedBuildContent(pkgBuilder, ruleDescr, dialectRegistry, pkg, mvelDialect);

    final InstrumentedDeclarationScopeResolver declarationResolver =
        new InstrumentedDeclarationScopeResolver();

    final ObjectType cheeseObjeectType = new ClassObjectType(Cheese.class);

    final Pattern pattern = new Pattern(0, cheeseObjeectType, "cheese");

    final GroupElement subrule = new GroupElement(GroupElement.AND);
    subrule.addChild(pattern);
    final Map<String, Declaration> map = new HashMap<String, Declaration>();
    map.put("cheese", pattern.getDeclaration());
    declarationResolver.setDeclarations(map);
    context.setDeclarationResolver(declarationResolver);

    final MVELConsequenceBuilder builder = new MVELConsequenceBuilder();
    builder.build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);

    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();

    PropagationContextFactory pctxFactory =
        kBase.getConfiguration().getComponentFactory().getPropagationContextFactory();
    kBase.addPackage(pkg);

    StatefulKnowledgeSessionImpl ksession =
        (StatefulKnowledgeSessionImpl) kBase.newStatefulKnowledgeSession();

    final Cheese cheddar = new Cheese("cheddar", 10);
    final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar);
    final LeftTupleImpl tuple = new LeftTupleImpl(f0, null, true);
    f0.removeLeftTuple(tuple);

    final AgendaItem item =
        new AgendaItemImpl(
            0,
            tuple,
            10,
            pctxFactory.createPropagationContext(1, 1, null, tuple, null),
            new RuleTerminalNode(
                0,
                new CompositeObjectSinkAdapterTest.MockBetaNode(),
                context.getRule(),
                subrule,
                0,
                new BuildContext(kBase, null)),
            null);
    final DefaultKnowledgeHelper kbHelper = new DefaultKnowledgeHelper(ksession);
    kbHelper.setActivation(item);
    ((MVELConsequence) context.getRule().getConsequence())
        .compile(
            (MVELDialectRuntimeData)
                pkgBuilder
                    .getPackageRegistry(pkg.getName())
                    .getDialectRuntimeRegistry()
                    .getDialectData("mvel"));
    context.getRule().getConsequence().evaluate(kbHelper, ksession);

    assertEquals(5, cheddar.getPrice());
  }
  @Test
  public void testImperativeCodeError() throws Exception {
    InternalKnowledgePackage pkg = new KnowledgePackageImpl("pkg1");
    final RuleDescr ruleDescr = new RuleDescr("rule 1");
    ruleDescr.setConsequence("if (cheese.price == 10) { cheese.price = 5; }");

    Properties properties = new Properties();
    properties.setProperty("drools.dialect.default", "mvel");
    KnowledgeBuilderConfigurationImpl cfg1 = new KnowledgeBuilderConfigurationImpl(properties);

    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg, cfg1);
    final KnowledgeBuilderConfigurationImpl conf = pkgBuilder.getBuilderConfiguration();
    PackageRegistry pkgRegistry = pkgBuilder.getPackageRegistry(pkg.getName());
    DialectCompiletimeRegistry dialectRegistry =
        pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    MVELDialect mvelDialect = (MVELDialect) dialectRegistry.getDialect(pkgRegistry.getDialect());

    final InstrumentedBuildContent context =
        new InstrumentedBuildContent(pkgBuilder, ruleDescr, dialectRegistry, pkg, mvelDialect);

    final InstrumentedDeclarationScopeResolver declarationResolver =
        new InstrumentedDeclarationScopeResolver();

    final ObjectType cheeseObjeectType = new ClassObjectType(Cheese.class);

    final Pattern pattern = new Pattern(0, cheeseObjeectType);

    final PatternExtractor extractor = new PatternExtractor(cheeseObjeectType);

    final Declaration declaration = new Declaration("cheese", extractor, pattern);
    final Map<String, Declaration> map = new HashMap<String, Declaration>();
    map.put("cheese", declaration);
    declarationResolver.setDeclarations(map);
    context.setDeclarationResolver(declarationResolver);

    final MVELConsequenceBuilder builder = new MVELConsequenceBuilder();
    builder.build(context, RuleImpl.DEFAULT_CONSEQUENCE_NAME);

    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl ksession =
        (StatefulKnowledgeSessionImpl) kBase.newStatefulKnowledgeSession();

    final Cheese cheddar = new Cheese("cheddar", 10);
    final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar);
    final LeftTupleImpl tuple = new LeftTupleImpl(f0, null, true);

    final AgendaItem item = new AgendaItemImpl(0, tuple, 10, null, null, null);
    final DefaultKnowledgeHelper kbHelper = new DefaultKnowledgeHelper(ksession);
    kbHelper.setActivation(item);
    try {
      ((MVELConsequence) context.getRule().getConsequence())
          .compile(
              (MVELDialectRuntimeData)
                  pkgBuilder
                      .getPackageRegistry(pkg.getName())
                      .getDialectRuntimeRegistry()
                      .getDialectData("mvel"));
      context.getRule().getConsequence().evaluate(kbHelper, ksession);
      fail("should throw an exception, as 'if' is not allowed");
    } catch (Exception e) {
    }

    assertEquals(10, cheddar.getPrice());
  }