@SuppressWarnings("unused")
  private static KnowledgePackage getProcessWorkItems() {
    RuleFlowProcess process = new RuleFlowProcess();
    process.setId("org.drools.test.TestProcess");
    process.setName("TestProcess");
    process.setPackageName("org.drools.test");
    StartNode start = new StartNode();
    start.setId(1);
    start.setName("Start");
    process.addNode(start);
    ActionNode actionNode = new ActionNode();
    actionNode.setId(2);
    actionNode.setName("Action");
    DroolsConsequenceAction action = new DroolsConsequenceAction();
    action.setDialect("java");
    action.setConsequence("System.out.println(\"Executed action\");");
    actionNode.setAction(action);
    process.addNode(actionNode);
    new ConnectionImpl(
        start, Node.CONNECTION_DEFAULT_TYPE, actionNode, Node.CONNECTION_DEFAULT_TYPE);
    WorkItemNode workItemNode = new WorkItemNode();
    workItemNode.setId(3);
    workItemNode.setName("WorkItem1");
    Work work = new WorkImpl();
    work.setName("MyWork");
    workItemNode.setWork(work);
    process.addNode(workItemNode);
    new ConnectionImpl(
        actionNode, Node.CONNECTION_DEFAULT_TYPE, workItemNode, Node.CONNECTION_DEFAULT_TYPE);
    WorkItemNode workItemNode2 = new WorkItemNode();
    workItemNode2.setId(4);
    workItemNode2.setName("WorkItem2");
    work = new WorkImpl();
    work.setName("MyWork");
    workItemNode2.setWork(work);
    process.addNode(workItemNode2);
    new ConnectionImpl(
        workItemNode, Node.CONNECTION_DEFAULT_TYPE, workItemNode2, Node.CONNECTION_DEFAULT_TYPE);
    WorkItemNode workItemNode3 = new WorkItemNode();
    workItemNode3.setId(5);
    workItemNode3.setName("WorkItem3");
    work = new WorkImpl();
    work.setName("MyWork");
    workItemNode3.setWork(work);
    process.addNode(workItemNode3);
    new ConnectionImpl(
        workItemNode2, Node.CONNECTION_DEFAULT_TYPE, workItemNode3, Node.CONNECTION_DEFAULT_TYPE);
    EndNode end = new EndNode();
    end.setId(6);
    end.setName("End");
    process.addNode(end);
    new ConnectionImpl(
        workItemNode3, Node.CONNECTION_DEFAULT_TYPE, end, Node.CONNECTION_DEFAULT_TYPE);

    KnowledgeBuilderImpl packageBuilder = new KnowledgeBuilderImpl();
    ProcessBuilderImpl processBuilder = new ProcessBuilderImpl(packageBuilder);
    processBuilder.buildProcess(process, null);

    return packageBuilder.getPackage();
  }
  @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);
    }
  }
  private boolean applyResourceChanges(
      InternalKieModule currentKM,
      InternalKieModule newKM,
      KieJarChangeSet cs,
      List<String> modifiedClasses,
      KieBase kBase,
      KieBaseModel kieBaseModel,
      KnowledgeBuilderImpl pkgbuilder,
      CompositeKnowledgeBuilder ckbuilder) {
    boolean modifyingUsedClass = false;
    for (String modifiedClass : modifiedClasses) {
      if (pkgbuilder.isClassInUse(convertResourceToClassName(modifiedClass))) {
        modifyingUsedClass = true;
        break;
      }
    }

    boolean shouldRebuild = modifyingUsedClass;
    if (modifyingUsedClass) {
      // there are modified classes used by this kbase, so it has to be completely updated
      updateAllResources(currentKM, newKM, kieBaseModel, pkgbuilder, ckbuilder);
    } else {
      // there are no modified classes used by this kbase, so update it incrementally
      shouldRebuild =
          updateResourcesIncrementally(
                  currentKM, newKM, cs, modifiedClasses, kBase, kieBaseModel, pkgbuilder, ckbuilder)
              > 0;
    }
    return shouldRebuild;
  }
  private void rebuildAll(
      ReleaseId newReleaseId,
      ResultsImpl results,
      InternalKieModule newKM,
      List<String> modifiedClasses,
      KieBaseModel kieBaseModel,
      KnowledgeBuilderImpl kbuilder,
      CompositeKnowledgeBuilder ckbuilder) {
    Set<String> modifiedPackages = new HashSet<String>();
    if (!modifiedClasses.isEmpty()) {
      ClassLoader rootClassLoader = kbuilder.getRootClassLoader();
      if (rootClassLoader instanceof ProjectClassLoader) {
        ProjectClassLoader projectClassLoader = (ProjectClassLoader) rootClassLoader;
        projectClassLoader.reinitTypes();
        for (String resourceName : modifiedClasses) {
          String className = convertResourceToClassName(resourceName);
          byte[] bytes = newKM.getBytes(resourceName);
          Class<?> clazz = projectClassLoader.defineClass(className, resourceName, bytes);
          modifiedPackages.add(clazz.getPackage().getName());
        }
        kbuilder.setAllRuntimesDirty(modifiedPackages);
      }
    }

    ckbuilder.build();

    PackageBuilderErrors errors = kbuilder.getErrors();
    if (!errors.isEmpty()) {
      for (KnowledgeBuilderError error : errors.getErrors()) {
        results.addMessage(error);
      }
      log.error(
          "Unable to update KieBase: "
              + kieBaseModel.getName()
              + " to release "
              + newReleaseId
              + "\n"
              + errors.toString());
    }

    if (!modifiedClasses.isEmpty()) {
      kbuilder.rewireClassObjectTypes(modifiedPackages);
    }
  }
  private void updateKBase(
      InternalKnowledgeBase kBase,
      InternalKieModule currentKM,
      ReleaseId newReleaseId,
      InternalKieModule newKM,
      KieJarChangeSet cs,
      List<String> modifiedClasses,
      List<String> dslFiles,
      ResultsImpl results,
      KieBaseModel kieBaseModel) {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(kBase);
    KnowledgeBuilderImpl pkgbuilder = (KnowledgeBuilderImpl) kbuilder;
    CompositeKnowledgeBuilder ckbuilder = kbuilder.batch();

    boolean shouldRebuild =
        applyResourceChanges(
            currentKM, newKM, cs, modifiedClasses, kBase, kieBaseModel, pkgbuilder, ckbuilder);
    // remove resources first
    for (ResourceChangeSet rcs : cs.getChanges().values()) {
      if (rcs.getChangeType() == ChangeType.REMOVED) {
        String resourceName = rcs.getResourceName();
        if (!resourceName.endsWith(".properties")
            && isFileInKBase(newKM, kieBaseModel, resourceName)) {
          pkgbuilder.removeObjectsGeneratedFromResource(currentKM.getResource(resourceName));
        }
      }
    }

    if (shouldRebuild) {
      // readd unchanged dsl files to the kbuilder
      for (String dslFile : dslFiles) {
        if (isFileInKBase(newKM, kieBaseModel, dslFile)) {
          newKM.addResourceToCompiler(ckbuilder, kieBaseModel, dslFile);
        }
      }
      rebuildAll(
          newReleaseId, results, newKM, modifiedClasses, kieBaseModel, pkgbuilder, ckbuilder);
    }

    for (StatefulKnowledgeSession session : kBase.getStatefulKnowledgeSessions()) {
      ((InternalWorkingMemory) session).notifyHalt();
    }
  }
  @SuppressWarnings("unused")
  private static KnowledgePackage getProcessTimer2() {
    RuleFlowProcess process = new RuleFlowProcess();
    process.setId("org.drools.test.ProcessTimer2");
    process.setName("ProcessTimer2");
    process.setPackageName("org.drools.test");
    StartNode start = new StartNode();
    start.setId(1);
    start.setName("Start");
    process.addNode(start);
    TimerNode timerNode = new TimerNode();
    timerNode.setId(2);
    timerNode.setName("Timer");
    Timer timer = new Timer();
    timer.setDelay("0");
    timerNode.setTimer(timer);
    process.addNode(timerNode);
    new ConnectionImpl(
        start, Node.CONNECTION_DEFAULT_TYPE, timerNode, Node.CONNECTION_DEFAULT_TYPE);
    ActionNode actionNode = new ActionNode();
    actionNode.setId(3);
    actionNode.setName("Action");
    DroolsConsequenceAction action = new DroolsConsequenceAction();
    action.setDialect("java");
    action.setConsequence(
        "try { Thread.sleep(1000); } catch (Throwable t) {} System.out.println(\"Executed action\");");
    actionNode.setAction(action);
    process.addNode(actionNode);
    new ConnectionImpl(
        timerNode, Node.CONNECTION_DEFAULT_TYPE, actionNode, Node.CONNECTION_DEFAULT_TYPE);
    EndNode end = new EndNode();
    end.setId(6);
    end.setName("End");
    process.addNode(end);
    new ConnectionImpl(actionNode, Node.CONNECTION_DEFAULT_TYPE, end, Node.CONNECTION_DEFAULT_TYPE);

    KnowledgeBuilderImpl packageBuilder = new KnowledgeBuilderImpl();
    ProcessBuilderImpl processBuilder = new ProcessBuilderImpl(packageBuilder);
    processBuilder.buildProcess(process, null);
    return packageBuilder.getPackage();
  }
 protected static KnowledgeBase createKnowledgeBase() {
   // create a builder
   KnowledgeBuilderImpl builder = new KnowledgeBuilderImpl();
   // load the process
   Reader source =
       new InputStreamReader(
           AbstractWorkingMemoryDbLoggerTest.class.getResourceAsStream("/ruleflow.rf"));
   builder.addProcessFromXml(source);
   source =
       new InputStreamReader(
           AbstractWorkingMemoryDbLoggerTest.class.getResourceAsStream("/ruleflow2.rf"));
   builder.addProcessFromXml(source);
   source =
       new InputStreamReader(
           AbstractWorkingMemoryDbLoggerTest.class.getResourceAsStream("/ruleflow3.rf"));
   builder.addProcessFromXml(source);
   // create the knowledge base
   KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
   kbase.addKnowledgePackages((Collection) Arrays.asList(builder.getPackage()));
   return kbase;
 }
  /**
   * 加载规则package
   *
   * @param userRule
   */
  private void loadPackage(UserRule userRule) {
    if (kBase.getKiePackage("com.camel.drools.expert.sample." + userRule.getUserCode()) != null) {
      return;
    }

    final KnowledgeBuilderImpl builder = new KnowledgeBuilderImpl();
    File file =
        new File(
            KieSpringBasicService.class.getResource("/").getPath().toString()
                + drlDirPath
                + userRule.getUserCode()
                + ".drl");
    try {
      String drl = FileUtils.readFileToString(file);
      builder.addPackageFromDrl(new StringReader(drl));
      if (builder.hasErrors()) {
        System.out.println("[ERROR: Parsing drl error: " + builder.getErrors());
      }
    } catch (DroolsParserException | IOException e) {
      e.printStackTrace();
    }
    ((InternalKnowledgeBase) kBase).addPackage(builder.getPackage());
  }
  private int updateResourcesIncrementally(
      InternalKieModule currentKM,
      InternalKieModule newKM,
      KieJarChangeSet cs,
      List<String> modifiedClasses,
      KieBase kBase,
      KieBaseModel kieBaseModel,
      KnowledgeBuilderImpl kbuilder,
      CompositeKnowledgeBuilder ckbuilder) {
    int fileCount = modifiedClasses.size();
    for (ResourceChangeSet rcs : cs.getChanges().values()) {
      if (rcs.getChangeType() != ChangeType.REMOVED) {
        String resourceName = rcs.getResourceName();
        if (!resourceName.endsWith(".properties")
            && isFileInKBase(newKM, kieBaseModel, resourceName)) {
          List<ResourceChange> changes = rcs.getChanges();
          if (!changes.isEmpty()) {
            // we need to deal with individual parts of the resource
            fileCount +=
                AbstractKieModule.updateResource(ckbuilder, newKM, resourceName, rcs) ? 1 : 0;
          } else {
            // the whole resource has to handled
            if (rcs.getChangeType() == ChangeType.UPDATED) {
              Resource resource = currentKM.getResource(resourceName);
              kbuilder.removeObjectsGeneratedFromResource(resource);
            }
            fileCount += newKM.addResourceToCompiler(ckbuilder, kieBaseModel, resourceName) ? 1 : 0;
          }
        }
      }

      for (ResourceChangeSet.RuleLoadOrder loadOrder : rcs.getLoadOrder()) {
        KnowledgePackageImpl pkg =
            (KnowledgePackageImpl) kBase.getKiePackage(loadOrder.getPkgName());
        if (pkg != null) {
          RuleImpl rule = pkg.getRule(loadOrder.getRuleName());
          if (rule != null) {
            // rule can be null, if it didn't exist before
            rule.setLoadOrder(loadOrder.getLoadOrder());
          }
        }
      }
    }
    return fileCount;
  }
 private void updateAllResources(
     InternalKieModule currentKM,
     InternalKieModule newKM,
     KieBaseModel kieBaseModel,
     KnowledgeBuilderImpl kbuilder,
     CompositeKnowledgeBuilder ckbuilder) {
   for (String resourceName : currentKM.getFileNames()) {
     if (!resourceName.endsWith(".properties")
         && isFileInKBase(currentKM, kieBaseModel, resourceName)) {
       Resource resource = currentKM.getResource(resourceName);
       kbuilder.removeObjectsGeneratedFromResource(resource);
     }
   }
   for (String resourceName : newKM.getFileNames()) {
     if (!resourceName.endsWith(".properties")
         && isFileInKBase(newKM, kieBaseModel, resourceName)) {
       newKM.addResourceToCompiler(ckbuilder, kieBaseModel, resourceName);
     }
   }
 }
  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());
    }
  }
  @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());
  }