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());
    }
  }
Exemplo n.º 2
0
  /**
   * 加载规则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());
  }