@Test
  public void testEventExpires() throws Exception {
    String timerRule =
        "package org.drools.test\n"
            + "declare TestEvent \n"
            + "    @role( event )\n"
            + "    @expires( 10s )\n"
            + "end\n"
            + ""
            + "rule TimerRule \n"
            + "    when \n"
            + "        TestEvent( ) from entry-point \"Test\"\n"
            + "    then \n"
            + "end";
    KnowledgeBaseConfiguration kbconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbconf.setOption(EventProcessingOption.STREAM);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kbconf);
    Resource resource = ResourceFactory.newByteArrayResource(timerRule.getBytes());
    Collection<KnowledgePackage> kpackages = buildKnowledgePackage(resource, ResourceType.DRL);
    kbase.addKnowledgePackages(kpackages);
    StatefulKnowledgeSession ksession = createSession(kbase);

    FactType type = kbase.getFactType("org.drools.test", "TestEvent");
    Assert.assertNotNull("could not get type", type);

    ksession = disposeAndReloadSession(ksession, kbase);
    ksession.getWorkingMemoryEntryPoint("Test").insert(type.newInstance());
    ksession.fireAllRules();
    ksession = disposeAndReloadSession(ksession, kbase);

    ksession = disposeAndReloadSession(ksession, kbase);
  }
  public void testLogger1() throws Exception {

    // load the process
    KnowledgeBase kbase = createKnowledgeBase();
    // create a new session
    Environment env = KnowledgeBaseFactory.newEnvironment();
    env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
    env.set(
        EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager());
    Properties properties = new Properties();
    properties.put(
        "drools.processInstanceManagerFactory",
        "org.jbpm.persistence.processinstance.JPAProcessInstanceManagerFactory");
    properties.put(
        "drools.processSignalManagerFactory",
        "org.jbpm.persistence.processinstance.JPASignalManagerFactory");
    KnowledgeSessionConfiguration config =
        KnowledgeBaseFactory.newKnowledgeSessionConfiguration(properties);
    StatefulKnowledgeSession session =
        JPAKnowledgeService.newStatefulKnowledgeSession(kbase, config, env);
    new JPAWorkingMemoryDbLogger(session);
    JPAProcessInstanceDbLog log = new JPAProcessInstanceDbLog(env);
    session
        .getWorkItemManager()
        .registerWorkItemHandler("Human Task", new SystemOutWorkItemHandler());

    // record the initial count to compare to later
    List<ProcessInstanceLog> processInstances = log.findProcessInstances("com.sample.ruleflow");
    int initialProcessInstanceSize = processInstances.size();

    // start process instance
    long processInstanceId = session.startProcess("com.sample.ruleflow").getId();

    System.out.println("Checking process instances for process 'com.sample.ruleflow'");
    processInstances = log.findProcessInstances("com.sample.ruleflow");
    assertEquals(initialProcessInstanceSize + 1, processInstances.size());
    ProcessInstanceLog processInstance = processInstances.get(0);
    System.out.print(processInstance);
    System.out.println(" -> " + processInstance.getStart() + " - " + processInstance.getEnd());
    assertNotNull(processInstance.getStart());
    assertNotNull(processInstance.getEnd());
    assertEquals(processInstanceId, processInstance.getProcessInstanceId());
    assertEquals("com.sample.ruleflow", processInstance.getProcessId());
    List<NodeInstanceLog> nodeInstances = log.findNodeInstances(processInstanceId);
    assertEquals(6, nodeInstances.size());
    for (NodeInstanceLog nodeInstance : nodeInstances) {
      System.out.println(nodeInstance);
      assertEquals(processInstanceId, processInstance.getProcessInstanceId());
      assertEquals("com.sample.ruleflow", processInstance.getProcessId());
      assertNotNull(nodeInstance.getDate());
    }
    log.clear();
    processInstances = log.findProcessInstances("com.sample.ruleflow");
    assertEquals(0, processInstances.size());
    log.dispose();
  }
Ejemplo n.º 3
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 testPersistenceTimer2() throws Exception {
    setUp();

    Properties properties = new Properties();
    properties.setProperty("drools.commandService", SingleSessionCommandService.class.getName());
    properties.setProperty(
        "drools.processInstanceManagerFactory", JPAProcessInstanceManagerFactory.class.getName());
    properties.setProperty(
        "drools.workItemManagerFactory", JPAWorkItemManagerFactory.class.getName());
    properties.setProperty(
        "drools.processSignalManagerFactory", JPASignalManagerFactory.class.getName());

    SessionConfiguration config = new SessionConfiguration(properties);
    config.setTimerJobFactoryManager(new JpaTimeJobFactoryManager());

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    Collection<KnowledgePackage> kpkgs = getProcessTimer2();
    kbase.addKnowledgePackages(kpkgs);

    SingleSessionCommandService service = new SingleSessionCommandService(kbase, config, env);
    int sessionId = service.getSessionId();
    StartProcessCommand startProcessCommand = new StartProcessCommand();
    startProcessCommand.setProcessId("org.drools.test.TestProcess");
    ProcessInstance processInstance = service.execute(startProcessCommand);
    System.out.println("Started process instance " + processInstance.getId());

    Thread.sleep(2000);

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    GetProcessInstanceCommand getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstance.getId());
    processInstance = service.execute(getProcessInstanceCommand);
    assertNull(processInstance);
  }
  /**
   * 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();
  }
Ejemplo n.º 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());
  }
  @Test
  @Ignore
  public void testTMSWithLateUpdate() {
    // This is not actually fixable, as noted here, JBRULES-3416
    // facts must be updated, before changing other facts, as they act as HEAD in buckets.
    // leaving test here as @ignore here for future reference.
    String str =
        ""
            + "package org.drools.test;\n"
            + "\n"
            + "import org.drools.Father;\n"
            + "import org.drools.YoungestFather;\n"
            + "\n"
            + "rule \"findMarriedCouple\"\n"
            + "when\n"
            + "    $h: Father()\n"
            + "    not Father(father == $h)\n"
            + "then\n"
            + "    insertLogical(new YoungestFather($h));\n"
            + "end";

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

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

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

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

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

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

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

    // System.err.println(reportWMObjects(kSession));
  }
  public KnowledgePackage getKnowledgePackage2() {

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

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

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

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

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

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

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

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

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

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

    ksession.fireAllRules();

    assertEquals(Triangle.Type.ACUTE, list.get(0));
  }
Ejemplo n.º 10
0
  @Test
  public void testIncrementOperator() throws Exception {
    String str = "";
    str += "package org.drools \n";
    str += "global java.util.List list \n";
    str += "rule rule1 \n";
    str += "    dialect \"mvel\" \n";
    str += "when \n";
    str += "    $I : Integer() \n";
    str += "then \n";
    str += "    i = $I.intValue(); \n";
    str += "    i += 5; \n";
    str += "    list.add( i ); \n";
    str += "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

    assertFalse(kbuilder.hasErrors());

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

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

    ksession.fireAllRules();

    assertEquals(1, list.size());
    assertEquals(10, list.get(0));
  }
Ejemplo n.º 11
0
  @Test
  public void testStatelessWithCommands() throws Exception {
    File f1 = fileManager.write("rule1.drl", createDefaultRule("rule1"));

    File f2 = fileManager.write("rule2.drl", createDefaultRule("rule2"));

    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='" + f1.getParentFile().toURI().toURL() + "' type='DRL' />";
    xml += "    </add> ";
    xml += "</change-set>";
    File fxml = fileManager.write("changeset", "changeset.xml", xml);

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

    KnowledgeAgent kagent = this.createKAgent(kbase);

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

    StatelessKnowledgeSession ksession = kagent.newStatelessKnowledgeSession();

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

    ksession.execute(new InsertObjectCommand("hello"));

    assertEquals(2, list.size());
    assertTrue(list.contains("rule1"));
    assertTrue(list.contains("rule2"));
  }
Ejemplo n.º 12
0
 public static StatefulKnowledgeSession createKnowledgeSessionFromKBase(
     KnowledgeBase kbase, HashMap<String, Object> context) {
   KnowledgeSessionConfiguration ksconf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
   StatefulKnowledgeSession knowledgeSession =
       JPAKnowledgeService.newStatefulKnowledgeSession(kbase, ksconf, createEnvironment(context));
   return knowledgeSession;
 }
Ejemplo n.º 13
0
  @Test
  public void testModifyFileUrl() throws Exception {
    fileManager.write("rule1.drl", createDefaultRule("rule1"));

    fileManager.write("rule2.drl", createDefaultRule("rule2"));

    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()
            + "/rule1.drl' type='DRL' />";
    xml +=
        "        <resource source='http://localhost:"
            + this.getPort()
            + "/rule2.drl' type='DRL' />";
    xml += "    </add> ";
    xml += "</change-set>";

    File fxml = fileManager.write("changeset.xml", xml);

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    KnowledgeAgent kagent = 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"));

    list.clear();

    this.fileManager.write("rule1.drl", createDefaultRule("rule3"));

    scan(kagent);

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

    assertEquals(2, list.size());

    assertTrue(list.contains("rule3"));
    assertTrue(list.contains("rule2"));

    kagent.dispose();
  }
 private StatefulKnowledgeSession createSession(KnowledgeBase kbase) {
   final KnowledgeSessionConfiguration conf =
       KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
   conf.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId()));
   StatefulKnowledgeSession ksession =
       JPAKnowledgeService.newStatefulKnowledgeSession(kbase, conf, createEnvironment());
   return ksession;
 }
 private Environment createEnvironment() {
   Environment env = KnowledgeBaseFactory.newEnvironment();
   env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
   // env.set(EnvironmentName.TRANSACTION_MANAGER,
   // TransactionManagerServices.getTransactionManager());
   env.set(EnvironmentName.GLOBALS, new MapGlobalResolver());
   return env;
 }
Ejemplo n.º 16
0
  public DroolsSession(File saved, String processXML, int initialProcessInstanceId)
      throws IOException {
    this.saved = saved;

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

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

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

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

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

    processId = process.getId();

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

    marshaller = MarshallerFactory.newMarshaller(kbase);

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

    ((HudsonProcessInstanceManager)
            ((InternalWorkingMemoryEntryPoint) session)
                .getInternalWorkingMemory()
                .getProcessInstanceManager())
        .setProcessCounter(initialProcessInstanceId);
  }
  @Test
  @Ignore("Probably expects H2 do delete everything on shutdown?")
  public void testPersistenceTimer() throws Exception {
    final Environment env = KnowledgeBaseFactory.newEnvironment();
    env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
    env.set(
        EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager());

    final Properties properties = new Properties();
    properties.setProperty("drools.commandService", SingleSessionCommandService.class.getName());
    properties.setProperty(
        "drools.processInstanceManagerFactory", JPAProcessInstanceManagerFactory.class.getName());
    properties.setProperty(
        "drools.workItemManagerFactory", JPAWorkItemManagerFactory.class.getName());
    properties.setProperty(
        "drools.processSignalManagerFactory", JPASignalManagerFactory.class.getName());
    properties.setProperty("drools.timerService", JpaJDKTimerService.class.getName());
    final SessionConfiguration config = new SessionConfiguration(properties);

    final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    final Collection<KnowledgePackage> kpkgs = getProcessTimer();
    kbase.addKnowledgePackages(kpkgs);

    SingleSessionCommandService service = new SingleSessionCommandService(kbase, config, env);
    final int sessionId = service.getSessionId();
    final StartProcessCommand startProcessCommand = new StartProcessCommand();
    startProcessCommand.setProcessId("org.drools.test.TestProcess");
    ProcessInstance processInstance = service.execute(startProcessCommand);
    System.out.println("Started process instance " + processInstance.getId());
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    GetProcessInstanceCommand getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstance.getId());
    processInstance = service.execute(getProcessInstanceCommand);
    assertNotNull(processInstance);
    service.dispose();

    service = new SingleSessionCommandService(sessionId, kbase, config, env);
    Thread.sleep(3000);
    getProcessInstanceCommand = new GetProcessInstanceCommand();
    getProcessInstanceCommand.setProcessInstanceId(processInstance.getId());
    processInstance = service.execute(getProcessInstanceCommand);
    assertNull(processInstance);
  }
Ejemplo n.º 18
0
 private KnowledgeBase createKnowledgeBase() {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(new ClassPathResource("ruleflow.rf"), ResourceType.DRF);
   kbuilder.add(new ClassPathResource("ruleflow2.rf"), ResourceType.DRF);
   kbuilder.add(new ClassPathResource("ruleflow3.rf"), ResourceType.DRF);
   KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
   kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
   return kbase;
 }
 private static KnowledgeBase readKnowledgeBase(String name) throws Exception {
   KnowledgeBuilderConfiguration kconf =
       KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration();
   kconf.setProperty("drools.dump.dir", "/home/kylin/work/tmp/974943");
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(kconf);
   kbuilder.add(ResourceFactory.newClassPathResource(name), ResourceType.DRL);
   KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
   kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
   return kbase;
 }
 public RulesManager() {
   final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(ResourceFactory.newClassPathResource("Car.drl", Car.class), ResourceType.DRL);
   if (kbuilder.hasErrors()) {
     throw new RuntimeException("Unable to compile \"Car.drl\".");
   }
   final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
   knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
   knowledgeBase.addKnowledgePackages(pkgs);
 }
  @Test
  public void testTMSwithQueries() {
    String str =
        ""
            + "package org.drools.test;\n"
            + "\n"
            + "global java.util.List list; \n"
            + "\n"
            + "declare Bean\n"
            + "    str : String\n"
            + "end\n"
            + "\n"
            + "query bean ( String $s )\n"
            + "    Bean(  $s ; )\n"
            + "end\n"
            + "\n"
            + "\n"
            + "rule \"init\"\n"
            + "when\n"
            + "then\n"
            + "    insert( new Bean(\"AAA\") );\n"
            + "    insert( \"x\" );\n"
            + "end\n"
            + "\n"
            + "rule \"LogicIn\"\n"
            + "when\n"
            + "    String( this == \"x\" )\n"
            + "    ?bean(  \"AAA\" ; )\n"
            + "then\n"
            + "    insertLogical(\"y\");\n"
            + "    retract(\"x\");\n"
            + "end "
            + "\n"
            + "rule \"Never\"\n"
            + "salience -999\n"
            + "when\n"
            + "    $s : String( this == \"y\" )\n"
            + "then\n"
            + "    list.add($s);\n"
            + "end";

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

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

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

    // System.err.println(reportWMObjects(kSession));
  }
 private KnowledgeBase loadKnowledgeBaseFromString(String drlSource) {
   KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   knowledgeBuilder.add(
       ResourceFactory.newByteArrayResource(drlSource.getBytes()), ResourceType.DRL);
   if (knowledgeBuilder.hasErrors()) {
     System.err.print(knowledgeBuilder.getErrors().toString());
   }
   KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
   knowledgeBase.addKnowledgePackages(knowledgeBuilder.getKnowledgePackages());
   return knowledgeBase;
 }
Ejemplo n.º 23
0
  @Test
  public void testModifyDirectory() throws IOException, InterruptedException {
    // adds 2 files to a dir and executes then adds one and removes one and
    // detects changes
    File f1 = fileManager.write("rule1.drl", createDefaultRule("rule1"));

    File f2 = fileManager.write("rule2.drl", createDefaultRule("rule2"));

    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='" + f1.getParentFile().toURI().toURL() + "' type='DRL' />";
    xml += "    </add> ";
    xml += "</change-set>";
    File fxml = fileManager.write("changeset", "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"));

    list.clear();

    fileManager.write("rule3.drl", createDefaultRule("rule3"));
    fileManager.deleteFile(f1);

    scan(kagent);

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

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

    kagent.dispose();
  }
Ejemplo n.º 24
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;
  }
 public StatefulKnowledgeSession loadRules(String packageName, String version) {
   try {
     RulePackageDownloader downloader = new RulePackageDownloader(getRuleDirectory(), "", "");
     KnowledgeBase kb = KnowledgeBaseFactory.newKnowledgeBase();
     kb.addKnowledgePackages(downloader.download(packageName, version));
     StatefulKnowledgeSession session = kb.newStatefulKnowledgeSession();
     this.session = session;
     return session;
   } catch (Exception e) {
     throw new RuntimeException("Unable to compile rules - more details in cause:", e);
   }
 }
  private StatefulKnowledgeSession disposeAndReloadSession(
      StatefulKnowledgeSession ksession, KnowledgeBase kbase) {
    int ksessionId = ksession.getId();
    ksession.dispose();

    final KnowledgeSessionConfiguration conf =
        KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    conf.setOption(ClockTypeOption.get(ClockType.PSEUDO_CLOCK.getId()));

    StatefulKnowledgeSession newksession =
        JPAKnowledgeService.loadStatefulKnowledgeSession(
            ksessionId, kbase, conf, createEnvironment());
    return newksession;
  }
Ejemplo n.º 27
0
 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;
 }
Ejemplo n.º 28
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;
 }
  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());
  }
Ejemplo n.º 30
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));
  }