org.kie.api.KieBase Java Examples

The following examples show how to use org.kie.api.KieBase. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IntermediateEventTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
@Timeout(10)
public void testIntermediateTimerEventMI() throws Exception {
    NodeLeftCountDownProcessEventListener countDownListener = new NodeLeftCountDownProcessEventListener("After timer", 3);
    KieBase kbase = createKnowledgeBase("timer/BPMN2-IntermediateTimerEventMI.bpmn2");

    ksession = createKnowledgeSession(kbase);
    ksession.addEventListener(countDownListener);
    TestWorkItemHandler handler = new TestWorkItemHandler();

    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
    ProcessInstance processInstance = ksession.startProcess("defaultprocessid");
    assertProcessInstanceActive(processInstance);

    countDownListener.waitTillCompleted();
    assertProcessInstanceActive(processInstance.getId(), ksession);

    ksession.abortProcessInstance(processInstance.getId());

    assertProcessInstanceAborted(processInstance.getId(), ksession);
}
 
Example #2
Source File: NullSafeDereferencingTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testNullSafeNullComparisonReverse() {
    // DROOLS-82
    String str =
            "import org.drools.compiler.*;\n" +
            "rule R1 when\n" +
            "   Person( \"Main Street\".equalsIgnoreCase(address!.street) )\n" +
            "then\n" +
            "end";

    KieBase kbase = loadKnowledgeBaseFromString(str);
    KieSession ksession = kbase.newKieSession();
    ksession.insert(new Person("Mario", 38));

    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();
}
 
Example #3
Source File: IntermediateEventTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testConditionalBoundaryEventOnTask() throws Exception {
    KieBase kbase = createKnowledgeBase("BPMN2-BoundaryConditionalEventOnTask.bpmn2");
    ksession = createKnowledgeSession(kbase);
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task",
            new TestWorkItemHandler());
    ProcessInstance processInstance = ksession
            .startProcess("BoundarySignalOnTask");

    Person person = new Person();
    person.setName("john");
    ksession.insert(person);

    assertProcessInstanceFinished(processInstance, ksession);
    assertNodeTriggered(processInstance.getId(), "StartProcess",
            "User Task", "Boundary event", "Condition met", "End2");

}
 
Example #4
Source File: ParallelCompilationTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public KieBase call() throws Exception {
    final Reader source = new InputStreamReader(ParallelCompilationTest.class.getResourceAsStream(DRL_FILE));

    final Properties props = new Properties();
    props.setProperty("drools.dialect.java.compiler", "JANINO");
    props.setProperty("drools.dialect.java.compiler.lnglevel", "1.6");
    KieBase result;

    final KnowledgeBuilderConfiguration configuration = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(props, ParallelCompilationTest.class.getClass().getClassLoader());
    final KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder(configuration);

    Thread.sleep(Math.round(Math.random()*250));

    Resource newReaderResource = ResourceFactory.newReaderResource(source);
    //synchronized (RuleUtil.class)
    {
        builder.add(newReaderResource, ResourceType.DRL);
    }
    result = builder.newKieBase();

    return result;
}
 
Example #5
Source File: FlowTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiInstanceLoopCharacteristicsProcessWithOutput()
        throws Exception {
    KieBase kbase = createKnowledgeBaseWithoutDumper("BPMN2-MultiInstanceLoopCharacteristicsProcessWithOutput.bpmn2");
    ksession = createKnowledgeSession(kbase);
    Map<String, Object> params = new HashMap<String, Object>();
    List<String> myList = new ArrayList<String>();
    List<String> myListOut = new ArrayList<String>();
    myList.add("First Item");
    myList.add("Second Item");
    params.put("list", myList);
    params.put("listOut", myListOut);
    assertEquals(0, myListOut.size());
    ProcessInstance processInstance = ksession.startProcess(
            "MultiInstanceLoopCharacteristicsProcessWithOutput", params);
    assertProcessInstanceCompleted(processInstance);
    assertEquals(2, myListOut.size());

}
 
Example #6
Source File: JBRULESTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testJBRules2055() {
    final KieBase kbase = loadKnowledgeBase("test_JBRules2055.drl");
    final KieSession ksession = createKnowledgeSession(kbase);
    final List<String> results = new ArrayList<String>();
    ksession.setGlobal("results", results);
    ksession.insert(new Cheese("stilton"));
    ksession.insert(new Cheese("brie"));
    ksession.insert(new Cheese("muzzarella"));
    ksession.insert(new Person("bob", "stilton"));
    ksession.fireAllRules();
    assertEquals(2, results.size());
    assertEquals("stilton", results.get(0));
    assertEquals("brie", results.get(1));

}
 
Example #7
Source File: AgendaFilterTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
private void testAgendaFilter(final AgendaFilter agendaFilter, final String expectedMatchingRuleName) {
    final String str = "package org.drools.compiler\n" +
            "rule Aaa when then end\n" +
            "rule Bbb when then end\n";

    final KieBase kbase = loadKnowledgeBaseFromString(str);
    final KieSession ksession = createKnowledgeSession(kbase);

    final org.kie.api.event.rule.AgendaEventListener ael = mock(org.kie.api.event.rule.AgendaEventListener.class);
    ksession.addEventListener(ael);

    final int rules = ksession.fireAllRules(agendaFilter);
    assertEquals(1, rules);

    final ArgumentCaptor<org.kie.api.event.rule.AfterMatchFiredEvent> arg = ArgumentCaptor.forClass(org.kie.api.event.rule.AfterMatchFiredEvent.class);
    verify(ael).afterMatchFired(arg.capture());
    assertThat(arg.getValue().getMatch().getRule().getName()).isEqualTo(expectedMatchingRuleName);
}
 
Example #8
Source File: StructureRefTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultObjectStructureRef() throws Exception {

    String value = "simple text for testing";

    KieBase kbase = createKnowledgeBaseWithoutDumper("BPMN2-DefaultObjectStructureRef.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler workItemHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task",
            workItemHandler);
    ProcessInstance processInstance = ksession.startProcess("StructureRef");
    assertEquals(STATE_ACTIVE, processInstance.getState());

    Map<String, Object> res = new HashMap<>();
    res.put("testHT", value);
    ksession.getWorkItemManager().completeWorkItem(
            workItemHandler.getWorkItem().getId(), res);

    assertProcessInstanceCompleted(processInstance.getId(), ksession);
}
 
Example #9
Source File: JavaInvokerTest.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
@Test
public void testStaticMethod2() throws Exception {
    KieBase kbase = readKnowledgeBase();
    KieSession ksession = createSession(kbase);
    ksession.getWorkItemManager().registerWorkItemHandler("Java",
                                                          new JavaInvocationWorkItemHandler());
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("Class",
               "org.jbpm.process.workitem.java.MyJavaClass");
    params.put("Method",
               "staticMethod2");
    params.put("Object",
               new MyJavaClass());
    List<Object> parameters = new ArrayList<Object>();
    parameters.add("krisv");
    params.put("Parameters",
               parameters);
    ksession.startProcess("com.sample.bpmn.java",
                          params);
}
 
Example #10
Source File: IntermediateEventTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testConditionalBoundaryEventInterrupting() throws Exception {
    KieBase kbase = createKnowledgeBase("BPMN2-ConditionalBoundaryEventInterrupting.bpmn2");
    ksession = createKnowledgeSession(kbase);
    ksession.getWorkItemManager().registerWorkItemHandler("MyTask",
            new DoNothingWorkItemHandler());
    ProcessInstance processInstance = ksession
            .startProcess("ConditionalBoundaryEvent");
    assertProcessInstanceActive(processInstance);

    ksession = restoreSession(ksession, true);
    Person person = new Person();
    person.setName("john");
    ksession.insert(person);


    assertProcessInstanceFinished(processInstance, ksession);
    assertNodeTriggered(processInstance.getId(), "StartProcess", "Hello",
            "StartSubProcess", "Task", "BoundaryEvent", "Goodbye",
            "EndProcess");

}
 
Example #11
Source File: VariableTagsTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testProcessWithReadonlyVariable() throws Exception {
    KieBase kbase = createKnowledgeBase("variable-tags/approval-with-readonly-variable-tags.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler workItemHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", workItemHandler);
    
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("approver", "john");
    
    ProcessInstance processInstance = ksession.startProcess("approvals", parameters);
    assertTrue(processInstance.getState() == ProcessInstance.STATE_ACTIVE);        
    WorkItem workItem = workItemHandler.getWorkItem();
    assertNotNull(workItem);
            
    assertThrows(VariableViolationException.class, () -> ksession.getWorkItemManager().completeWorkItem(workItem.getId(), Collections.singletonMap("ActorId", "john")));
    
    ksession.abortProcessInstance(processInstance.getId());
    
    assertProcessInstanceFinished(processInstance, ksession);
    ksession.dispose();
}
 
Example #12
Source File: NullTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testNullBinding() throws Exception {
    final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase("test_nullBindings.drl"));
    final KieSession ksession = createKnowledgeSession(kbase);

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

    ksession.insert(new Person("bob"));
    ksession.insert(new Person(null));

    ksession.fireAllRules();

    assertEquals(1, list.size());

    assertEquals("OK", list.get(0));
}
 
Example #13
Source File: RuleMetadataTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsert() {
    String rule1 = "insert( new A(1, $bb, \"3\") );";
    KieBase kbase = getKnowledgeBase(rule1);
    RuleImpl rule = getRule(kbase, "R0");

    ConsequenceMetaData consequenceMetaData = rule.getConsequenceMetaData();
    assertEquals(1, consequenceMetaData.getStatements().size());
    ConsequenceMetaData.Statement statment = consequenceMetaData.getStatements().get(0);
    assertEquals(ConsequenceMetaData.Statement.Type.INSERT, statment.getType());
    assertEquals("org.drools.A", statment.getFactClassName());

    assertEquals(3, statment.getFields().size());
    ConsequenceMetaData.Field field1 = statment.getFields().get(0);
    assertEquals("a", field1.getName());
    assertEquals("1", field1.getValue());
    assertTrue(field1.isLiteral());
    ConsequenceMetaData.Field field2 = statment.getFields().get(1);
    assertEquals("b", field2.getName());
    assertEquals("$bb", field2.getValue());
    assertFalse(field2.isLiteral());
    ConsequenceMetaData.Field field3 = statment.getFields().get(2);
    assertEquals("c", field3.getName());
    assertEquals("\"3\"", field3.getValue());
    assertTrue(field3.isLiteral());
}
 
Example #14
Source File: PropertySpecificTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testBetaAfterBetaWithWatch() {
    String rule1 = "$b : B(a == 15) @watch(k) A(i == $b.j) @watch(b, c) C()";
    KieBase kbase = getKnowledgeBase(rule1);
    InternalWorkingMemory wm = ((InternalWorkingMemory)kbase.newKieSession());

    ObjectTypeNode otnA = getObjectTypeNode(kbase, "A" );
    Class classType = ((ClassObjectType) otnA.getObjectType()).getClassType();
    ObjectTypeNode otnC = getObjectTypeNode(kbase, "C" );
    List<String> sp = getSettableProperties(wm, otnA);

    BetaNode betaNodeA = ( BetaNode ) otnA.getObjectSinkPropagator().getSinks()[0];
    assertEquals( calculatePositiveMask(classType, list("i", "b", "c"), sp), betaNodeA.getRightDeclaredMask() );
    assertEquals( calculatePositiveMask(classType, list("i", "b", "c"), sp), betaNodeA.getRightInferredMask() );
    assertEquals( calculatePositiveMask(classType, list("j", "k"), sp), betaNodeA.getLeftDeclaredMask() );
    assertEquals( calculatePositiveMask(classType, list("a", "j", "k"), sp), betaNodeA.getLeftInferredMask() );

    BetaNode betaNodeC = ( BetaNode ) otnC.getObjectSinkPropagator().getSinks()[0];
    assertEquals( EmptyBitMask.get(), betaNodeC.getRightDeclaredMask());
    assertEquals( EmptyBitMask.get(), betaNodeC.getRightInferredMask() );
    assertEquals( AllSetBitMask.get(), betaNodeC.getLeftDeclaredMask() );
    assertEquals( AllSetBitMask.get(), betaNodeC.getLeftInferredMask() );
}
 
Example #15
Source File: RecursiveQueryBenchmark.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static long[] execTest(KieBase kbase, int n, boolean isRelational) {
    KieSession ksession = kbase.newKieSession();

    Node root = generateTree( ksession, n, isRelational );

    List list = new ArrayList();
    long start = System.nanoTime();
    ksession.getQueryResults( "findNodesWithValue", isRelational ? root.getId() : root, 0, list );
    ksession.fireAllRules();
    long[] result = new long[]{ (System.nanoTime() - start) };
    //System.out.println( list.size() );

    ksession.dispose();

    return result;
}
 
Example #16
Source File: StandaloneBPMNProcessTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
@Disabled
public void testExclusiveSplitXPath() throws Exception {
    KieBase kbase = createKnowledgeBase("BPMN2-ExclusiveSplitXPath.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    
    ksession.getWorkItemManager().registerWorkItemHandler("Email", new SystemOutWorkItemHandler());
    Document document = DocumentBuilderFactory
            .newInstance()
            .newDocumentBuilder()
            .parse(new ByteArrayInputStream(
                    "<myDocument><chapter1>BlaBla</chapter1><chapter2>MoreBlaBla</chapter2></myDocument>".getBytes()));
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("x", document);
    params.put("y", "SomeString");
    ProcessInstance processInstance = ksession.startProcess("com.sample.test", params);
    assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_COMPLETED);
}
 
Example #17
Source File: ActivityTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Disabled
@Test
public void testDMNBusinessRuleTaskByDecisionName()throws Exception {
    KieBase kbase = createKnowledgeBaseWithoutDumper(
            "dmn/BPMN2-BusinessRuleTaskDMNByDecisionName.bpmn2", "dmn/0020-vacation-days.dmn");
    ksession = createKnowledgeSession(kbase);
    // first run 16, 1 and expected days is 5
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("age", 16);
    params.put("yearsOfService", 1);
    ProcessInstance processInstance = ksession.startProcess("BPMN2-BusinessRuleTask", params);

    assertProcessInstanceFinished(processInstance, ksession);
    BigDecimal vacationDays = (BigDecimal) ((WorkflowProcessInstance) processInstance).getVariable("vacationDays");
    assertEquals(BigDecimal.valueOf(5), vacationDays);
}
 
Example #18
Source File: StrEvaluatorTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testStrEndsWith() {
    KieBase kbase = readKnowledgeBase();
    KieSession ksession = createKnowledgeSession(kbase);
    try {
        List list = new ArrayList();
        ksession.setGlobal( "list", list );

        RoutingMessage m = new RoutingMessage();
        m.setRoutingValue("messageBody:R2");

        ksession.insert(m);
        ksession.fireAllRules();
        assertTrue(list.size() == 4);

        assertTrue( list.get(0).equals("Message ends with R2") );
        assertTrue( list.get(1).equals("Message length is not 17") );
        assertTrue( list.get(2).equals("Message does not start with R2") );
        assertTrue( list.get(3).equals("Message does not end with R1") );
    } finally {
        ksession.dispose();
    }
}
 
Example #19
Source File: IntermediateEventTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
@Timeout(10)
public void testIntermediateTimerParallelGateway() throws Exception {
    NodeLeftCountDownProcessEventListener countDownListener = new NodeLeftCountDownProcessEventListener("Timer1", 1);
    NodeLeftCountDownProcessEventListener countDownListener2 = new NodeLeftCountDownProcessEventListener("Timer2", 1);
    NodeLeftCountDownProcessEventListener countDownListener3 = new NodeLeftCountDownProcessEventListener("Timer3", 1);
    KieBase kbase = createKnowledgeBase("timer/BPMN2-IntermediateTimerParallelGateway.bpmn2");

    ksession = createKnowledgeSession(kbase);
    ksession.addEventListener(countDownListener);
    ksession.addEventListener(countDownListener2);
    ksession.addEventListener(countDownListener3);
    TestWorkItemHandler handler = new TestWorkItemHandler();

    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);
    ProcessInstance processInstance = ksession.startProcess("Evaluation.timer-parallel");
    assertProcessInstanceActive(processInstance);

    countDownListener.waitTillCompleted();
    countDownListener2.waitTillCompleted();
    countDownListener3.waitTillCompleted();
    assertProcessInstanceCompleted(processInstance.getId(), ksession);

}
 
Example #20
Source File: AlphaNodeTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void test3Alpha() {
    String str =
            "import org.drools.compiler.Person\n" +
            "rule R1 when\n" +
            "  $p : Person(name == \"Mario\")\n" +
            "then\n" +
            "  modify($p) { setAge(2) }" +
            "  modify($p) { setAge(2) }" +
            "end\n" +
            "rule R3 when\n" +
            "  $p : Person(age > 1)\n" +
            "then\n" +
            "end\n";

    KieBase kbase = loadKnowledgeBaseFromString( str );
    KieSession ksession = kbase.newKieSession();

    ksession.insert( new Person( "Mario", 0 ) );
    assertEquals( 2, ksession.fireAllRules() );
}
 
Example #21
Source File: IntermediateEventTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
@Disabled("Transfomer has been disabled")
public void testMessageIntermediateThrowWithTransformation() throws Exception {
    KieBase kbase = createKnowledgeBaseWithoutDumper("BPMN2-IntermediateThrowEventMessageWithTransformation.bpmn2");
    ksession = createKnowledgeSession(kbase);
    final StringBuffer messageContent = new StringBuffer();
    ksession.getWorkItemManager().registerWorkItemHandler("Send Task",
            new SendTaskHandler(){

	@Override
	public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
		// collect message content for verification
		messageContent.append(workItem.getParameter("Message"));
		super.executeWorkItem(workItem, manager);
	}

    });
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("x", "MyValue");
    ProcessInstance processInstance = ksession.startProcess(
            "MessageIntermediateEvent", params);
    assertProcessInstanceCompleted(processInstance);

    assertThat(messageContent.toString()).isEqualTo("MYVALUE");

}
 
Example #22
Source File: NullTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testArithmeticExpressionWithNull() {
    // JBRULES-3568
    final String str = "import " + PrimitiveBean.class.getCanonicalName() + ";\n" +
            "rule R when\n" +
            "   PrimitiveBean(primitive/typed > 0.7)\n" +
            "then\n" +
            "end";

    final KieBase kbase = loadKnowledgeBaseFromString(str);
    final KieSession ksession = kbase.newKieSession();

    ksession.insert(new PrimitiveBean(0.9, 1.1));
    ksession.insert(new PrimitiveBean(0.9, null));
    assertEquals(1, ksession.fireAllRules());
    ksession.dispose();
}
 
Example #23
Source File: InlineCastTest.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Test
public void testInlineCastWithBinding() throws Exception {
    String str = "import org.drools.compiler.*;\n" +
            "rule R1 when\n" +
            "   Person( name == \"mark\", $country : address#LongAddress.country == \"uk\" )\n" +
            "then\n" +
            "end\n";

    KieBase kbase = loadKnowledgeBaseFromString(str);
    KieSession ksession = kbase.newKieSession();

    Person mark1 = new Person("mark");
    mark1.setAddress(new LongAddress("uk"));
    ksession.insert(mark1);

    Person mark2 = new Person("mark");
    ksession.insert(mark2);

    Person mark3 = new Person("mark");
    mark3.setAddress(new Address());
    ksession.insert(mark3);

    assertEquals(1, ksession.fireAllRules());
    ksession.dispose();
}
 
Example #24
Source File: ActivityTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompositeProcessWithDIGraphical() throws Exception {
    KieBase kbase = createKnowledgeBase("BPMN2-CompositeProcessWithDIGraphical.bpmn2");
    ksession = createKnowledgeSession(kbase);
    ProcessInstance processInstance = ksession.startProcess("Composite");
    assertProcessInstanceCompleted(processInstance);
}
 
Example #25
Source File: StandaloneBPMNProcessTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testMinimalProcess() throws Exception {
    KieBase kbase = createKnowledgeBase("BPMN2-MinimalProcess.bpmn2");
    KieSession ksession = createKnowledgeSession(kbase);
    ProcessInstance processInstance = ksession.startProcess("Minimal");
    assertThat(processInstance.getState()).isEqualTo(ProcessInstance.STATE_COMPLETED);
}
 
Example #26
Source File: RulesDeployer.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void deploy(EngineDeployment deployment, Map<String, Object> deploymentSettings) {
    LOGGER.debug("Processing rules deployment {}", deployment.getName());

    KnowledgeBuilder knowledgeBuilder = null;

    DeploymentManager deploymentManager = CommandContextUtil.getProcessEngineConfiguration().getDeploymentManager();

    Map<String, EngineResource> resources = deployment.getResources();
    for (String resourceName : resources.keySet()) {
        if (resourceName.endsWith(".drl")) { // is only parsing .drls sufficient? what about other rule dsl's? (@see ResourceType)
            LOGGER.info("Processing rules resource {}", resourceName);
            if (knowledgeBuilder == null) {
                knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
            }
            EngineResource resourceEntity = resources.get(resourceName);
            byte[] resourceBytes = resourceEntity.getBytes();
            Resource droolsResource = ResourceFactory.newByteArrayResource(resourceBytes);
            knowledgeBuilder.add(droolsResource, ResourceType.DRL);
        }
    }

    if (knowledgeBuilder != null) {
        KieBase kieBase = knowledgeBuilder.newKieBase();
        deploymentManager.getKnowledgeBaseCache().add(deployment.getId(), kieBase);
    }
}
 
Example #27
Source File: MarshallingTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testAccumulateSessionSerialization() throws Exception {
    KieBase kbase = loadKnowledgeBase("../test_AccumulateSerialization.drl" );
    KieSession ksession = kbase.newKieSession();

    final List<Number> results = new ArrayList<Number>();

    ksession.setGlobal( "results",
                        results );

    ksession.insert( new Cheese( "stilton",
                                 10 ) );
    ksession.insert( new Cheese( "brie",
                                 5 ) );
    ksession.insert( new Cheese( "provolone",
                                 150 ) );
    ksession.insert( new Cheese( "brie",
                                 20 ) );
    ksession.insert( new Person( "Bob",
                                 "brie" ) );

    ksession = getSerialisedStatefulKnowledgeSession( ksession,
                                                      true );

    ksession.fireAllRules();

    assertEquals( 1,
                  results.size() );
    assertEquals( 25,
                  results.get( 0 ).intValue() );
}
 
Example #28
Source File: ErrorEventTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testErrorBoundaryEventOnEntry() throws Exception {
    KieBase kbase = createKnowledgeBase("BPMN2-BoundaryErrorEventCatchingOnEntryException.bpmn2");
    ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler handler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task",handler);
    
    ProcessInstance processInstance = ksession
        .startProcess("BoundaryErrorEventOnEntry");
    assertProcessInstanceActive(processInstance.getId(), ksession);
    assertEquals(1, handler.getWorkItems().size());
}
 
Example #29
Source File: IntermediateEventTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignalBoundaryEvent() throws Exception {
    KieBase kbase = createKnowledgeBase(
            "BPMN2-BoundarySignalEventOnTaskbpmn2.bpmn",
            "BPMN2-IntermediateThrowEventSignal.bpmn2");
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler handler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task",
            handler);
    ProcessInstance processInstance = ksession
            .startProcess("BoundarySignalOnTask");
    
    Set<EventDescription<?>> eventDescriptions = processInstance.getEventDescriptions();
    assertThat(eventDescriptions)
        .hasSize(2)
        .extracting("event").contains("MySignal");
    assertThat(eventDescriptions)
        .extracting("eventType").contains("signal");
    assertThat(eventDescriptions)            
        .extracting("processInstanceId").contains(processInstance.getId());
    assertThat(eventDescriptions)
        .filteredOn("eventType", "signal")
        .hasSize(1)
        .extracting("properties", Map.class)
        .anyMatch(m -> m.containsKey("AttachedToID") && m.containsKey("AttachedToName"));
           
    ProcessInstance processInstance2 = ksession
            .startProcess("SignalIntermediateEvent");
    assertProcessInstanceFinished(processInstance2, ksession);

    assertProcessInstanceFinished(processInstance, ksession);
}
 
Example #30
Source File: MultithreadTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassLoaderRace() throws InterruptedException {

    final String drl = "package org.drools.integrationtests;\n" +
            "" +
            "rule \"average temperature\"\n" +
            "when\n" +
            " $avg := Number( ) from accumulate ( " +
            "      $x : Integer ( ); " +
            "      average ($x) )\n" +
            "then\n" +
            "  System.out.println( $avg );\n" +
            "end\n" +
            "\n";

    final KieBase kbase = loadKnowledgeBaseFromString(drl);
    final KieSession session = kbase.newKieSession();

    final Thread t = new Thread(session::fireUntilHalt);
    t.start();
    try {
        session.fireAllRules();

        for (int j = 0; j < 100; j++) {
            session.insert(j);
        }
        Thread.sleep(1000);
    } finally {
        session.halt();
        session.dispose();
    }
}