Java Code Examples for org.kie.internal.runtime.StatefulKnowledgeSession#dispose()

The following examples show how to use org.kie.internal.runtime.StatefulKnowledgeSession#dispose() . 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
public void testSignalBoundaryEventOnSubprocessTakingDifferentPaths() throws Exception {
    KieBase kbase = createKnowledgeBase(
            "BPMN2-SignalBoundaryOnSubProcess.bpmn");
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);

    ProcessInstance processInstance = ksession.startProcess("jbpm.testing.signal");
    assertProcessInstanceActive(processInstance);

    ksession.signalEvent("continue", null, processInstance.getId());
    assertProcessInstanceFinished(processInstance, ksession);

    ksession.dispose();

    ksession = createKnowledgeSession(kbase);

    processInstance = ksession.startProcess("jbpm.testing.signal");
    assertProcessInstanceActive(processInstance);

    ksession.signalEvent("forward", null);
    assertProcessInstanceFinished(processInstance, ksession);

    ksession.dispose();
}
 
Example 2
Source File: JbpmSerializationHelper.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static StatefulKnowledgeSession getSerialisedStatefulKnowledgeSession(StatefulKnowledgeSession ksession,
                                                                                 ObjectMarshallingStrategy [] strategies,
                                                                                 boolean dispose) throws Exception {
       
        Marshaller marshaller = MarshallerFactory.newMarshaller( ksession.getKieBase(), strategies );
        
        final byte [] b1 = serializeKnowledgeSession(marshaller, ksession);
        StatefulKnowledgeSession ksession2 = deserializeKnowledgeSession(marshaller, b1);
       
        final byte[] b2 = serializeKnowledgeSession(marshaller, ksession2);

        // bytes should be the same.
        if ( !areByteArraysEqual( b1,
                                  b2 ) ) {
//            throw new IllegalArgumentException( "byte streams for serialisation test are not equal" );
        }

        ((StatefulKnowledgeSessionImpl) ksession2).setGlobalResolver( ((StatefulKnowledgeSessionImpl) ksession).getGlobalResolver() );

        if ( dispose ) {
            ksession.dispose();
        }

        return ksession2;
    }
 
Example 3
Source File: ProcessFactoryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessFactory() throws Exception {
    RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process");
    factory
            // header
            .name("My process")
            .packageName("org.jbpm")
            // nodes
            .startNode(1)
                .name("Start")
                .done()
            .actionNode(2)
                .name("Action")
                .action("java",
                        "System.out.println(\"Action\");")
                .done()
            .endNode(3)
                .name("End")
                .done()
            // connections
            .connection(1, 2)
            .connection(2, 3);
    RuleFlowProcess process = factory.validate().getProcess();
    Resource res = ResourceFactory.newByteArrayResource(XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes());
    res.setSourcePath("/tmp/processFactory.bpmn2"); // source path or target path must be set to be added into kbase
    KieBase kbase = createKnowledgeBaseFromResources(res);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    ksession.startProcess("org.jbpm.process");
    ksession.dispose();
}
 
Example 4
Source File: ProcessFactoryTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
@Timeout(10)
public void testActionNodeIsDroolsAction() throws Exception {
    RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process");
    factory
            .name("ActionNodeActionProcess")
            .version("1")
            .startNode(1)
                .name("Start")
                .done()
            .endNode(3)
                .name("End")
                .done()
            .actionNode(2)
                .name("printTextActionNode")
                .action("java",
                        "System.out.println(\"test print\");",
                        true)
                .done()
            .connection(1, 2)
            .connection(2, 3);
    RuleFlowProcess process = factory.validate().getProcess();

    assertNotNull(process);

    Resource res = ResourceFactory.newByteArrayResource(XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes());
    res.setSourcePath("/tmp/processFactory.bpmn2");
    KieBase kbase = createKnowledgeBaseFromResources(res);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    ProcessInstance pi = ksession.startProcess("org.jbpm.process");

    assertNotNull(pi);

    assertEquals(ProcessInstance.STATE_COMPLETED,
                 pi.getState());

    ksession.dispose();
}
 
Example 5
Source File: IntermediateEventTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignalBoundaryEventOnMultiInstanceSubprocess() throws Exception {
    KieBase kbase = createKnowledgeBase(
            "subprocess/BPMN2-MultiInstanceSubprocessWithBoundarySignal.bpmn2");
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler handler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);

    Map<String, Object> params = new HashMap<String, Object>();
    List<String> approvers = new ArrayList<String>();
    approvers.add("john");
    approvers.add("john");

    params.put("approvers", approvers);

    ProcessInstance processInstance = ksession.startProcess("boundary-catch-error-event", params);
    assertProcessInstanceActive(processInstance);

    List<WorkItem> workItems = handler.getWorkItems();
    assertThat(workItems).isNotNull();
    assertThat(workItems.size()).isEqualTo(2);

    ksession.signalEvent("Outside", null, processInstance.getId());
    assertProcessInstanceFinished(processInstance, ksession);

    ksession.dispose();
}
 
Example 6
Source File: IntermediateEventTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignalBoundaryEventNoInteruptOnMultiInstanceSubprocess() throws Exception {
    KieBase kbase = createKnowledgeBase(
            "subprocess/BPMN2-MultiInstanceSubprocessWithBoundarySignalNoInterupting.bpmn2");
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler handler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);

    Map<String, Object> params = new HashMap<String, Object>();
    List<String> approvers = new ArrayList<String>();
    approvers.add("john");
    approvers.add("john");

    params.put("approvers", approvers);

    ProcessInstance processInstance = ksession.startProcess("boundary-catch-error-event", params);
    assertProcessInstanceActive(processInstance);

    List<WorkItem> workItems = handler.getWorkItems();
    assertThat(workItems).isNotNull();
    assertThat(workItems.size()).isEqualTo(2);

    ksession.signalEvent("Outside", null, processInstance.getId());

    assertProcessInstanceActive(processInstance.getId(), ksession);

    for (WorkItem wi : workItems) {
    	ksession.getWorkItemManager().completeWorkItem(wi.getId(), null);
    }
    assertProcessInstanceFinished(processInstance, ksession);

    ksession.dispose();
}
 
Example 7
Source File: IntermediateEventTest.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Test
public void testErrorBoundaryEventOnMultiInstanceSubprocess() throws Exception {
    KieBase kbase = createKnowledgeBase(
            "subprocess/BPMN2-MultiInstanceSubprocessWithBoundaryError.bpmn2");
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler handler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);

    Map<String, Object> params = new HashMap<String, Object>();
    List<String> approvers = new ArrayList<String>();
    approvers.add("john");
    approvers.add("john");

    params.put("approvers", approvers);

    ProcessInstance processInstance = ksession.startProcess("boundary-catch-error-event", params);
    assertProcessInstanceActive(processInstance);
    Set<EventDescription<?>> eventDescriptions = processInstance.getEventDescriptions();
    assertThat(eventDescriptions)
        .hasSize(3)
        .extracting("event").contains("workItemCompleted", "Inside", "Error-_D83CFC28-3322-4ABC-A12D-83476B08C7E8-MyError");
    assertThat(eventDescriptions)
        .extracting("eventType").contains("workItem", "signal");
    assertThat(eventDescriptions)            
        .extracting("processInstanceId").contains(processInstance.getId());
    assertThat(eventDescriptions)
        .filteredOn("eventType", "signal")
        .hasSize(2)
        .extracting("properties", Map.class)
        .anyMatch(m -> m.containsKey("AttachedToID") && m.containsKey("AttachedToName"));

    List<WorkItem> workItems = handler.getWorkItems();
    assertThat(workItems).isNotNull();
    assertThat(workItems.size()).isEqualTo(2);

    ksession.signalEvent("Inside", null, processInstance.getId());
    assertProcessInstanceFinished(processInstance, ksession);

    ksession.dispose();
}
 
Example 8
Source File: CamelSqlTest.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
@Test
public void testSelect() {
    Environment env = createEnvironment(context);

    KieBase kbase = createBase();
    StatefulKnowledgeSession kieSession = JPAKnowledgeService.newStatefulKnowledgeSession(kbase,
                                                                                          null,
                                                                                          env);

    kieSession.getWorkItemManager().registerWorkItemHandler("CamelSql",
                                                            handler);

    String sqlQuery = "select NAME from TEST";
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("Query",
               sqlQuery);
    params.put("DataSource",
               "jdbc/testDS1");

    WorkflowProcessInstance wpi = (WorkflowProcessInstance) kieSession.startProcess("camelSqlProcess",
                                                                                    params);

    Assert.assertEquals(2,
                        ((RuleFlowProcessInstance) wpi).getVariables().size());

    kieSession.dispose();
}
 
Example 9
Source File: StatelessKnowledgeSessionImpl.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
private void dispose(StatefulKnowledgeSession ksession) {
    ksession.dispose();
}
 
Example 10
Source File: ProcessFactoryTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
public void testCompositeNode() throws Exception {
    RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process");
    factory
            // header
            .name("My process")
            .packageName("org.jbpm")
            // nodes
            .startNode(1)
                .name("Start")
                .done()
            .compositeContextNode(2)
                .name("SubProcess")
                .startNode(1)
                    .name("SubProcess Start")
                    .done()
                .actionNode(2)
                    .name("SubProcess Action")
                    .action("java",
                            "System.out.println(\"SubProcess Action\");")
                    .done()
                .endNode(3)
                    .name("SubProcess End")
                    .terminate(true)
                    .done()
                .connection(1, 2)
                .connection(2, 3)
                .done()
            .endNode(3)
                .name("End")
                .done()
            // connections
            .connection(1, 2)
            .connection(2, 3);
    RuleFlowProcess process = factory.validate().getProcess();

    assertEquals("SubProcess",
                 process.getNode(2).getName());

    Resource res = ResourceFactory.newByteArrayResource(XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes());
    res.setSourcePath("/tmp/processFactory.bpmn2"); // source path or target path must be set to be added into kbase
    KieBase kbase = createKnowledgeBaseFromResources(res);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    ProcessInstance pi = ksession.startProcess("org.jbpm.process");

    assertEquals(ProcessInstance.STATE_COMPLETED,
                 pi.getState());

    ksession.dispose();
}
 
Example 11
Source File: ProcessFactoryTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
@Timeout(10)
public void testBoundaryTimerTimeCycle() throws Exception {
    NodeLeftCountDownProcessEventListener countDownListener = new NodeLeftCountDownProcessEventListener("BoundaryTimerEvent",
                                                                                                        1);
    String timeCycle = "1s###5s";
    RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process");
    factory
            // header
            .name("My process")
            .packageName("org.jbpm")
            // nodes
            .startNode(1)
                .name("Start")
                .done()
            .humanTaskNode(2)
                .name("Task")
                .actorId("john")
                .taskName("MyTask")
                .done()
            .endNode(3)
                .name("End1")
                .terminate(false)
                .done()
            .boundaryEventNode(4)
                .name("BoundaryTimerEvent")
                .attachedTo(2)
                .metaData(TIME_CYCLE, timeCycle)
                .metaData(CANCEL_ACTIVITY, false)
                .eventType(EVENT_TYPE_TIMER, timeCycle)
                .done()
            .endNode(5)
                .name("End2")
                .terminate(false)
                .done()
            // connections
            .connection(1, 2)
            .connection(2, 3)
            .connection(4, 5);
    RuleFlowProcess process = factory.validate().getProcess();

    Resource res = ResourceFactory.newByteArrayResource(XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes());
    res.setSourcePath("/tmp/processFactory.bpmn2"); // source path or target path must be set to be added into kbase
    KieBase kbase = createKnowledgeBaseFromResources(res);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler testHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task",
                                                          testHandler);
    ksession.addEventListener(countDownListener);

    ProcessInstance pi = ksession.startProcess("org.jbpm.process");
    assertProcessInstanceActive(pi);

    countDownListener.waitTillCompleted(); // wait for boundary timer firing

    assertNodeTriggered(pi.getId(),
                        "End2");
    assertProcessInstanceActive(pi); // still active because CancelActivity = false

    ksession.getWorkItemManager().completeWorkItem(testHandler.getWorkItem().getId(),
                                                   null);
    assertProcessInstanceCompleted(pi);

    ksession.dispose();
}
 
Example 12
Source File: ProcessFactoryTest.java    From kogito-runtimes with Apache License 2.0 4 votes vote down vote up
@Test
@Timeout(10)
public void testBoundaryTimerTimeDuration() throws Exception {
    NodeLeftCountDownProcessEventListener countDownListener = new NodeLeftCountDownProcessEventListener("BoundaryTimerEvent",
                                                                                                        1);
    String timeDuration = "1s";
    RuleFlowProcessFactory factory = RuleFlowProcessFactory.createProcess("org.jbpm.process");
    factory
            // header
            .name("My process")
            .packageName("org.jbpm")
            // nodes
            .startNode(1)
                .name("Start")
                .done()
            .humanTaskNode(2)
                .name("Task")
                .actorId("john")
                .taskName("MyTask")
                .done()
            .endNode(3)
                .name("End1")
                .terminate(false)
                .done()
            .boundaryEventNode(4)
                .name("BoundaryTimerEvent")
                .attachedTo(2)
                .metaData(TIME_DURATION, timeDuration)
                .metaData(CANCEL_ACTIVITY, false)
                .eventType(EVENT_TYPE_TIMER, timeDuration)
                .done()
            .endNode(5)
                .name("End2")
                .terminate(false)
                .done()
            // connections
            .connection(1, 2)
            .connection(2, 3)
            .connection(4, 5);
    RuleFlowProcess process = factory.validate().getProcess();

    Resource res = ResourceFactory.newByteArrayResource(XmlBPMNProcessDumper.INSTANCE.dump(process).getBytes());
    res.setSourcePath("/tmp/processFactory.bpmn2"); // source path or target path must be set to be added into kbase
    KieBase kbase = createKnowledgeBaseFromResources(res);
    StatefulKnowledgeSession ksession = createKnowledgeSession(kbase);
    TestWorkItemHandler testHandler = new TestWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task",
                                                          testHandler);
    ksession.addEventListener(countDownListener);

    ProcessInstance pi = ksession.startProcess("org.jbpm.process");
    assertProcessInstanceActive(pi);

    countDownListener.waitTillCompleted(); // wait for boundary timer firing

    assertNodeTriggered(pi.getId(),
                        "End2");
    assertProcessInstanceActive(pi); // still active because CancelActivity = false

    ksession.getWorkItemManager().completeWorkItem(testHandler.getWorkItem().getId(),
                                                   null);
    assertProcessInstanceCompleted(pi);

    ksession.dispose();
}
 
Example 13
Source File: DdLoadTest.java    From drools-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
	//rule,rule2可以放在数据库中,有个唯一code和他们对于,代码要执行规则的时候,根据code从数据库获取出来就OK了,这样自己开发的规则管理系统那边对数据库里的规则进行维护就行了
	String rule = "package com.neo.drools\r\n";
	rule += "import com.neo.drools.model.Message;\r\n";
	rule += "rule \"rule1\"\r\n";
	rule += "\twhen\r\n";
	rule += "Message( status == 1, myMessage : msg )";
	rule += "\tthen\r\n";
	rule += "\t\tSystem.out.println( 1+\":\"+myMessage );\r\n";
	rule += "end\r\n";


	String rule2 = "package com.neo.drools\r\n";
	rule += "import com.neo.drools.model.Message;\r\n";

	rule += "rule \"rule2\"\r\n";
	rule += "\twhen\r\n";
	rule += "Message( status == 2, myMessage : msg )";
	rule += "\tthen\r\n";
	rule += "\t\tSystem.out.println( 2+\":\"+myMessage );\r\n";
	rule += "end\r\n";


	StatefulKnowledgeSession kSession = null;
	try {


		KnowledgeBuilder kb = KnowledgeBuilderFactory.newKnowledgeBuilder();
		//装入规则,可以装入多个
		kb.add(ResourceFactory.newByteArrayResource(rule.getBytes("utf-8")), ResourceType.DRL);
		kb.add(ResourceFactory.newByteArrayResource(rule2.getBytes("utf-8")), ResourceType.DRL);

		KnowledgeBuilderErrors errors = kb.getErrors();
		for (KnowledgeBuilderError error : errors) {
			System.out.println(error);
		}
		KnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
		kBase.addKnowledgePackages(kb.getKnowledgePackages());

		kSession = kBase.newStatefulKnowledgeSession();


		Message message1 = new Message();
		message1.setStatus(1);
		message1.setMsg("hello world!");

		Message message2 = new Message();
		message2.setStatus(2);
		message2.setMsg("hi world!");

		kSession.insert(message1);
		kSession.insert(message2);
		kSession.fireAllRules();

	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	} finally {
		if (kSession != null)
			kSession.dispose();
	}

}