private static KnowledgeBase readKnowledgeBase() throws Exception {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(
       ResourceFactory.newClassPathResource("multipleinstance/multipleinstance.bpmn"),
       ResourceType.BPMN2);
   return kbuilder.newKnowledgeBase();
 }
Exemple #2
0
  @Test
  public void testIncrementOperator() throws Exception {
    String str = "";
    str += "package org.drools \n";
    str += "global java.util.List list \n";
    str += "rule rule1 \n";
    str += "    dialect \"mvel\" \n";
    str += "when \n";
    str += "    $I : Integer() \n";
    str += "then \n";
    str += "    i = $I.intValue(); \n";
    str += "    i += 5; \n";
    str += "    list.add( i ); \n";
    str += "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

    assertFalse(kbuilder.hasErrors());

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal("list", list);
    ksession.insert(5);

    ksession.fireAllRules();

    assertEquals(1, list.size());
    assertEquals(10, list.get(0));
  }
  public void testDroolsGeneration(int i) throws Exception {
    String filename = (i % 2 == 0) ? "/drools/stress1.drl" : "/drools/stress2.drl";
    InputStreamReader reader =
        new InputStreamReader(DroolsKnowledgeBaseTest.class.getResourceAsStream(filename));

    KnowledgeAgentConfiguration aconf = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
    aconf.setProperty("drools.agent.newInstance", "false");
    aconf.setProperty("drools.agent.monitorChangeSetEvents", "false");
    aconf.setProperty("drools.agent.scanResources", "false");

    KnowledgeBuilder builder = compileRules(reader);

    KnowledgeAgent kagent =
        KnowledgeAgentFactory.newKnowledgeAgent("Success Correspondence Agent", aconf);
    KnowledgeBase kbase = kagent.getKnowledgeBase();
    kbase.addKnowledgePackages(builder.getKnowledgePackages());
    //        kagent.monitorResourceChangeEvents(false);
    Rule rule1 = kbase.getRule("com.rosettastone.succor", "Equal rule 1");
    Rule rule5 = kbase.getRule("com.rosettastone.succor", "Equal rule 5");
    Rule rule6 = kbase.getRule("com.rosettastone.succor", "Equal rule 6");

    StatelessKnowledgeSession session = kbase.newStatelessKnowledgeSession();
    if (i % 2 == 0) {
      Assert.assertNotNull(rule1);
      Assert.assertNotNull(rule5);
      Assert.assertNull(rule6);
      testRulesFirst(session);
    } else {
      Assert.assertNull(rule1);
      Assert.assertNotNull(rule5);
      Assert.assertNotNull(rule6);
      testRulesSecond(session);
    }
  }
Exemple #4
0
  @Test
  public void testTokensInString() {
    // should query antldr DFA63 class but don't know how
    String[] operators = {",", "=", "|=", "*"};
    // test various in consequence
    String strBegin =
        ""
            + "package org.drools \n"
            + "import org.drools.Cheese \n"
            + "dialect \"mvel\"\n"
            + "rule rule1 \n"
            + "when \n"
            + "$c:Cheese(type==\"swiss\") \n"
            + "then \n"
            + "modify($c){ type = \"swiss";

    String strEnd = "good\"};\n" + "end\n";
    StringBuffer failures = new StringBuffer();
    for (String oper : operators) {
      KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
      String rule = strBegin + oper + strEnd;
      System.out.print(rule);
      kbuilder.add(ResourceFactory.newByteArrayResource(rule.getBytes()), ResourceType.DRL);
      if (kbuilder.hasErrors()) {
        failures.append(kbuilder.getErrors().toString());
      }
    }
    String failStr = failures.toString();
    if (failStr.length() > 0) {
      fail(failStr);
    }
  }
Exemple #5
0
  @Test
  public void testPackageImports() throws Exception {
    String str = "";
    str += "package org.drools \n";
    str += "dialect \"mvel\"\n";
    str += "import org.acme.healthcare.* \n";
    str += "import org.acme.insurance.* \n";
    str += "import org.acme.sensors.SensorReading \n";
    str += "rule rule1 \n";
    str += "  when \n";
    str += "    eval(true)\n";
    str += "  then \n";
    str += "    insert(new Claim());         // from org.acme.healthcare.* \n";
    str += "    insert(new Policy());        // from org.acme.insurance.* \n";
    str += "    insert(new SensorReading()); // from org.acme.sensor.SensorReading \n";
    str += "end\n";

    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
      throw new RuntimeException(kbuilder.getErrors().toString());
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);

    int result = ksession.fireAllRules();

    assertEquals(1, result);
    Collection<Object> insertedObjects = ksession.getObjects();
    assertEquals(3, insertedObjects.size());
  }
  public KnowledgePackage getKnowledgePackage2() {

    String str = "";
    str += "package org.drools\n";
    str += "global java.util.List list\n";
    str += "rule rule1 dialect\"java\" \n";
    str += "when\n";
    str += "   $p : Person( age : age == ( 18 + 18 ), eval( age == 36 ))\n";
    str += "   eval( $p.getAge() == 36 )\n";
    str += "then\n";
    str += "   System.out.println( $p );\n";
    str += "   list.add( $p );\n";
    str += "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    List<Person> list = new ArrayList<Person>();
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    ksession.setGlobal("list", list);
    ksession.insert(new Person("darth", 36));
    ksession.fireAllRules();

    assertEquals(new Person("darth", 36), list.get(0));

    return kbase.getKnowledgePackage("org.drools");
  }
  private static KnowledgeBase readKnowledgeBase() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("rulenodedemo.bpmn2"), ResourceType.BPMN2);
    kbuilder.add(ResourceFactory.newClassPathResource("financerules.drl"), ResourceType.DRL);

    return kbuilder.newKnowledgeBase();
  }
Exemple #8
0
  @Test
  public void testNestedEnum() {
    String str =
        ""
            + "package org.test \n"
            + "import "
            + Triangle.class.getCanonicalName()
            + "\n"
            + "global java.util.List list \n"
            + "rule \"show\" \n"
            + "when  \n"
            + "    $t: Triangle(t == Triangle.Type.ACUTE) \n"
            + "then \n"
            + "    list.add($t.getT()); \n"
            + "end \n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal("list", list);
    Triangle t = new Triangle(Triangle.Type.ACUTE);
    ksession.insert(t);

    ksession.fireAllRules();

    assertEquals(Triangle.Type.ACUTE, list.get(0));
  }
  protected Collection<KnowledgePackage> compileResources(
      Map<Resource, ResourceType> resources, boolean enablePropertySpecificFacts) {
    KnowledgeBuilderConfiguration conf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration();

    if (enablePropertySpecificFacts) {
      conf.setOption(PropertySpecificOption.ALLOWED);
    } else {
      conf.setOption(PropertySpecificOption.DISABLED);
    }

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(conf);
    for (Map.Entry<Resource, ResourceType> entry : resources.entrySet()) {
      kbuilder.add(entry.getKey(), entry.getValue());
      if (kbuilder.hasErrors()) {
        Logger.getLogger(Case1.class.getName())
            .log(Level.SEVERE, "Compilation Errors in {0}", entry.getKey());
        Iterator<KnowledgeBuilderError> iterator = kbuilder.getErrors().iterator();
        while (iterator.hasNext()) {
          KnowledgeBuilderError knowledgeBuilderError = iterator.next();
          Logger.getLogger(Case1.class.getName())
              .log(Level.SEVERE, knowledgeBuilderError.getMessage());
          System.out.println(knowledgeBuilderError.getMessage());
        }
        throw new IllegalStateException("Compilation Errors");
      }
    }
    return kbuilder.getKnowledgePackages();
  }
  @Test
  @Ignore
  public void testTMSWithLateUpdate() {
    // This is not actually fixable, as noted here, JBRULES-3416
    // facts must be updated, before changing other facts, as they act as HEAD in buckets.
    // leaving test here as @ignore here for future reference.
    String str =
        ""
            + "package org.drools.test;\n"
            + "\n"
            + "import org.drools.Father;\n"
            + "import org.drools.YoungestFather;\n"
            + "\n"
            + "rule \"findMarriedCouple\"\n"
            + "when\n"
            + "    $h: Father()\n"
            + "    not Father(father == $h)\n"
            + "then\n"
            + "    insertLogical(new YoungestFather($h));\n"
            + "end";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    StatefulKnowledgeSession kSession = createKnowledgeSession(kbase);

    Father abraham = new Father("abraham");
    Father bart = new Father("bart");
    Collection<Object> youngestFathers;

    bart.setFather(abraham);
    FactHandle abrahamHandle = kSession.insert(abraham);
    FactHandle bartHandle = kSession.insert(bart);
    kSession.fireAllRules();

    youngestFathers = kSession.getObjects(new ClassObjectFilter(YoungestFather.class));
    assertEquals(1, youngestFathers.size());
    assertEquals(bart, ((YoungestFather) youngestFathers.iterator().next()).getMan());

    Father homer = new Father("homer");
    FactHandle homerHandle = kSession.insert(homer);

    homer.setFather(abraham);
    // If we do kSession.update(homerHandle, homer) here instead of after bart.setFather(homer) it
    // works
    // But in some use cases we cannot do this because fact fields are actually called
    // while the facts are in an invalid temporary state
    bart.setFather(homer);
    // Late update call for homer, after bart has been changed too, but before fireAllRules
    kSession.update(homerHandle, homer);
    kSession.update(bartHandle, bart);
    kSession.fireAllRules();

    youngestFathers = kSession.getObjects(new ClassObjectFilter(YoungestFather.class));
    assertEquals(bart, ((YoungestFather) youngestFathers.iterator().next()).getMan());
    assertEquals(1, youngestFathers.size());

    // System.err.println(reportWMObjects(kSession));
  }
 private static KnowledgeBase readKnowledgeBase() throws Exception {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(
       ResourceFactory.newClassPathResource("humantask/HumanTaskDeadline.bpmn"),
       ResourceType.BPMN2);
   return kbuilder.newKnowledgeBase();
 }
  public DroolsSession(File saved, String processXML, int initialProcessInstanceId)
      throws IOException {
    this.saved = saved;

    KnowledgeBuilder kbuilder =
        KnowledgeBuilderFactory.newKnowledgeBuilder(new PackageBuilderConfiguration());
    kbuilder.add(new ReaderResource(new StringReader(processXML)), ResourceType.DRF);
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    StringBuilder sb = new StringBuilder();
    if (errors.size() > 0) {

      for (KnowledgeBuilderError error : errors) {
        sb.append(error.getMessage()).append("\n");
      }

      throw new IllegalArgumentException("Could not parse knowledge:\n" + sb);
    }

    Collection<KnowledgePackage> knowledgePackages = kbuilder.getKnowledgePackages();

    Process process = knowledgePackages.iterator().next().getProcesses().iterator().next();

    processId = process.getId();

    kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(knowledgePackages);

    marshaller = MarshallerFactory.newMarshaller(kbase);

    SessionConfiguration conf = new SessionConfiguration();
    Properties p = new Properties();
    p.setProperty(
        "drools.processInstanceManagerFactory",
        HudsonProcessInstanceManagerFactory.class.getName());
    conf.addProperties(p);
    Environment env = EnvironmentFactory.newEnvironment();
    if (!saved.exists() || saved.length() == 0) {
      session = kbase.newStatefulKnowledgeSession(conf, env);
    } else {
      InputStream is = null;
      try {
        is = new FileInputStream(saved);
        session = marshaller.unmarshall(is, conf, env);
      } catch (ClassNotFoundException e) {
        throw new IOException2("Class not found while unmarshalling " + saved.getAbsolutePath(), e);
      } catch (IOException e) {
        throw new IOException2("Error while unmarshalling " + saved.getAbsolutePath(), e);
      } finally {
        is.close();
      }
    }

    ((HudsonProcessInstanceManager)
            ((InternalWorkingMemoryEntryPoint) session)
                .getInternalWorkingMemory()
                .getProcessInstanceManager())
        .setProcessCounter(initialProcessInstanceId);
  }
 private KnowledgeBase createKnowledgeBase() {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(new ClassPathResource("ruleflow.rf"), ResourceType.DRF);
   kbuilder.add(new ClassPathResource("ruleflow2.rf"), ResourceType.DRF);
   kbuilder.add(new ClassPathResource("ruleflow3.rf"), ResourceType.DRF);
   KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
   kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
   return kbase;
 }
 private static KnowledgeBase readKnowledgeBase(String name) throws Exception {
   KnowledgeBuilderConfiguration kconf =
       KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration();
   kconf.setProperty("drools.dump.dir", "/home/kylin/work/tmp/974943");
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(kconf);
   kbuilder.add(ResourceFactory.newClassPathResource(name), ResourceType.DRL);
   KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
   kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
   return kbase;
 }
 public Boolean execute(Context context) {
   KnowledgeBuilder kbuilder = ((KnowledgeCommandContext) context).getKnowledgeBuilder();
   boolean errors = kbuilder.hasErrors();
   if (this.outIdentifier != null) {
     ((ExecutionResultImpl) ((KnowledgeCommandContext) context).getExecutionResults())
         .getResults()
         .put(this.outIdentifier, errors);
   }
   return errors;
 }
 public RulesManager() {
   final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(ResourceFactory.newClassPathResource("Car.drl", Car.class), ResourceType.DRL);
   if (kbuilder.hasErrors()) {
     throw new RuntimeException("Unable to compile \"Car.drl\".");
   }
   final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
   knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
   knowledgeBase.addKnowledgePackages(pkgs);
 }
  @Test
  public void testTMSwithQueries() {
    String str =
        ""
            + "package org.drools.test;\n"
            + "\n"
            + "global java.util.List list; \n"
            + "\n"
            + "declare Bean\n"
            + "    str : String\n"
            + "end\n"
            + "\n"
            + "query bean ( String $s )\n"
            + "    Bean(  $s ; )\n"
            + "end\n"
            + "\n"
            + "\n"
            + "rule \"init\"\n"
            + "when\n"
            + "then\n"
            + "    insert( new Bean(\"AAA\") );\n"
            + "    insert( \"x\" );\n"
            + "end\n"
            + "\n"
            + "rule \"LogicIn\"\n"
            + "when\n"
            + "    String( this == \"x\" )\n"
            + "    ?bean(  \"AAA\" ; )\n"
            + "then\n"
            + "    insertLogical(\"y\");\n"
            + "    retract(\"x\");\n"
            + "end "
            + "\n"
            + "rule \"Never\"\n"
            + "salience -999\n"
            + "when\n"
            + "    $s : String( this == \"y\" )\n"
            + "then\n"
            + "    list.add($s);\n"
            + "end";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    StatefulKnowledgeSession kSession = createKnowledgeSession(kbase);

    List list = new ArrayList();
    kSession.setGlobal("list", list);

    kSession.fireAllRules();
    assertEquals(0, list.size());

    // System.err.println(reportWMObjects(kSession));
  }
 private KnowledgeBase loadKnowledgeBaseFromString(String drlSource) {
   KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   knowledgeBuilder.add(
       ResourceFactory.newByteArrayResource(drlSource.getBytes()), ResourceType.DRL);
   if (knowledgeBuilder.hasErrors()) {
     System.err.print(knowledgeBuilder.getErrors().toString());
   }
   KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
   knowledgeBase.addKnowledgePackages(knowledgeBuilder.getKnowledgePackages());
   return knowledgeBase;
 }
  private KnowledgeBuilder compileRules(Reader reader) {
    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kBuilder.add(ResourceFactory.newReaderResource(reader), ResourceType.DRL);

    if (kBuilder.hasErrors()) {
      for (KnowledgeBuilderError err : kBuilder.getErrors()) {
        System.err.println(err.toString());
      }
      throw new IllegalStateException("DRL errors");
    }
    return kBuilder;
  }
 private void handleKnowledgeBuilderErrors(KnowledgeBuilder knowledgeBuilder) {
   if (knowledgeBuilder.hasErrors()) {
     StringBuilder builder = new StringBuilder(1024);
     builder.append("Drools " + knowledgeBuilder.getClass().getSimpleName() + " error occurred:");
     for (KnowledgeBuilderError knowledgeBuilderError : knowledgeBuilder.getErrors()) {
       builder.append("Error in line(s) [");
       appendLinesTo(knowledgeBuilderError.getErrorLines(), builder);
       builder.append("]:");
       builder.append(knowledgeBuilderError.getMessage());
     }
     throw new TestFluxException(builder.toString());
   }
 }
  public WorkflowProcessJbpm(String sourcefile, String key) {
    KnowledgeBuilderConfiguration kbc = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration();
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(kbc);

    Resource resource = ResourceFactory.newFileResource(sourcefile);

    kbuilder.add(resource, ResourceType.BPMN2);
    KnowledgeBase kbase = kbuilder.newKnowledgeBase();

    ksession = kbase.newStatefulKnowledgeSession();
    ksession.getWorkItemManager().registerWorkItemHandler("Manual Task", this);
    processInstance = ksession.startProcess(key);
  }
Exemple #22
0
  @Override
  public KnowledgeBuilder getKnowledgeBuilder(final ClassLoader cls) {
    final KnowledgeBuilderConfiguration conf =
        KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(null, cls);
    final KnowledgeBuilder kb = KnowledgeBuilderFactory.newKnowledgeBuilder(conf);
    kb.add(ResourceFactory.newClassPathResource("basic_move_rules.drl", cls), ResourceType.DRL);

    if (kb.hasErrors()) {
      for (KnowledgeBuilderError error : kb.getErrors()) {
        LOG.warn(error.getMessage() + ": " + error.getResource());
      }
    }
    return kb;
  }
Exemple #23
0
 private static KnowledgeBase readKnowledgeBase() throws Exception {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(ResourceFactory.newClassPathResource("Sample.drl"), ResourceType.DRL);
   KnowledgeBuilderErrors errors = kbuilder.getErrors();
   if (errors.size() > 0) {
     for (KnowledgeBuilderError error : errors) {
       System.err.println(error);
     }
     throw new IllegalArgumentException("Could not parse knowledge.");
   }
   KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
   kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
   return kbase;
 }
 private Collection<KnowledgePackage> buildKnowledgePackage(
     Resource resource, ResourceType resourceType) {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(resource, resourceType);
   KnowledgeBuilderErrors errors = kbuilder.getErrors();
   if (errors != null && errors.size() > 0) {
     for (KnowledgeBuilderError error : errors) {
       System.err.println("Error: " + error.getMessage());
     }
     Assert.fail("KnowledgeBase did not build");
   }
   Collection<KnowledgePackage> packages = kbuilder.getKnowledgePackages();
   return packages;
 }
 private static KnowledgeBase readKnowledgeBase() throws Exception {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   // Resource resource
   // =ResourceFactory.newClassPathResource("ruleflow.rf");
   DecisionTableConfiguration config = KnowledgeBuilderFactory.newDecisionTableConfiguration();
   config.setInputType(DecisionTableInputType.XLS);
   //		kbuilder.add(
   //				ResourceFactory
   //						.newClassPathResource("proposalRules/proposalRule.xls"),
   //				ResourceType.DTABLE, config);
   kbuilder.add(
       ResourceFactory.newClassPathResource("comboRules/comboRule-shandong.xls"),
       ResourceType.DTABLE,
       config);
   kbuilder.add(
       ResourceFactory.newClassPathResource("comboRules/comboRule-shenzhen.xls"),
       ResourceType.DTABLE,
       config);
   kbuilder.add(
       ResourceFactory.newClassPathResource("comboRules/comboRuleFlow.rf"),
       ResourceType.DRF,
       config);
   kbuilder.add(
       ResourceFactory.newClassPathResource("specialClausRule/specialClausRule.xls"),
       ResourceType.DTABLE,
       config);
   kbuilder.add(
       ResourceFactory.newClassPathResource("quickPriceRules/quickPriceRule-shandong.xls"),
       ResourceType.DTABLE,
       config);
   kbuilder.add(
       ResourceFactory.newClassPathResource("quickPriceRules/quickPriceRule-shenzhen.xls"),
       ResourceType.DTABLE,
       config);
   kbuilder.add(
       ResourceFactory.newClassPathResource("quickPriceRules/quickPriceRuleFlow.rf"),
       ResourceType.DRF,
       config);
   KnowledgeBuilderErrors errors = kbuilder.getErrors();
   if (errors.size() > 0) {
     for (KnowledgeBuilderError error : errors) {
       System.err.println("error is :" + error);
     }
     throw new IllegalArgumentException("Could not parse knowledge.....");
   }
   KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
   kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
   System.out.println("[debug]finish read base!");
   return kbase;
 }
  public void start() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    for (Resource resource : implementation.getResources()) {
      kbuilder.add(
          ResourceFactory.newUrlResource(resource.getLocationURL()),
          ResourceType.getResourceType(resource.getType()));
    }

    // TODO: do something with this!
    System.out.println(kbuilder.getErrors());

    knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
    knowledgeBase.addKnowledgePackages(kbuilder.getKnowledgePackages());
  }
  @Test
  public void testOldSchoolPackageUrl() throws Exception {
    String rule1 = this.createDefaultRule("rule1");

    String rule2 = this.createDefaultRule("rule2");

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(rule1.getBytes()), ResourceType.DRL);
    kbuilder.add(ResourceFactory.newByteArrayResource(rule2.getBytes()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }

    KnowledgeBuilderImpl kbi = (KnowledgeBuilderImpl) kbuilder;

    writePackage(kbi.getPackageBuilder().getPackage(), fileManager.newFile("pkgold.pkg"));

    String xml = "";
    xml += "<change-set xmlns='http://drools.org/drools-5.0/change-set'";
    xml += "    xmlns:xs='http://www.w3.org/2001/XMLSchema-instance'";
    xml +=
        "    xs:schemaLocation='http://drools.org/drools-5.0/change-set http://anonsvn.jboss.org/repos/labs/labs/jbossrules/trunk/drools-api/src/main/resources/change-set-1.0.0.xsd' >";
    xml += "    <add> ";
    xml +=
        "        <resource source='http://localhost:"
            + this.getPort()
            + "/pkgold.pkg' type='PKG' />";
    xml += "    </add> ";
    xml += "</change-set>";
    File fxml = fileManager.write("changeset.xml", xml);

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

    KnowledgeAgent kagent = this.createKAgent(kbase);

    applyChangeSet(kagent, ResourceFactory.newUrlResource(fxml.toURI().toURL()));

    StatefulKnowledgeSession ksession = kagent.getKnowledgeBase().newStatefulKnowledgeSession();
    List<String> list = new ArrayList<String>();
    ksession.setGlobal("list", list);
    ksession.fireAllRules();
    ksession.dispose();

    assertEquals(2, list.size());
    assertTrue(list.contains("rule1"));
    assertTrue(list.contains("rule2"));

    kagent.dispose();
  }
Exemple #28
0
  @Test
  @Ignore("Added 30-APR-2011 -Rikkola-")
  public void testNestedEnumFromJar() {
    String str =
        ""
            + "package org.test \n"
            + "import org.drools.examples.eventing.EventRequest \n"
            + "global java.util.List list \n"
            + "rule 'zaa'\n  "
            + "when \n  "
            + "request: EventRequest( status == EventRequest.Status.ACTIVE )\n   "
            + "then \n "
            + "request.setStatus(EventRequest.Status.ACTIVE); \n  "
            + "end";

    JarInputStream jis = null;
    try {
      jis = new JarInputStream(this.getClass().getResourceAsStream("/eventing-example.jar"));
    } catch (IOException e) {
      fail("Failed to load the jar");
    }
    MapBackedClassLoader loader = createClassLoader(jis);

    KnowledgeBuilderConfiguration knowledgeBuilderConfiguration =
        KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(null, loader);
    KnowledgeBuilder kbuilder =
        KnowledgeBuilderFactory.newKnowledgeBuilder(knowledgeBuilderConfiguration);
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }

    KnowledgeBaseConfiguration knowledgeBaseConfiguration =
        KnowledgeBaseFactory.newKnowledgeBaseConfiguration(null, loader);

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(knowledgeBaseConfiguration);
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    List list = new ArrayList();
    ksession.setGlobal("list", list);
    Triangle t = new Triangle(Triangle.Type.ACUTE);
    ksession.insert(t);

    ksession.fireAllRules();

    assertEquals(Triangle.Type.ACUTE, list.get(0));
  }
  private void initializeSession() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder.add(new ClassPathResource("InsuranceProcessV1.bpmn"), ResourceType.BPMN2);
    if (kbuilder.hasErrors()) {
      KnowledgeBuilderErrors errors = kbuilder.getErrors();

      for (KnowledgeBuilderError error : errors) {
        System.out.println(">>> Error:" + error.getMessage());
      }
      throw new IllegalStateException(">>> Knowledge couldn't be parsed! ");
    }

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    session = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLoggerFactory.newConsoleLogger(session);

    session.addEventListener(
        new DefaultAgendaEventListener() {

          @Override
          public void afterRuleFlowGroupActivated(
              org.drools.event.rule.RuleFlowGroupActivatedEvent event) {
            session.fireAllRules();
          }
        });

    // Registers an independent mocked work item handler for each task present
    // in the process.
    PatientDataServiceWorkItemHandler patientDataHandler = new PatientDataServiceWorkItemHandler();
    session.getWorkItemManager().registerWorkItemHandler("Gather Patient Data", patientDataHandler);
    InsuranceServiceWorkItemHandler insuranceServiceHandler = new InsuranceServiceWorkItemHandler();
    session
        .getWorkItemManager()
        .registerWorkItemHandler("Insurance Service", insuranceServiceHandler);
    CompanyGatewayWorkItemHandler companyGatewayHandler = new CompanyGatewayWorkItemHandler();
    session
        .getWorkItemManager()
        .registerWorkItemHandler("External Insurance Company Service", companyGatewayHandler);
    RatesServiceWorkItemHandler ratesServiceHandler = new RatesServiceWorkItemHandler();
    session.getWorkItemManager().registerWorkItemHandler("Rates Service", ratesServiceHandler);
    InvoiceServiceWorkItemHandler invoiceServiceHandler = new InvoiceServiceWorkItemHandler();
    session.getWorkItemManager().registerWorkItemHandler("Invoice Service", invoiceServiceHandler);
  }
  private StatefulKnowledgeSession createSession() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("rules/patient.drl"), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
      for (KnowledgeBuilderError error : kbuilder.getErrors()) {
        System.out.println(error);
      }
      throw new IllegalStateException("Error building kbase!");
    }

    kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    patientHeartbeatsEntryPoint = ksession.getWorkingMemoryEntryPoint("patientHeartbeats");
    return ksession;
  }