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();
  }
  /**
   * Creates a ksession from a kbase containing process definition
   *
   * @return
   */
  public StatefulKnowledgeSession createKnowledgeSession() {
    // Create the kbuilder
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    // Add simpleProcess.bpmn to kbuilder
    kbuilder.add(new ClassPathResource("taskTypeVarietyProcess.bpmn2"), ResourceType.BPMN2);
    kbuilder.add(new ClassPathResource("taskTypeVarietyRules.drl"), ResourceType.DRL);
    System.out.println("Compiling resources");

    // Check for errors
    if (kbuilder.hasErrors()) {
      if (kbuilder.getErrors().size() > 0) {
        for (KnowledgeBuilderError error : kbuilder.getErrors()) {
          System.out.println("Error building kbase: " + error.getMessage());
        }
      }
      throw new RuntimeException("Error building kbase!");
    }

    // Create a knowledge base and add the generated package
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    // return a new stateful session
    return kbase.newStatefulKnowledgeSession();
  }
 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;
 }
Ejemplo n.º 4
0
 private static KnowledgeBase readKnowledgeBase() throws Exception {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(ResourceFactory.newClassPathResource("pacienteLanguage.dsl"), ResourceType.DSL);
   kbuilder.add(ResourceFactory.newClassPathResource("pacienteComDSL.drl"), ResourceType.DSLR);
   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;
 }
  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));
  }
Ejemplo n.º 7
0
 private static KnowledgeBase readKnowledgeBase() throws Exception {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(
       ResourceFactory.newClassPathResource("multipleinstance/multipleinstance.bpmn"),
       ResourceType.BPMN2);
   return kbuilder.newKnowledgeBase();
 }
  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");
  }
Ejemplo n.º 9
0
 private static KnowledgeBase readKnowledgeBase() throws Exception {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(
       ResourceFactory.newClassPathResource("humantask/HumanTaskDeadline.bpmn"),
       ResourceType.BPMN2);
   return kbuilder.newKnowledgeBase();
 }
Ejemplo n.º 10
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));
  }
Ejemplo n.º 11
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);
    }
  }
Ejemplo n.º 12
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));
  }
Ejemplo n.º 13
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());
  }
Ejemplo n.º 14
0
  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);
  }
  /**
   * @param TestPlan plan
   * @param List of Test Run Cases
   * @param Map of Axis configurations
   * @return test run cases processed by test plan rules
   */
  @SuppressWarnings("unchecked")
  public List<TestRunCase> filterTestRunCases(
      TestPlan plan, List<TestRunCase> runCases, Map<Axis, Set<AxisConfig>> axisMap) {

    if (plan.getRules().isEmpty()) return runCases;

    // Create Knowledge builder
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    // Add custom DSL
    kbuilder.add(ResourceFactory.newClassPathResource("default.dsl"), ResourceType.DSL);

    // Add custom rules
    kbuilder.add(
        ResourceFactory.newReaderResource(new StringReader(buildRules(plan.getRules()))),
        ResourceType.DSLR);

    // System.out.println(plan.getRules());

    // Check for errors
    if (kbuilder.hasErrors()) {
      System.err.println(kbuilder.getErrors().toString());
    }

    // Create Knowledge base
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    // Create global results list
    ksession.setGlobal("runCases", runCases);

    // Insert objects
    ksession.execute(CommandFactory.newInsert(plan));
    ksession.execute(CommandFactory.newInsertElements(runCases));
    ksession.execute(CommandFactory.newInsertElements(axisMap.keySet()));
    List<Set<AxisConfig>> l = new ArrayList<Set<AxisConfig>>(axisMap.values());
    for (Set<AxisConfig> s : l) {
      ksession.execute(CommandFactory.newInsertElements(s));
    }

    ksession.fireAllRules();

    return runCases;
  }
  private KnowledgeBase createKnowledgeBase(String ruleFile, String ruleFileType) throws Exception {
    KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    if (ruleFileType.equalsIgnoreCase(EbuildleapConstants.DROOLS_RULE_DRL)) {
      builder.add(ResourceFactory.newClassPathResource(ruleFile), ResourceType.DRL);
    }
    if (ruleFileType.equalsIgnoreCase(EbuildleapConstants.DROOLS_RULE_XLS)) {
      DecisionTableConfiguration config = KnowledgeBuilderFactory.newDecisionTableConfiguration();
      config.setInputType(DecisionTableInputType.XLS);
      builder.add(ResourceFactory.newClassPathResource(ruleFile), ResourceType.DTABLE, config);
    }

    if (builder.hasErrors()) {
      throw new RuntimeException(builder.getErrors().toString());
    }
    KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
    knowledgeBase.addKnowledgePackages(builder.getKnowledgePackages());
    return knowledgeBase;
  }
 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);
 }
 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;
 }
  @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 void addFileToKnowledgeBase(KnowledgeBuilder knowledgeBuilder, File file) {
   try {
     knowledgeBuilder.add(ResourceFactory.newFileResource(file), ResourceType.DRL);
   } catch (Throwable t) {
     throw new TestFluxException(
         "Exception occurred while adding file "
             + file.getAbsolutePath()
             + " to knowledge base: "
             + t.getMessage());
   }
 }
Ejemplo n.º 22
0
  public RulesetTest(String source) throws IllegalStateException {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource("commons.drl", Section508.class), ResourceType.DRL);
    kbuilder.add(ResourceFactory.newClassPathResource(source, Section508.class), ResourceType.DRL);
    kbuilder.add(ResourceFactory.newClassPathResource("query.drl", getClass()), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
      throw new IllegalStateException(kbuilder.getErrors().toString());
    }

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

    factory =
        new HTMLElementFactory(
            KnowledgeBaseFactory.newKnowledgeBase().newStatefulKnowledgeSession());
    html = factory.createHtmlTag(new BigInteger("1"), new Properties());
    body = factory.createBodyTag(new BigInteger("101"), html, new Properties());
    id = BigInteger.ONE;
  }
Ejemplo n.º 23
0
  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;
  }
Ejemplo n.º 24
0
  public void initKsession() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource("base.drl", getClass()), ResourceType.DRL);
    kbuilder.add(
        ResourceFactory.newClassPathResource("key-handlers.drl", getClass()), ResourceType.DRL);
    kbuilder.add(ResourceFactory.newClassPathResource("pacman.drl", getClass()), ResourceType.DRL);
    kbuilder.add(ResourceFactory.newClassPathResource("monster.drl", getClass()), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
      System.out.println(kbuilder.getErrors());
    }

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

    this.ksession = kbase.newStatefulKnowledgeSession();

    this.pacMan = new PacMan();
    this.pacMan.setSpeed(3);
    this.ksession.insert(this.pacMan);

    Monster monster = new Monster();
    monster.setSpeed(5);
    this.ksession.insert(monster);

    this.ksession.insert(new Score());

    KnowledgeRuntimeLoggerFactory.newThreadedFileLogger(this.ksession, "pacman.log", 3000);

    Location pacLocation = new Location(this.pacMan, 1, 5);

    Location monLocation = new Location(monster, 10, 5);

    this.ksession.insert(pacLocation);
    this.ksession.insert(monLocation);

    Tick tick = new Tick(0);
    this.ksession.insert(tick);
  }
Ejemplo n.º 25
0
  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);
  }
  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());
  }
 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;
 }
 public KnowledgeBase readKnowledgeBase() throws Exception {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(ResourceFactory.newClassPathResource(drlFileName), 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;
 }
Ejemplo n.º 29
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;
  }
Ejemplo n.º 30
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));
  }