@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 testNullSafeMemberOf() {
    // DROOLS-50
    String str =
        "declare A\n"
            + "    list : java.util.List\n"
            + "end\n"
            + "\n"
            + "rule Init when\n"
            + "then\n"
            + "    insert( new A( java.util.Arrays.asList( \"test\" ) ) );"
            + "    insert( \"test\" );"
            + "end\n"
            + "rule R when\n"
            + "    $a : A()\n"
            + "    $s : String( this memberOf $a!.list )\n"
            + "then\n"
            + "end";

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

    assertEquals(2, ksession.fireAllRules());
    ksession.dispose();
  }
  @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());
  }
Example #4
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());
    }
  }
Example #5
0
  @Test
  public void testCancelNonRegisteredWorkItemHandler() {
    String processId = "org.drools.actions";
    String workName = "Unnexistent Task";
    RuleFlowProcess process = getWorkItemProcess(processId, workName);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    ((AbstractRuleBase) ((InternalKnowledgeBase) kbase).getRuleBase()).addProcess(process);
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

    ksession.getWorkItemManager().registerWorkItemHandler(workName, new DoNothingWorkItemHandler());

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("UserName", "John Doe");
    parameters.put("Person", new Person("John Doe"));

    ProcessInstance processInstance = ksession.startProcess("org.drools.actions", parameters);
    long processInstanceId = processInstance.getId();
    Assert.assertEquals(ProcessInstance.STATE_ACTIVE, processInstance.getState());
    ksession.getWorkItemManager().registerWorkItemHandler(workName, null);

    try {
      ksession.abortProcessInstance(processInstanceId);
      Assert.fail("should fail if WorkItemHandler for" + workName + "is not registered");
    } catch (WorkItemHandlerNotFoundException wihnfe) {

    }

    Assert.assertEquals(ProcessInstance.STATE_ABORTED, processInstance.getState());
  }
  private void assertProcessInstancesNotExist(long[] processId) {
    StatefulKnowledgeSession ksession = reloadKnowledgeSession();

    for (long id : processId) {
      assertNull(ksession.getProcessInstance(id));
    }
  }
 public void execute(int repNr) {
   for (int i = 0; i < objectNr; i++) {
     ksession.insert(as[i]);
     ksession.insert(bs[i]);
   }
   ksession.fireAllRules();
 }
Example #8
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));
  }
Example #9
0
  @Test
  public void testPackageImports() throws Exception {
    String str = "";
    str += "package org.kie \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<? extends Object> insertedObjects = ksession.getObjects();
    assertEquals(3, insertedObjects.size());
  }
Example #10
0
  // JBRULES-2526
  @Test
  public void testOrWithVariableResolution2() throws Exception {
    final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource(
            "test_OrCEFollowedByMultipleEval2.drl", FirstOrderLogicTest.class),
        ResourceType.DRL);

    assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors());

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

    final StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);

    final AgendaEventListener al = mock(AgendaEventListener.class);
    ksession.addEventListener(al);

    ksession.insert(new FactA("a"));
    ksession.insert(new FactB("b"));
    ksession.insert(new FactC("c"));

    ksession.fireAllRules();
    verify(al, times(8)).afterMatchFired(any(AfterMatchFiredEvent.class));
  }
Example #11
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));
  }
  /** Helper functions */
  private void assertProcessInstancesExist(long[] processId) {
    StatefulKnowledgeSession ksession = reloadKnowledgeSession();

    for (long id : processId) {
      assertNotNull(
          "Process instance " + id + " should not exist!", ksession.getProcessInstance(id));
    }
  }
 @Override
 protected StatefulKnowledgeSession disposeAndReloadSession(
     StatefulKnowledgeSession ksession, KnowledgeBase kbase) {
   long ksessionId = ksession.getIdentifier();
   ksession.dispose();
   return InfinispanKnowledgeService.loadStatefulKnowledgeSession(
       ksessionId, kbase, null, createEnvironment(context));
 }
 public void execute(Object object) {
   StatefulKnowledgeSession ksession = newWorkingMemory();
   try {
     ksession.insert(object);
     ksession.fireAllRules();
   } finally {
     dispose(ksession);
   }
 }
 @Test
 public void testNegativeNumbers() throws Exception {
   KnowledgeBase kbase = readKnowledgeBase("/data/DT_WithNegativeNumbers.xls");
   StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
   IntHolder i1 = new IntHolder(1);
   IntHolder i2 = new IntHolder(-1);
   ksession.insert(i1);
   ksession.insert(i2);
   ksession.fireAllRules();
 }
  @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));
  }
Example #17
0
  @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());
  }
  @Test
  public void testOutOfMemory() throws Exception {
    KnowledgeBase kbase = loadKnowledgeBase("empty.drl");

    for (int i = 0; i < 10000; i++) {
      StatefulKnowledgeSession session = createKnowledgeSession(kbase);
      WorkingMemoryFileLogger logger = new WorkingMemoryFileLogger(session);
      session.fireAllRules();
      session.dispose();
    }
  }
 public void execute(int repNr) {
   int i = 0;
   for (Bean bean : beans) {
     factHandles[i++] = ksession.insert(bean);
   }
   ksession.fireAllRules();
   for (FactHandle factHandle : factHandles) {
     ksession.retract(factHandle);
   }
   ksession.fireAllRules();
 }
  @Before
  public void setUp() throws Exception {
    context = setupWithPoolingDataSource(JBPM_PERSISTENCE_UNIT_NAME);
    env = createEnvironment(context);

    kbase = createBase();
    StatefulKnowledgeSession ksession =
        JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    sessionId = ksession.getIdentifier();
    ksession.dispose();
  }
  @Override
  protected StatefulKnowledgeSession disposeAndReloadSession(
      StatefulKnowledgeSession ksession, KnowledgeBase kbase) {
    long sessionId = ksession.getIdentifier();
    ksession.dispose();
    EnvironmentBuilder envBuilder = new KnowledgeSessionStorageEnvironmentBuilder(storage);
    Environment env = KieServices.Factory.get().newEnvironment();
    env.set(EnvironmentName.TRANSACTION_MANAGER, envBuilder.getTransactionManager());
    env.set(EnvironmentName.PERSISTENCE_CONTEXT_MANAGER, envBuilder.getPersistenceContextManager());

    return JPAKnowledgeService.loadStatefulKnowledgeSession(sessionId, kbase, null, env);
  }
  @Test
  public void create2ProcessInstances() throws Exception {
    long[] processId = new long[2];

    StatefulKnowledgeSession ksession = reloadKnowledgeSession();
    processId[0] =
        ksession.createProcessInstance("org.jbpm.processinstance.helloworld", null).getId();
    processId[1] =
        ksession.createProcessInstance("org.jbpm.processinstance.helloworld", null).getId();
    ksession.dispose();

    assertProcessInstancesExist(processId);
  }
  @Test
  public void testPersistenceWorkItems3() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("WorkItemsProcess.rf"), ResourceType.DRF);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession =
        InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    ksession.getWorkItemManager().registerWorkItemHandler("MyWork", new SystemOutWorkItemHandler());
    ProcessInstance processInstance = ksession.startProcess("org.drools.test.TestProcess");
    ksession.insert("TestString");
    assertEquals(ProcessInstance.STATE_COMPLETED, processInstance.getState());
  }
Example #24
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);
  }
Example #25
0
  @Test
  public void testForallSinglePattern2() throws Exception {
    final KnowledgeBase kbase = loadKnowledgeBase("test_ForallSinglePattern2.drl");
    final StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);

    ksession.insert(new Triangle(3, 3, 3));
    ksession.insert(new Triangle(3, 3, 3));

    // no cheeses, so should fire
    int fired = ksession.fireAllRules();
    assertEquals(1, fired);

    ksession.dispose();
  }
  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());
  }
Example #27
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));
  }
 public List executeWithResults(Iterable objects, ObjectFilter filter) {
   List list = new ArrayList();
   StatefulKnowledgeSession ksession = newWorkingMemory();
   try {
     for (Object object : objects) {
       ksession.insert(object);
     }
     ksession.fireAllRules();
     for (FactHandle fh : ksession.getFactHandles(filter)) {
       list.add(((InternalFactHandle) fh).getObject());
     }
   } finally {
     dispose(ksession);
   }
   return list;
 }
  @Test
  public void testPersistenceRuleSet() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("RuleSetProcess.rf"), ResourceType.DRF);
    kbuilder.add(new ClassPathResource("RuleSetRules.drl"), ResourceType.DRL);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatefulKnowledgeSession ksession =
        InfinispanKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    long id = ksession.getIdentifier();

    ksession.insert(new ArrayList<Object>());

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    ProcessInstance processInstance = ksession.startProcess("org.drools.test.TestProcess");

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNotNull(processInstance);

    ksession = InfinispanKnowledgeService.loadStatefulKnowledgeSession(id, kbase, null, env);
    ksession.fireAllRules();
    processInstance = ksession.getProcessInstance(processInstance.getId());
    assertNull(processInstance);
  }
  @Test
  public void testNullSafeNullComparison2() {
    String str =
        "import org.drools.compiler.*;\n"
            + "rule R1 when\n"
            + " $street : String()\n"
            + " Person( address!.street == $street ) \n"
            + "then\n"
            + "end";

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

    ksession.insert(new Person("Mario", 38));

    ksession.insert("Main Street");
    Person mark = new Person("Mark", 37);
    mark.setAddress(new Address("Main Street"));
    ksession.insert(mark);

    Person edson = new Person("Edson", 34);
    edson.setAddress(new Address(null));
    ksession.insert(edson);

    assertEquals(1, ksession.fireAllRules());
    ksession.dispose();
  }