Example #1
0
  private KieBase createKnowledgeBase() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource(
            "memory/BPMN2-RuleTaskWithInsertProcessInstance.bpmn2"),
        ResourceType.BPMN2);
    kbuilder.add(
        ResourceFactory.newClassPathResource("memory/ProcessInstanceRule.drl"), ResourceType.DRL);

    if (!kbuilder.getErrors().isEmpty()) {
      Iterator<KnowledgeBuilderError> errIter = kbuilder.getErrors().iterator();
      while (errIter.hasNext()) {
        KnowledgeBuilderError err = errIter.next();
        StringBuilder lines = new StringBuilder("");
        if (err.getLines().length > 0) {
          lines.append(err.getLines()[0]);
          for (int i = 1; i < err.getLines().length; ++i) {
            lines.append(", " + err.getLines()[i]);
          }
        }
        logger.warn(err.getMessage() + " (" + lines.toString() + ")");
      }
      throw new IllegalArgumentException("Errors while parsing knowledge base");
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

    return kbase;
  }
Example #2
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());
  }
Example #3
0
  @Test
  public void invokePmmlWithTrait() {

    String extraDrl =
        "package org.drools.pmml.pmml_4_2.test;"
            + ""
            + "import org.drools.core.factmodel.traits.Entity;"
            + ""
            + "rule \"Init\" "
            + "when "
            + "   $s : String( this == \"trigger\" ) "
            + "then "
            + "   System.out.println( \"Trig\" ); "
            + "   Entity o = new Entity(); "
            + "   insert( o ); \n"
            + ""
            +
            // don an object with the default input trait ( modelName + "Input" )
            // both soft and hard fields will be used to feed data into the model
            ""
            + "   MockColdTrait input = don( o, MockColdTrait.class ); "
            + "   modify( input ) { "
            + "       setTemp( 22.0 );"
            + "   } "
            + "end "
            + ""
            + ""
            + "rule Log when $x : MockColdTrait() then System.out.println( \"IN \" + $x ); end "
            + "rule Log2 when $x : Cold() then System.out.println( \"OUT \" + $x ); end ";

    KieServices ks = KieServices.Factory.get();
    KieFileSystem kfs = ks.newKieFileSystem();

    kfs.write(ResourceFactory.newClassPathResource(pmmlSource).setResourceType(ResourceType.PMML));
    kfs.write(
        ResourceFactory.newByteArrayResource(extraDrl.getBytes())
            .setSourcePath("rules.drl")
            .setResourceType(ResourceType.DRL));

    Results res = ks.newKieBuilder(kfs).buildAll().getResults();
    if (res.hasMessages(Message.Level.ERROR)) {
      System.out.println(res.getMessages(Message.Level.ERROR));
    }
    assertEquals(0, res.getMessages(Message.Level.ERROR).size());

    KieSession kSession =
        ks.newKieContainer(ks.getRepository().getDefaultReleaseId()).newKieSession();

    kSession.insert("trigger");
    kSession.fireAllRules();

    System.out.println(reportWMObjects(kSession));

    QueryResults qrs = kSession.getQueryResults("Cold", "MockCold", Variable.v);
    assertTrue(qrs.iterator().hasNext());
    Object val = qrs.iterator().next().get("$result");
    Assert.assertEquals(0.56, val);
  }
Example #4
0
  public ChecklistUI() {
    setSize(new Dimension(400, 300));
    setTitle("Checklist");
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    initializeComponent();

    JBPMHelper.startH2Server();
    JBPMHelper.setupDataSource();
    DefaultRuntimeEnvironment environment = new DefaultRuntimeEnvironment();
    environment.setUserGroupCallback(
        new UserGroupCallback() {
          public List<String> getGroupsForUser(
              String userId, List<String> groupIds, List<String> allExistingGroupIds) {
            List<String> result = new ArrayList<String>();
            if ("actor4".equals(userId)) {
              result.add("group1");
            }
            return result;
          }

          public boolean existsUser(String arg0) {
            return true;
          }

          public boolean existsGroup(String arg0) {
            return true;
          }
        });
    environment.addAsset(
        ResourceFactory.newClassPathResource("checklist/SampleChecklistProcess.bpmn"),
        ResourceType.BPMN2);
    checklistManager = new DefaultChecklistManager(environment);
  }
  protected KieSession createKnowledgeSession(String processFile) throws Exception {
    KieServices ks = KieServices.Factory.get();
    KieRepository kr = ks.getRepository();
    KieFileSystem kfs = ks.newKieFileSystem();
    if (processFile != null) {
      Resource process = ResourceFactory.newClassPathResource(processFile);
      kfs.write(process);
    }

    KieBuilder kb = ks.newKieBuilder(kfs);
    kb.buildAll();

    if (kb.getResults().hasMessages(Level.ERROR)) {
      throw new RuntimeException("Build Errors:\n" + kb.getResults().toString());
    }

    KieContainer kContainer = ks.newKieContainer(kr.getDefaultReleaseId());
    KieBase kbase = kContainer.getKieBase();

    Environment env = EnvironmentFactory.newEnvironment();

    Properties defaultProps = new Properties();
    defaultProps.setProperty(
        "drools.processSignalManagerFactory", DefaultSignalManagerFactory.class.getName());
    defaultProps.setProperty(
        "drools.processInstanceManagerFactory",
        DefaultProcessInstanceManagerFactory.class.getName());
    SessionConfiguration conf = new SessionConfiguration(defaultProps);

    KieSession ksession = (StatefulKnowledgeSession) kbase.newKieSession(conf, env);
    return ksession;
  }
  /**
   * Test that illustrates that jobs are persisted and survives server restart and as soon as
   * GlobalTimerService is active jobs are fired NOTE: this test is disabled by default as it
   * requires real db (not in memory) and test to be executed separately each with new jvm process
   */
  @Test
  @Ignore
  public void testContinueGlobalTestService() throws Exception {
    SimpleRuntimeEnvironment environment = new DefaultRuntimeEnvironment();

    environment.addAsset(
        ResourceFactory.newClassPathResource("BPMN2-IntermediateCatchEventTimerCycle2.bpmn2"),
        ResourceType.BPMN2);
    environment.addToConfiguration(
        "drools.timerService", "org.jbpm.process.core.timer.impl.RegisteredTimerServiceDelegate");
    RuntimeManager manger =
        RuntimeManagerFactory.Factory.get().newSingletonRuntimeManager(environment);

    // build GlobalTimerService instance

    TimerService globalTs = new GlobalTimerService(manger, globalScheduler);
    // and register it in the registry under 'default' key
    TimerServiceRegistry.getInstance().registerTimerService("default", globalTs);
    // prepare listener to assert results
    final List<Long> timerExporations = new ArrayList<Long>();
    ProcessEventListener listener =
        new DefaultProcessEventListener() {

          @Override
          public void afterNodeLeft(ProcessNodeLeftEvent event) {
            if (event.getNodeInstance().getNodeName().equals("timer")) {
              timerExporations.add(event.getProcessInstance().getId());
            }
          }
        };

    Thread.sleep(5000);
  }
Example #7
0
  @Test
  public void testTimerStartDateISO() throws Exception {

    byte[] content =
        IoUtils.readBytesFromInputStream(
            this.getClass().getResourceAsStream("/BPMN2-TimerStartDate.bpmn2"));
    String processContent = new String(content, "UTF-8");

    DateTime now = new DateTime(System.currentTimeMillis());
    now = now.plus(2000);

    processContent = processContent.replaceFirst("#\\{date\\}", now.toString());
    Resource resource = ResourceFactory.newReaderResource(new StringReader(processContent));
    resource.setSourcePath("/BPMN2-TimerStartDate.bpmn2");
    resource.setTargetPath("/BPMN2-TimerStartDate.bpmn2");
    KieBase kbase = createKnowledgeBaseFromResources(resource);

    ksession = createKnowledgeSession(kbase);
    final List<Long> list = new ArrayList<Long>();
    ksession.addEventListener(
        new DefaultProcessEventListener() {
          public void afterProcessStarted(ProcessStartedEvent event) {
            list.add(event.getProcessInstance().getId());
          }
        });
    assertEquals(0, list.size());
    Thread.sleep(3000);
    assertEquals(1, list.size());
  }
Example #8
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();
  }
Example #9
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));
  }
  @Before
  public void init() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    String ruleFormat =
        "import java.util.Map import java.util.List import com.formbuilder.rule.Evaluator rule \"Values present\" when $rule: Evaluator(!this.eval()) $list: List() then $list.add(\"One of %s cannot be empty\"); end";
    String className =
        Character.toString(ruleString.charAt(0)).toUpperCase() + ruleString.substring(1);

    ruleObj = (Rule) Class.forName("com.formbuilder.rule." + className + "Rule").newInstance();
    ruleObj.setDroolString(ruleFormat);
    inputs = "name, project_type, start_date, end_date";
    ruleObj.setNameListToValidate(inputs);
    Resource myResource =
        ResourceFactory.newReaderResource(new StringReader(ruleObj.computeDroolsRule()));
    kbuilder.add(myResource, ResourceType.DRL);

    // Check the builder for errors
    if (kbuilder.hasErrors()) {
      System.out.println("******" + kbuilder.getErrors().toString());
      throw new RuntimeException("Unable to compile drl\".");
    }

    // get the compiled packages (which are serializable)
    pkgs = kbuilder.getKnowledgePackages();

    // add the packages to a knowledgebase (deploy the knowledge packages).
    kbase.addKnowledgePackages(pkgs);
    // Get Drools for the same rules

  }
Example #11
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 #12
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 #13
0
  @Test
  public void testSizeCheckInObject() {
    String str =
        ""
            + "package org.drools.compiler.test \n"
            + "import "
            + Triangle.class.getCanonicalName()
            + "\n"
            +
            // "import " + Address.class.getCanonicalName() + "\n" +
            "global java.util.List list \n"
            + "rule \"show\" \n"
            + "when  \n"
            + "    $m : Triangle( deliveries.size == 0) \n"
            + "then \n"
            + "    list.add('r1'); \n"
            + "end \n";
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL);

    if (kbuilder.hasErrors()) {
      System.out.println(kbuilder.getErrors().toString());
      fail(kbuilder.getErrors().toString());
    }
  }
Example #14
0
  /**
   * Creates default configuration of <code>RuntimeManager</code> with given <code>strategy</code>
   * and all <code>resources</code> being added to knowledge base. <br>
   * There should be only one <code>RuntimeManager</code> created during single test.
   *
   * @param strategy - selected strategy of those that are supported
   * @param resources - resources that shall be added to knowledge base
   * @param identifier - identifies the runtime manager
   * @return new instance of RuntimeManager
   */
  protected RuntimeManager createRuntimeManager(
      Strategy strategy, Map<String, ResourceType> resources, String identifier) {
    if (manager != null) {
      throw new IllegalStateException("There is already one RuntimeManager active");
    }

    RuntimeEnvironmentBuilder builder = null;
    if (!setupDataSource) {
      builder =
          RuntimeEnvironmentBuilder.getEmpty()
              .addConfiguration(
                  "drools.processSignalManagerFactory", DefaultSignalManagerFactory.class.getName())
              .addConfiguration(
                  "drools.processInstanceManagerFactory",
                  DefaultProcessInstanceManagerFactory.class.getName());
    } else if (sessionPersistence) {
      builder = RuntimeEnvironmentBuilder.getDefault().entityManagerFactory(emf);
    } else {
      builder = RuntimeEnvironmentBuilder.getDefaultInMemory();
    }
    builder.userGroupCallback(new JBossUserGroupCallbackImpl("classpath:/usergroups.properties"));

    for (Map.Entry<String, ResourceType> entry : resources.entrySet()) {
      builder.addAsset(ResourceFactory.newClassPathResource(entry.getKey()), entry.getValue());
    }

    return createRuntimeManager(strategy, resources, builder.get(), identifier);
  }
Example #15
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());
  }
  @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());
  }
Example #17
0
  private KnowledgeBase buildKnowledgeBase(String ruleName, String rule) {
    String str = "";
    str += "package org.kie \n";
    str += "import " + A.class.getCanonicalName() + "\n";
    str += "import " + B.class.getCanonicalName() + "\n";
    str += "import " + C.class.getCanonicalName() + "\n";
    str += "import " + D.class.getCanonicalName() + "\n";
    str += "import " + E.class.getCanonicalName() + "\n";
    str += "global java.util.List list \n";

    int i = 0;
    str += "rule " + ruleName + "  when \n";
    str += rule;
    str += "then \n";
    str += " list.add( kcontext.getMatch() );\n";
    str += "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

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

    KieBaseConfiguration kconf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kconf.setOption(RuleEngineOption.PHREAK);

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kconf);
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    return kbase;
  }
Example #18
0
  private Collection<KnowledgePackage> buildKnowledgePackage(String ruleName, String rule) {
    String str = "";
    str += "package org.kie \n";
    str += "import " + A.class.getCanonicalName() + "\n";
    str += "import " + B.class.getCanonicalName() + "\n";
    str += "import " + C.class.getCanonicalName() + "\n";
    str += "import " + D.class.getCanonicalName() + "\n";
    str += "import " + E.class.getCanonicalName() + "\n";
    str += "global java.util.List list \n";

    int i = 0;
    str += "rule " + ruleName + "  when \n";
    str += rule;
    str += "then \n";
    str += " list.add( kcontext.getMatch() );\n";
    str += "end \n";

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

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

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

    return kbuilder.getKnowledgePackages();
  }
Example #19
0
  @Test
  public void testTokensInString() {
    // should query antldr DFA63 class but don't know how
    String[] operators = {",", "=", "|=", "*"};
    // test various in consequence
    String strBegin =
        ""
            + "package org.kie \n"
            + "import org.drools.compiler.Cheese \n"
            + "dialect \"mvel\"\n"
            + "rule rule1 \n"
            + "when \n"
            + "$c:Cheese(type==\"swiss\") \n"
            + "then \n"
            + "modify($c){ type = \"swiss";

    String strEnd = "good\"};\n" + "end\n";
    StringBuffer failures = new StringBuffer();
    for (String oper : operators) {
      KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
      String rule = strBegin + oper + strEnd;
      System.out.print(rule);
      kbuilder.add(ResourceFactory.newByteArrayResource(rule.getBytes()), ResourceType.DRL);
      if (kbuilder.hasErrors()) {
        failures.append(kbuilder.getErrors().toString());
      }
    }
    String failStr = failures.toString();
    if (failStr.length() > 0) {
      fail(failStr);
    }
  }
Example #20
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));
  }
 private static KieSession createKieSession() {
   KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
   kbuilder.add(
       ResourceFactory.newClassPathResource("exceptions/ExceptionHandlingWithSignal.bpmn2"),
       ResourceType.BPMN2);
   KieBase kbase = kbuilder.newKnowledgeBase();
   return kbase.newKieSession();
 }
  private KnowledgeBase createBase() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newClassPathResource("processinstance/HelloWorld.rf"), ResourceType.DRF);
    assertFalse(kbuilder.getErrors().toString(), kbuilder.hasErrors());

    return kbuilder.newKnowledgeBase();
  }
Example #23
0
  @Test
  public void testDuplicateLocalVariableMVELConsequence() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newInputStreamResource(
            getClass().getResourceAsStream("test_DuplicateLocalVariableMVELConsequence.drl")),
        ResourceType.DRL);

    assertTrue(kbuilder.hasErrors());
  }
Example #24
0
  public static void setup() {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(
        ResourceFactory.newInputStreamResource(
            ExampleScenario.class.getResourceAsStream(FILE_NAME_RULES)),
        ResourceType.DRL);

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    wm = kbase.newStatefulKnowledgeSession();
  }
  KieBase loadRules(String drools) {
    KnowledgeBase kieBase = KnowledgeBaseFactory.newKnowledgeBase();

    Resource droolsResource = ResourceFactory.newByteArrayResource(drools.getBytes());

    KnowledgeBuilder kBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kBuilder.add(droolsResource, org.kie.api.io.ResourceType.DRL);
    validate(kBuilder);

    kieBase.addKnowledgePackages(kBuilder.getKnowledgePackages());
    return kieBase;
  }
  @Produces
  @Singleton
  @PerRequest
  @PerProcessInstance
  public RuntimeEnvironment produceEnvironment(EntityManagerFactory emf) {

    RuntimeEnvironment environment =
        RuntimeEnvironmentBuilder.Factory.get()
            .newDefaultBuilder()
            .entityManagerFactory(emf)
            .userGroupCallback(getUserGroupCallback())
            .registerableItemsFactory(
                InjectableRegisterableItemsFactory.getFactory(
                    beanManager, new ManagedAuditEventBuilderImpl()))
            .addAsset(
                ResourceFactory.newClassPathResource("BPMN2-ScriptTask.bpmn2"), ResourceType.BPMN2)
            .addAsset(
                ResourceFactory.newClassPathResource("BPMN2-UserTask.bpmn2"), ResourceType.BPMN2)
            .get();
    return environment;
  }
Example #27
0
  private KnowledgeBase loadKnowledgeBaseFromString(String drl) {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newByteArrayResource(drl.getBytes()), ResourceType.DRL);

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

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    return kbase;
  }
  private void wrongTimerExpression(String timer) {
    String str = "";
    str += "package org.simple \n";
    str += "rule xxx \n";
    str += "  timer (" + timer + ") ";
    str += "when \n";
    str += "then \n";
    str += "end  \n";

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

    assertTrue(kbuilder.hasErrors());
  }
Example #29
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));
  }
Example #30
0
  private KnowledgeBase loadKnowledgeBase(String fileName) {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newClassPathResource(fileName, getClass()), ResourceType.DRL);
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if (errors.size() > 0) {
      for (KnowledgeBuilderError error : errors) {
        logger.warn(error.toString());
      }
      throw new IllegalArgumentException("Could not parse knowledge.");
    }
    assertFalse(kbuilder.hasErrors());

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    Collection<KnowledgePackage> knowledgePackages = kbuilder.getKnowledgePackages();
    kbase.addKnowledgePackages(knowledgePackages);
    return kbase;
  }