@Test
  public void testSimpleReturnValueConstraintEvaluator() throws Exception {
    final InternalKnowledgePackage pkg = new KnowledgePackageImpl("pkg1");

    ProcessDescr processDescr = new ProcessDescr();
    processDescr.setClassName("Process1");
    processDescr.setName("Process1");

    WorkflowProcessImpl process = new WorkflowProcessImpl();
    process.setName("Process1");
    process.setPackageName("pkg1");

    ReturnValueDescr descr = new ReturnValueDescr();
    descr.setText("return value;");

    KnowledgeBuilderImpl pkgBuilder = new KnowledgeBuilderImpl(pkg);
    DialectCompiletimeRegistry dialectRegistry =
        pkgBuilder.getPackageRegistry(pkg.getName()).getDialectCompiletimeRegistry();
    JavaDialect javaDialect = (JavaDialect) dialectRegistry.getDialect("java");

    ProcessBuildContext context =
        new ProcessBuildContext(
            pkgBuilder, pkg, process, processDescr, dialectRegistry, javaDialect);

    pkgBuilder.addPackageFromDrl(new StringReader("package pkg1;\nglobal Boolean value;"));

    ReturnValueConstraintEvaluator node = new ReturnValueConstraintEvaluator();

    final JavaReturnValueEvaluatorBuilder builder = new JavaReturnValueEvaluatorBuilder();
    builder.build(context, node, descr, null);

    ProcessDialectRegistry.getDialect(JavaDialect.ID).addProcess(context);
    javaDialect.compileAll();
    assertEquals(0, javaDialect.getResults().size());

    final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    List<KnowledgePackage> packages = new ArrayList<KnowledgePackage>();
    packages.add(pkgBuilder.getPackage());
    kbase.addKnowledgePackages(packages);
    final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    ksession.setGlobal("value", true);

    RuleFlowProcessInstance processInstance = new RuleFlowProcessInstance();
    processInstance.setKnowledgeRuntime((InternalKnowledgeRuntime) ksession);

    SplitInstance splitInstance = new SplitInstance();
    splitInstance.setProcessInstance(processInstance);

    assertTrue(node.evaluate(splitInstance, null, null));

    ksession.setGlobal("value", false);

    assertFalse(node.evaluate(splitInstance, null, null));
  }
Exemple #2
0
  @Test
  public void testNewConstructor() {
    String str =
        ""
            + "package org.drools.compiler.test \n"
            + "import "
            + Person.class.getCanonicalName()
            + "\n"
            + "import "
            + Address.class.getCanonicalName()
            + "\n"
            + "global java.util.List list \n"
            + "rule \"show\" \n"
            + "when  \n"
            + "    $m : Person( address == new Address('s1')) \n"
            + "then \n"
            + "    list.add('r1'); \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);

    Person p = new Person("yoda");
    p.setAddress(new Address("s1"));

    ksession.insert(p);

    ksession.fireAllRules();

    assertEquals("r1", list.get(0));

    // Check it was built with MVELReturnValueExpression constraint
    List<ObjectTypeNode> nodes = ((InternalKnowledgeBase) kbase).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];
    AlphaNodeFieldConstraint constraint = alphanode.getConstraint();

    if (constraint instanceof MvelConstraint) {
      assertTrue(((MvelConstraint) constraint).getFieldExtractor() instanceof ClassFieldReader);
      FieldValue r = ((MvelConstraint) constraint).getField();
      assertEquals(p.getAddress(), r.getValue());
    }
  }
Exemple #3
0
  @Test
  public void testFixedPattern() throws FileNotFoundException {

    DecisionTableConfiguration dtconf = KnowledgeBuilderFactory.newDecisionTableConfiguration();
    dtconf.setInputType(DecisionTableInputType.XLS);
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource("fixedPattern.xls", getClass()),
        ResourceType.DTABLE,
        dtconf);
    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    List<Long> list = new ArrayList<Long>();
    ksession.setGlobal("list", list);

    ksession.insert(1L);
    ksession.insert(2);
    ksession.fireAllRules();

    assertEquals(1, list.size());
    assertEquals(1L, (long) list.get(0));

    ksession.dispose();
  }
Exemple #4
0
  @Test
  public void testIncrementOperator() throws Exception {
    String str = "";
    str += "package org.kie \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));
  }
  @Test
  public void testLocalTransactionPerStatement() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(ruleString.getBytes()), ResourceType.DRL);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

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

    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession =
        InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    List<?> list = new ArrayList<Object>();

    ksession.setGlobal("list", list);

    ksession.insert(1);
    ksession.insert(2);
    ksession.insert(3);

    ksession.fireAllRules();

    assertEquals(3, list.size());
  }
  @Test
  public void memoryTest() throws InterruptedException {

    final StatefulKnowledgeSession ksession = createKnowledgeSession();
    Event myevent = new Event();
    ksession.setGlobal("event", myevent);

    final Server node1 = new Server(1500, "server1");

    new Thread(
            new Runnable() {
              public void run() {
                ksession.fireUntilHalt();
              }
            })
        .start();

    serverHandle = ksession.insert(node1);

    int memory = 1500;
    for (int i = 0; i < 5; i++) {
      Thread.sleep(6000);
      memory = memory - 200;

      node1.setMemory(memory);
      ksession.update(serverHandle, node1);
    }

    ksession.halt();
    System.out.println(myevent.getEvents());
  }
  @Test
  @SuppressWarnings("unchecked")
  public void test1() throws Exception {
    String rule = "package org.test;\n";
    rule += "import org.jbpm.integrationtests.test.Person\n";
    rule += "global java.util.List list\n";
    rule += "rule \"Rule 1\"\n";
    rule += "  ruleflow-group \"hello\"\n";
    rule += "when\n";
    rule += "    $p : Person( ) \n";
    rule += "then\n";
    rule += "    list.add( $p );\n";
    rule += "end";

    String process =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<process xmlns=\"http://drools.org/drools-5.0/process\"\n"
            + "    xmlns:xs=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
            + "    xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n"
            + "    type=\"RuleFlow\" name=\"ruleflow\" id=\"org.test.ruleflow\" package-name=\"org.test\" >\n"
            + "  <header>\n"
            + "  </header>\n"
            + "  <nodes>\n"
            + "    <start id=\"1\" name=\"Start\" />\n"
            + "    <ruleSet id=\"2\" name=\"Hello\" ruleFlowGroup=\"hello\" />\n"
            + "    <end id=\"3\" name=\"End\" />\n"
            + "  </nodes>\n"
            + "  <connections>\n"
            + "    <connection from=\"1\" to=\"2\"/>\n"
            + "    <connection from=\"2\" to=\"3\"/>\n"
            + "  </connections>\n"
            + "</process>";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newReaderResource(new StringReader(rule)), ResourceType.DRL);
    kbuilder.add(ResourceFactory.newReaderResource(new StringReader(process)), ResourceType.DRF);

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

    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    List<Object> list = new ArrayList<Object>();
    ksession.setGlobal("list", list);

    Person p = new Person("bobba fet", 32);
    ksession.insert(p);
    ksession.startProcess("org.test.ruleflow");

    assertEquals(1, ksession.getProcessInstances().size());

    ksession = SerializationHelper.getSerialisedStatefulKnowledgeSession(ksession, true);
    assertEquals(1, ksession.getProcessInstances().size());

    ksession.fireAllRules();

    assertEquals(1, ((List<Object>) ksession.getGlobal("list")).size());
    assertEquals(p, ((List<Object>) ksession.getGlobal("list")).get(0));
    assertEquals(0, ksession.getProcessInstances().size());
  }
Exemple #8
0
  @Test
  public void testNestedEnum() {
    String str =
        ""
            + "package org.drools.compiler.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));
  }
  public void doFactLeak() throws InterruptedException {
    // DROOLS-131
    String drl =
        "package org.drools.test; \n"
            + "global "
            + ConcurrentLinkedQueue.class.getCanonicalName()
            + " list; \n"
            +
            // "global " + AtomicInteger.class.getCanonicalName() + "counter; \n" +
            ""
            + "rule Intx when\n"
            + " $x : Integer() from entry-point \"x\" \n"
            + "then\n"
            + " list.add( $x );"
            + "end";
    int N = 1100;

    KnowledgeBase kb = loadKnowledgeBaseFromString(drl);
    final StatefulKnowledgeSession ks = kb.newStatefulKnowledgeSession();
    ConcurrentLinkedQueue list = new ConcurrentLinkedQueue<Integer>();
    AtomicInteger counter = new AtomicInteger(0);
    ks.setGlobal("list", list);
    // ks.setGlobal( "counter", counter );

    new Thread() {
      public void run() {
        ks.fireUntilHalt();
      }
    }.start();

    for (int j = 0; j < N; j++) {
      ks.getEntryPoint("x").insert(new Integer(j));
    }

    int count = 0;
    while (list.size() != N && count++ != 1000) {
      Thread.sleep(200);
    }

    ks.halt();
    if (list.size() != N) {
      for (int j = 0; j < N; j++) {
        if (!list.contains(new Integer(j))) {
          System.out.println("missed: " + j);
        }
      }
    }

    assertEquals(N, list.size());
  }
Exemple #10
0
  public void init(boolean exitOnClose) {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

    kbuilder
        .batch()
        .add(newClassPathResource("init.drl", getClass()), DRL)
        .add(newClassPathResource("game.drl", getClass()), DRL)
        .add(newClassPathResource("keys.drl", getClass()), DRL)
        .add(newClassPathResource("move.drl", getClass()), DRL)
        .add(newClassPathResource("collision.drl", getClass()), DRL)
        .add(newClassPathResource("ui.drl", getClass()), DRL)
        .build();
    if (kbuilder.hasErrors()) {
      throw new RuntimeException(kbuilder.getErrors().toString());
    }

    KieBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    config.setOption(EventProcessingOption.STREAM);

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

    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    // ksession.addEventListener( new DebugAgendaEventListener() );
    PongConfiguration pconf = new PongConfiguration();
    pconf.setExitOnClose(exitOnClose);
    ksession.setGlobal("pconf", pconf);

    //        ksession.addEventListener( new DefaultAgendaEventListener() {
    //            public void beforeMatchFired(BeforeActivationFiredEvent event)  {
    //                System.out.println( "b: " + event.getActivation().getRule().getName() + " : "
    // + event.getActivation().toFactHandles() );
    //            }
    //            public void afterMatchFired(AfterActivationFiredEvent event)  {
    //                System.out.println( "a: " + event.getActivation().getRule().getName() + " : "
    // + event.getActivation().toFactHandles() );
    //            }
    ////            public void matchCreated(ActivationCreatedEvent event)  {
    ////                System.out.println( "cr: " + event.getActivation().getRule().getName() + " :
    // " + event.getActivation().toFactHandles() );
    ////            }
    ////            public void matchCancelled(ActivationCancelledEvent event)  {
    ////                System.out.println( "cl: " + event.getActivation().getRule().getName() + " :
    // " + event.getActivation().toFactHandles() );
    ////            }
    //
    //        });

    runKSession(ksession);
  }
Exemple #11
0
  @Test
  @Ignore("Added 30-APR-2011 -Rikkola-")
  public void testNestedEnumFromJar() {
    String str =
        ""
            + "package org.drools.compiler.test \n"
            + "import org.kie.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());
    }

    KieBaseConfiguration 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 testFromWithOr() throws Exception {
    KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    builder.add(
        ResourceFactory.newInputStreamResource(
            getClass().getResourceAsStream("test_FromWithOr.drl")),
        ResourceType.DRL);

    if (builder.hasErrors()) {
      logger.info(builder.getErrors().toString());
    }
    assertFalse(builder.hasErrors());

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

    final StatefulKnowledgeSession session = createKnowledgeSession(kbase);

    final List<Address> results = new ArrayList<Address>();
    session.setGlobal("results", results);

    Address a1 = new Address();
    a1.setZipCode("12345");
    Address a2 = new Address();
    a2.setZipCode("54321");
    Address a3 = new Address();
    a3.setZipCode("99999");

    Person p = new Person();
    p.addAddress(a1);
    p.addAddress(a2);
    p.addAddress(a3);

    session.insert(p);
    session.fireAllRules();

    assertEquals(2, results.size());
    assertTrue(results.contains(a1));
    assertTrue(results.contains(a2));
  }
  @Test
  public void testSetFocus() {
    String str = "";
    str += "package org.drools.test\n";
    str += "global java.util.List list\n";
    str += "rule rule1\n";
    str += "agenda-group \"badfocus\"";
    str += "when\n";
    str += "  Integer(intValue > 0)\n";
    str += "then\n";
    str += "  list.add( 1 );\n";
    str += "end\n";
    str += "\n";

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

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

    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession =
        InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    List<?> list = new ArrayList<Object>();

    ksession.setGlobal("list", list);

    ksession.insert(1);
    ksession.insert(2);
    ksession.insert(3);
    ksession.getAgenda().getAgendaGroup("badfocus").setFocus();

    ksession.fireAllRules();

    assertEquals(3, list.size());
  }
  @Test
  public void testForall2() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newInputStreamResource(getClass().getResourceAsStream("test_Forall2.drl")),
        ResourceType.DRL);
    assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors());

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    final StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);

    final List<String> list = new ArrayList<String>();
    ksession.setGlobal("results", list);

    final State state = new State("SP");
    ksession.insert(state);

    final Person bob = new Person("Bob");
    bob.setStatus(state.getState());
    bob.setAlive(true);
    ksession.insert(bob);

    ksession.fireAllRules();

    assertEquals(0, list.size());

    final State qc = new State("QC");
    ksession.insert(qc);
    final Person john = new Person("John");
    john.setStatus(qc.getState());
    john.setAlive(false);

    ksession.fireAllRules();

    assertEquals(1, list.size());
  }
Exemple #15
0
  @Test
  public void testEvalWithBigDecimal() throws Exception {
    String str = "";
    str += "package org.kie \n";
    str += "import java.math.BigDecimal; \n";
    str += "global java.util.List list \n";
    str += "rule rule1 \n";
    str += "    dialect \"mvel\" \n";
    str += "when \n";
    str += "    $bd : BigDecimal() \n";
    str += "    eval( $bd.compareTo( BigDecimal.ZERO ) > 0 ) \n";
    str += "then \n";
    str += "    list.add( $bd ); \n";
    str += "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

    if (kbuilder.hasErrors()) {
      System.err.println(kbuilder.getErrors());
    }
    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(new BigDecimal(1.5));

    ksession.fireAllRules();

    assertEquals(1, list.size());
    assertEquals(new BigDecimal(1.5), list.get(0));
  }
  @Test
  public void testScrambleWithInterfaces() {
    /*
     *       K1 a b c d e f    1000
     *       I1     c d   f    10
     *       I2       d e      1
     *       K2   b c d e      100
     */

    // DROOLS-91
    String str =
        "package org.drools.test;\n"
            + "\n"
            + "import org.drools.compiler.integrationtests.PropertyReactivityTest.Intf1;\n"
            + "import org.drools.compiler.integrationtests.PropertyReactivityTest.Intf2;\n"
            + "import org.drools.compiler.integrationtests.PropertyReactivityTest.Klass;\n"
            + "import org.drools.compiler.integrationtests.PropertyReactivityTest.Klass2;\n"
            + "\n"
            + "global java.util.List list;\n"
            + "\n"
            + "rule \"Init\"\n"
            + "when\n"
            + "then\n"
            + "  insert( new Klass( 1, 2, 3, 4, 5, 6 ) );\n"
            + "  insert( new Klass2( 2, 3, 4, 5 ) );\n"
            + "end\n"
            + "\n"
            + "rule \"On1\"\n"
            + "when\n"
            + "  $x : Intf1( )\n"
            + "then\n"
            + "  System.out.println( \"Modify by interface \" );\n"
            + "  modify ( $x ) { setD( 200 ) }\n"
            + "end\n"
            + "rule \"On2\"\n"
            + "when\n"
            + "  $x : Klass2( )\n"
            + "then\n"
            + "  System.out.println( \"Modify by class \" );\n"
            + "  modify ( $x ) { setD( 200 ) }\n"
            + "end\n"
            + "\n"
            + "rule \"Log1\"\n"
            + "when\n"
            + "  Klass( d == 200, $id : id ) \n"
            + "then\n"
            + "  System.out.println( \"Log1 - As K1 \" + $id );\n"
            + "  list.add( $id + \"@K1\" );\n"
            + "end\n"
            + "\n"
            + "rule \"Log2\"\n"
            + "when\n"
            + "  Klass2( d == 200, $id : id ) \n"
            + "then\n"
            + "  System.out.println( \"Log2 - As K2 \" + $id );\n"
            + "  list.add( $id + \"@K2\" );\n"
            + "end\n"
            + "\n"
            + "rule \"Log3\"\n"
            + "when\n"
            + "  Intf1( d == 200, $id : id ) \n"
            + "then\n"
            + "  System.out.println( \"Log3 - As I1 \" + $id );\n"
            + "  list.add( $id + \"@I1\" );\n"
            + "end\n"
            + "\n"
            + "rule \"Log4\"\n"
            + "when\n"
            + "  Intf2( d == 200, $id : id ) \n"
            + "then\n"
            + "  System.out.println( \"Log4 - As K2 \" + $id );\n"
            + "  list.add( $id + \"@I2\" );\n"
            + "end";

    KnowledgeBase kbase = loadKnowledgeBaseFromString(str);
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    List<String> list = new ArrayList<String>();
    ksession.setGlobal("list", list);

    ksession.fireAllRules();

    System.out.println(list);

    assertTrue(list.containsAll(Arrays.asList("k1@K1", "k1@I1", "k1@I2")));
    assertTrue(list.containsAll(Arrays.asList("k2@K2", "k2@I2")));
    assertEquals(5, list.size());
  }
  @Test
  @Ignore("This test requires us to fix the propagation order")
  public void testForallWithSlidingWindow() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newInputStreamResource(
            getClass().getResourceAsStream("test_ForallSlidingWindow.drl")),
        ResourceType.DRL);
    assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors());

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

    final KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId()));
    final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(conf, null);
    final SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock();
    List<String> results = new ArrayList<String>();
    ksession.setGlobal("results", results);

    // advance time... no events, so forall should fire
    clock.advanceTime(60, TimeUnit.SECONDS);
    ksession.fireAllRules();
    assertEquals(1, results.size());

    int seq = 1;
    // advance time... there are matching events now, but forall still not fire
    ksession.insert(new StockTick(seq++, "RHT", 10, clock.getCurrentTime())); // 60
    clock.advanceTime(5, TimeUnit.SECONDS);
    ksession.fireAllRules();
    assertEquals(1, results.size());
    ksession.insert(new StockTick(seq++, "RHT", 10, clock.getCurrentTime())); // 65
    clock.advanceTime(5, TimeUnit.SECONDS);
    ksession.fireAllRules();
    assertEquals(1, results.size());

    // advance time... there are non-matching events now, so forall de-activates
    ksession.insert(new StockTick(seq++, "IBM", 10, clock.getCurrentTime())); // 70
    clock.advanceTime(10, TimeUnit.SECONDS);
    ksession.fireAllRules();
    assertEquals(1, results.size());

    // advance time... there are non-matching events now, so forall is still deactivated
    ksession.insert(new StockTick(seq++, "RHT", 10, clock.getCurrentTime())); // 80
    clock.advanceTime(10, TimeUnit.SECONDS);
    ksession.fireAllRules();
    assertEquals(1, results.size());

    // advance time... non-matching event expires now, so forall should fire
    ksession.insert(new StockTick(seq++, "RHT", 10, clock.getCurrentTime())); // 90
    clock.advanceTime(10, TimeUnit.SECONDS);
    ksession.fireAllRules();
    assertEquals(2, results.size());

    // advance time... forall still matches and should not fire
    ksession.insert(new StockTick(seq++, "RHT", 10, clock.getCurrentTime())); // 100
    clock.advanceTime(10, TimeUnit.SECONDS);
    ksession.fireAllRules();
    assertEquals(2, results.size());

    // advance time... forall still matches and should not fire
    clock.advanceTime(60, TimeUnit.SECONDS);
    ksession.fireAllRules();
    assertEquals(2, results.size());
  }
  @Test
  public void testUserTransactions() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(ruleString.getBytes()), ResourceType.DRL);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

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

    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    StatefulKnowledgeSession ksession =
        InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    ut.commit();

    List<?> list = new ArrayList<Object>();

    // insert and commit
    ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.setGlobal("list", list);
    ksession.insert(1);
    ksession.insert(2);
    ksession.fireAllRules();
    ut.commit();

    // insert and rollback
    ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.insert(3);
    ut.rollback();

    // check we rolled back the state changes from the 3rd insert
    ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.fireAllRules();
    ut.commit();
    assertEquals(2, list.size());

    // insert and commit
    ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.insert(3);
    ksession.insert(4);
    ut.commit();

    ksession.fireAllRules();

    assertEquals(4, list.size());

    // rollback again, this is testing that we can do consecutive rollbacks and commits without
    // issue
    ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.insert(5);
    ksession.insert(6);
    ut.rollback();

    ksession.fireAllRules();

    assertEquals(4, list.size());

    // now load the ksession
    ksession =
        InfinispanKnowledgeService.loadStatefulKnowledgeSession(
            ksession.getIdentifier(), kbase, null, env);

    ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.insert(7);
    ksession.insert(8);
    ut.commit();

    ksession.fireAllRules();

    assertEquals(6, list.size());
  }
Exemple #19
0
  @Test
  public void testEventTimestamp() {
    // DROOLS-268
    String drl =
        "\n"
            + "import org.drools.reteoo.integrationtests.CepEspTest.Event; \n"
            + "global java.util.List list; \n"
            + "global org.drools.core.time.SessionPseudoClock clock; \n"
            + ""
            + "declare Event \n"
            + " @role( event )\n"
            + " @timestamp( time ) \n"
            + " @expires( 10000000 ) \n"
            + "end \n"
            + ""
            + ""
            + "rule \"inform about E1\"\n"
            + "when\n"
            + " $event1 : Event( type == 1 )\n"
            + " //there is an event (T2) with value 0 between 0,2m after doorClosed\n"
            + " $event2: Event( type == 2, value == 1, this after [0, 1200ms] $event1, $timestamp : time )\n"
            + " //there is no newer event (T2) within the timeframe\n"
            + " not Event( type == 2, this after [0, 1200ms] $event1, time > $timestamp ) \n"
            + "then\n"
            + " list.add( clock.getCurrentTime() ); \n "
            + "end\n"
            + "\n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
      fail(kbuilder.getErrors().toString());
    }
    KieBaseConfiguration baseConfig = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    baseConfig.setOption(EventProcessingOption.STREAM);
    baseConfig.setOption(RuleEngineOption.RETEOO);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(baseConfig);
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    KieSessionConfiguration sessionConfig = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    sessionConfig.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId()));

    // init stateful knowledge session
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(sessionConfig, null);
    ArrayList list = new ArrayList();
    ksession.setGlobal("list", list);

    SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock();
    ksession.setGlobal("clock", clock);

    ksession.insert(new Event(1, -1, clock.getCurrentTime())); // 0
    clock.advanceTime(600, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    ksession.insert(new Event(2, 0, clock.getCurrentTime())); // 600
    clock.advanceTime(100, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    ksession.insert(new Event(2, 0, clock.getCurrentTime())); // 700
    clock.advanceTime(300, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    ksession.insert(new Event(2, 0, clock.getCurrentTime())); // 1000
    clock.advanceTime(100, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    ksession.insert(new Event(2, 1, clock.getCurrentTime())); // 1100
    clock.advanceTime(100, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    clock.advanceTime(100, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();
    ksession.insert(new Event(2, 0, clock.getCurrentTime())); // 1300

    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.fireAllRules();

    assertFalse(list.isEmpty());
    assertEquals(1, list.size());
    Long time = (Long) list.get(0);

    assertTrue(time > 1000 && time < 1500);

    ksession.dispose();
  }