@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"));
  }
  private void testRulesFirst(StatelessKnowledgeSession session) {
    RulesInvocationCounter counter = new RulesInvocationCounter();
    session.addEventListener(counter);

    EasyMock.reset(service);

    session.setGlobal("itemService", service);

    Item item1 = new Item();
    item1.setName("My test item1 name");
    item1.setPrice(1);
    service.equal(item1, 1);

    Item item5 = new Item();
    item5.setName("My test item5 name");
    item5.setPrice(5);
    service.equal(item5, 5);

    Item item6 = new Item();
    item6.setName("My test item6 name");
    item6.setPrice(12);

    EasyMock.replay(service);

    session.execute(item1);
    Assert.assertEquals(counter.getCounter(), 1);
    session.execute(item5);
    Assert.assertEquals(counter.getCounter(), 2);
    session.execute(item6);
    Assert.assertEquals(counter.getCounter(), 2);

    EasyMock.verify(service);
  }
  @Test
  public void testInsertObject() throws Exception {
    String str = "";
    str += "package org.drools \n";
    str += "import org.drools.Cheese \n";
    str += "rule rule1 \n";
    str += "  when \n";
    str += "    $c : Cheese() \n";
    str += " \n";
    str += "  then \n";
    str += "    $c.setPrice( 30 ); \n";
    str += "end\n";

    Cheese stilton = new Cheese("stilton", 5);

    StatelessKnowledgeSession ksession =
        getSession2(ResourceFactory.newByteArrayResource(str.getBytes()));
    GenericCommand cmd = (GenericCommand) CommandFactory.newInsert(stilton, "outStilton");
    BatchExecutionCommandImpl batch =
        new BatchExecutionCommandImpl(Arrays.asList(new GenericCommand<?>[] {cmd}));

    ExecutionResults result = (ExecutionResults) ksession.execute(batch);
    stilton = (Cheese) result.getValue("outStilton");
    assertEquals(30, stilton.getPrice());
  }
  @Test
  public void testArrayObjectAssert() throws Exception {
    StatelessKnowledgeSession session = getSession2("literal_rule_test.drl");

    final Cheese stilton = new Cheese("stilton", 5);

    session.execute(Arrays.asList(new Object[] {stilton}));

    assertEquals("stilton", list.get(0));
  }
  @Test
  public void testCollectionObjectAssert() throws Exception {
    StatelessKnowledgeSession session = getSession2("literal_rule_test.drl");

    final Cheese stilton = new Cheese("stilton", 5);

    List collection = new ArrayList();
    collection.add(stilton);
    session.execute(collection);

    assertEquals("stilton", list.get(0));
  }
  @Test
  public void testSetGlobal() throws Exception {
    String str = "";
    str += "package org.drools \n";
    str += "import org.drools.Cheese \n";
    str += "global java.util.List list1 \n";
    str += "global java.util.List list2 \n";
    str += "global java.util.List list3 \n";
    str += "rule rule1 \n";
    str += "  when \n";
    str += "    $c : Cheese() \n";
    str += " \n";
    str += "  then \n";
    str += "    $c.setPrice( 30 ); \n";
    str += "    list1.add( $c ); \n";
    str += "    list2.add( $c ); \n";
    str += "    list3.add( $c ); \n";
    str += "end\n";

    Cheese stilton = new Cheese("stilton", 5);
    List list1 = new ArrayList();
    List list2 = new ArrayList();
    List list3 = new ArrayList();

    StatelessKnowledgeSession ksession =
        getSession2(ResourceFactory.newByteArrayResource(str.getBytes()));
    Command setGlobal1 = CommandFactory.newSetGlobal("list1", list1);
    Command setGlobal2 = CommandFactory.newSetGlobal("list2", list2, true);
    Command setGlobal3 = CommandFactory.newSetGlobal("list3", list3, "outList3");
    Command insert = CommandFactory.newInsert(stilton);

    List cmds = new ArrayList();
    cmds.add(setGlobal1);
    cmds.add(setGlobal2);
    cmds.add(setGlobal3);
    cmds.add(insert);

    ExecutionResults result =
        (ExecutionResults) ksession.execute(CommandFactory.newBatchExecution(cmds));

    assertEquals(30, stilton.getPrice());

    assertNull(result.getValue("list1"));

    list2 = (List) result.getValue("list2");
    assertEquals(1, list2.size());
    assertSame(stilton, list2.get(0));

    list3 = (List) result.getValue("outList3");
    assertEquals(1, list3.size());
    assertSame(stilton, list3.get(0));
  }
Beispiel #7
0
  protected Collection<ReportItem> evaluate(Object... elements) {
    StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession();
    Collection<ReportItem> reportItems = new ArrayList<ReportItem>();

    List<Command<?>> commands = new ArrayList<Command<?>>();
    for (Object o : elements) {
      commands.add(CommandFactory.newInsert(o));
    }
    commands.add(CommandFactory.newFireAllRules());
    commands.add(CommandFactory.newQuery("reports", "getReports"));

    ExecutionResults results = ksession.execute(CommandFactory.newBatchExecution(commands));
    // System.out.println(results.getIdentifiers());

    QueryResults queryResults = (QueryResults) results.getValue("reports");
    for (QueryResultsRow result : queryResults) {
      reportItems.add((ReportItem) result.get("item"));
    }

    return reportItems;
  }
  private StatelessKnowledgeSession getSession2(Resource resource) throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(resource, ResourceType.DRL);

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

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

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

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

    session.setGlobal("list", this.list);
    session.setGlobal("cheesery", this.cheesery);
    return session;
  }
Beispiel #9
0
  public Main() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource("ContactLenses.drl", getClass()), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
      System.err.println(kbuilder.getErrors().toString());
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession();

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

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

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

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

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

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

    c = new ContactLenses("pre-presbyopic", "hypermetrope", "yes", "normal");
    ksession.execute(c);
    System.out.println("O paciente deve usar lente de contato? " + c.getContactLenses());
  }
  @Test
  public void testQuery() throws Exception {
    String str = "";
    str += "package org.drools.test  \n";
    str += "import org.drools.Cheese \n";
    str += "query cheeses \n";
    str += "    stilton : Cheese(type == 'stilton') \n";
    str += "    cheddar : Cheese(type == 'cheddar', price == stilton.price) \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());

    kbase = SerializationHelper.serializeObject(kbase);

    StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession();
    Cheese stilton1 = new Cheese("stilton", 1);
    Cheese cheddar1 = new Cheese("cheddar", 1);
    Cheese stilton2 = new Cheese("stilton", 2);
    Cheese cheddar2 = new Cheese("cheddar", 2);
    Cheese stilton3 = new Cheese("stilton", 3);
    Cheese cheddar3 = new Cheese("cheddar", 3);

    Set set = new HashSet();
    List list = new ArrayList();
    list.add(stilton1);
    list.add(cheddar1);
    set.add(list);

    list = new ArrayList();
    list.add(stilton2);
    list.add(cheddar2);
    set.add(list);

    list = new ArrayList();
    list.add(stilton3);
    list.add(cheddar3);
    set.add(list);

    List<Command> cmds = new ArrayList<Command>();
    cmds.add(CommandFactory.newInsert(stilton1));
    cmds.add(CommandFactory.newInsert(stilton2));
    cmds.add(CommandFactory.newInsert(stilton3));
    cmds.add(CommandFactory.newInsert(cheddar1));
    cmds.add(CommandFactory.newInsert(cheddar2));
    cmds.add(CommandFactory.newInsert(cheddar3));

    cmds.add(CommandFactory.newQuery("cheeses", "cheeses"));

    ExecutionResults batchResult =
        (ExecutionResults) ksession.execute(CommandFactory.newBatchExecution(cmds));

    org.drools.runtime.rule.QueryResults results =
        (org.drools.runtime.rule.QueryResults) batchResult.getValue("cheeses");
    assertEquals(3, results.size());
    assertEquals(2, results.getIdentifiers().length);
    Set newSet = new HashSet();
    for (org.drools.runtime.rule.QueryResultsRow result : results) {
      list = new ArrayList();
      list.add(result.get("stilton"));
      list.add(result.get("cheddar"));
      newSet.add(list);
    }
    assertEquals(set, newSet);
  }
Beispiel #11
0
  public Message process(Message message) throws ActionProcessingException {

    Document document = null;
    byte[] messageBodyBytes = null;

    Object messageBody = message.getBody().get();
    if (messageBody instanceof byte[]) {
      messageBodyBytes = (byte[]) messageBody;

      // parse document.
      ByteArrayInputStream tmp = new ByteArrayInputStream(messageBodyBytes);
      try {
        document = parser.parse(tmp);
      } catch (Exception e) {
        throw new ActionProcessingException("Exception parsing document.", e);
      }
    } else if (messageBody instanceof String) {
      messageBodyBytes = ((String) messageBody).getBytes();

      // parse document.
      ByteArrayInputStream tmp = new ByteArrayInputStream(messageBodyBytes);
      try {
        document = parser.parse(tmp);
      } catch (Exception e) {
        throw new ActionProcessingException("Exception parsing document.", e);
      }
    } else if (messageBody instanceof Document) {
      // just cast.
      document = (Document) messageBody;

      // get a byte[] from the document - TODO need to test this
      try {
        messageBodyBytes = nodeToString(document.getDocumentElement()).getBytes();
      } catch (TransformerException e) {
        throw new ActionProcessingException("Exception parsing document.", e);
      }
    }

    if (document != null) {
      LOG.debug("Document not null.");
      XmlMessagePayload payload = new XmlMessagePayload(document);

      // extract the index.
      StatelessKnowledgeSession ss = getKnowledgeBase().newStatelessKnowledgeSession();
      ss.execute(payload);

      Map<String, Object> indexFields = new HashMap<String, Object>();
      if (payload.getIndexes() != null) {
        for (BigDataIndex<?> bdi : payload.getIndexes()) {
          LOG.info("Extracted index: " + bdi);
          indexFields.put(bdi.getKey(), bdi.getValue());
        }
      }

      // persist the message and indexes
      String messageKey = UUID.randomUUID().toString();

      // save the message
      LOG.info("About to write message body for key " + messageKey);
      writePayload(messageKey, messageBodyBytes);
      LOG.info("Done writing message body for key " + messageKey);

      // now write indexes
      LOG.info("About to write message indexes for key " + messageKey);
      writeIndexes(indexFields, messageKey);

      try {
        getBean().addBytes(messageBodyBytes.length);
        getBean().addMessage();
      } catch (NamingException e) {
        LOG.error("Exception finding EJB.", e);
      }

    } else {
      LOG.warn("Did not find document.");
    }

    return message;
  }