/**
   * 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();
  }
Beispiel #2
0
  @Test
  public void testEvalDetectionInBetaNode() {
    // Tests evals are generated and executed with Java dialect

    String drl = "";
    drl += "package org.test\n";
    drl += "import org.drools.Person\n";
    drl += "global java.util.List list\n";
    drl += "rule test1\n";
    drl += "when\n";
    drl += "   $s  : String()\n";
    drl += "   $p1 : Person( eval( name \n != $s ), name == ( new String($s+\"xxx\") ) )\n";
    drl += "then\n";
    drl += "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newReaderResource(new StringReader(drl)), ResourceType.DRL);
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }
    assertFalse(kbuilder.hasErrors());

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

    List<ObjectTypeNode> nodes =
        ((InternalRuleBase) ((KnowledgeBaseImpl) kbase).ruleBase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for (ObjectTypeNode n : nodes) {
      if (((ClassObjectType) n.getObjectType()).getClassType() == Person.class) {
        node = n;
        break;
      }
    }

    BetaNode betaanode = (BetaNode) node.getSinkPropagator().getSinks()[0];
    BetaNodeFieldConstraint[] constraint = (BetaNodeFieldConstraint[]) betaanode.getConstraints();
    PredicateConstraint c = (PredicateConstraint) constraint[0];
    assertTrue(c.getPredicateExpression() instanceof PredicateExpression);
    assertTrue(c.getPredicateExpression() instanceof CompiledInvoker);
    assertTrue(!(c.getPredicateExpression() instanceof MVELPredicateExpression));

    ReturnValueRestriction r =
        (ReturnValueRestriction) ((VariableConstraint) constraint[1]).getRestriction();
    assertTrue(r.getExpression() instanceof ReturnValueExpression);
    assertTrue(r.getExpression() instanceof CompiledInvoker);
    assertTrue(!(r.getExpression() instanceof MVELReturnValueExpression));
  }
Beispiel #3
0
  @Test
  public void testEvalDetectionInAlphaNode() {
    // Tests evals are generated and executed with Java dialect
    String drl = "";
    drl += "package org.test\n";
    drl += "import org.drools.Person\n";
    drl += "global java.util.List list\n";
    drl += "rule test1\n";
    drl += "when\n";
    drl += "   $p1 : Person( eval( name \n != null ), name == ( new String(\"xxx\") ) )\n";
    drl += "then\n";
    drl += "end\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newReaderResource(new StringReader(drl)), ResourceType.DRL);
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }
    assertFalse(kbuilder.hasErrors());

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

    List<ObjectTypeNode> nodes =
        ((InternalRuleBase) ((KnowledgeBaseImpl) kbase).ruleBase).getRete().getObjectTypeNodes();
    ObjectTypeNode node = null;
    for (ObjectTypeNode n : nodes) {
      if (((ClassObjectType) n.getObjectType()).getClassType() == Person.class) {
        node = n;
        break;
      }
    }

    AlphaNode alphanode = (AlphaNode) node.getSinkPropagator().getSinks()[0];
    PredicateConstraint c = (PredicateConstraint) alphanode.getConstraint();
    assertTrue(c.getPredicateExpression() instanceof PredicateExpression);
    assertTrue(c.getPredicateExpression() instanceof CompiledInvoker);
    assertTrue(!(c.getPredicateExpression() instanceof MVELPredicateExpression));

    alphanode = (AlphaNode) alphanode.getSinkPropagator().getSinks()[0];
    AlphaNodeFieldConstraint constraint = alphanode.getConstraint();

    if (constraint instanceof LiteralConstraint) {
      FieldValue fieldVal = ((LiteralConstraint) constraint).getField();
      assertEquals("xxx", fieldVal.getValue());
    }
  }
Beispiel #4
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));
  }
Beispiel #5
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);
    }
  }
Beispiel #6
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");
  }
  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();
  }
Beispiel #9
0
  private StatefulKnowledgeSession createKnowledgeSession() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("rules.drl", getClass()), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
      if (kbuilder.getErrors().size() > 0) {
        for (KnowledgeBuilderError kerror : kbuilder.getErrors()) {
          System.err.println(kerror);
        }
      }
    }

    KnowledgeBase kbase = kbuilder.newKnowledgeBase();
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    return ksession;
  }
  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 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());
   }
 }
 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());
  }
Beispiel #16
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;
 }
Beispiel #17
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;
  }
 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;
 }
Beispiel #19
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));
  }
  @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();
  }
  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;
  }
Beispiel #23
0
  public Main() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource("ContactLenses.drl", getClass()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
      System.err.println(kbuilder.getErrors().toString());
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession();

    // attribute age 			{young, pre-presbyopic, presbyopic}
    // attribute spectacle-prescrip	{myope, hypermetrope}
    // attribute astigmatism		{no, yes}
    // attribute tear-prod-rate	{reduced, normal}
    // attribute contact-lenses	{soft, hard, none}
    // age, spectaclePrescrip, astigmatism, tearProdRate
    ContactLenses c = new ContactLenses("young", "myope", "no", "reduced");
    ksession.execute(c);
    System.out.println("O paciente deve usar lente de contato? " + c.getContactLenses());

    c = new ContactLenses("young", "myope", "no", "normal");
    ksession.execute(c);
    System.out.println("O paciente deve usar lente de contato? " + c.getContactLenses());

    c = new ContactLenses("young", "hypermetrope", "yes", "normal");
    ksession.execute(c);
    System.out.println("O paciente deve usar lente de contato? " + c.getContactLenses());

    c = new ContactLenses("young", "hypermetrope", "yes", "reduced");
    ksession.execute(c);
    System.out.println("O paciente deve usar lente de contato? " + c.getContactLenses());

    c = new ContactLenses("young", "myope", "yes", "normal");
    ksession.execute(c);
    System.out.println("O paciente deve usar lente de contato? " + c.getContactLenses());

    c = new ContactLenses("presbyopic", "hypermetrope", "yes", "normal");
    ksession.execute(c);
    System.out.println("O paciente deve usar lente de contato? " + c.getContactLenses());

    c = new ContactLenses("pre-presbyopic", "hypermetrope", "yes", "normal");
    ksession.execute(c);
    System.out.println("O paciente deve usar lente de contato? " + c.getContactLenses());
  }
  /**
   * @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;
  }
Beispiel #26
0
 /**
  * Author: User Date: 08/10/2014 19:18:20
  *
  * <p>Description: Explain for enclosing_method
  *
  * @see
  * @param
  */
 private static KnowledgeBase leerReglasDRL() {
   /*DRL*/
   final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(
       ResourceFactory.newFileResource(
           "C:\\temporal\\god\\god-drools\\src\\main\\java\\com\\rest\\services\\god\\drools\\rule\\generate.drl"),
       ResourceType.DRL);
   if (kbuilder.hasErrors()) {
     for (KnowledgeBuilderError error : kbuilder.getErrors()) {
       System.err.println(error);
     }
     throw new IllegalArgumentException("Imposible crear knowledge con Order.drl");
   }
   final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
   kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
   return kbase;
   /*DRL*/
 }
Beispiel #27
0
  private void createKnowledgeBase() {
    String rulesFile = System.getProperty("robot.rules", BaguetteSOLO.RULES_FILE);

    DEBUG.message("Creating knowledge base");
    kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    DEBUG.message("Loading rules since " + rulesFile);
    kbuilder.add(
        ResourceFactory.newClassPathResource(rulesFile, BaguetteSOLO.class), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
      System.err.println(kbuilder.getErrors().toString());
    }

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

    DEBUG.message("Creating session)");
    ksession = kbase.newStatefulKnowledgeSession();
  }
  private StatelessKnowledgeSession getSession2(Resource resource) throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(resource, ResourceType.DRL);

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

    assertFalse(kbuilder.hasErrors());
    Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

    kbase.addKnowledgePackages(pkgs);
    kbase = SerializationHelper.serializeObject(kbase);
    StatelessKnowledgeSession session = kbase.newStatelessKnowledgeSession();

    session.setGlobal("list", this.list);
    session.setGlobal("cheesery", this.cheesery);
    return session;
  }
Beispiel #29
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;
  }
Beispiel #30
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);
  }