Search in sources :

Example 36 with StatefulKnowledgeSession

use of org.drools.runtime.StatefulKnowledgeSession in project jBPM5-Developer-Guide by Salaboy.

the class MyFirstDrools5FusionRulesTest method testSimpleEvents.

@Test
public void testSimpleEvents() {
    StatefulKnowledgeSession ksession = createKnowledgeSession();
    // Uncomment to see all the logs
    // KnowledgeRuntimeLoggerFactory.newConsoleLogger(ksession);
    // We have our Session, now let's play with our Events
    SessionPseudoClock clock = ksession.getSessionClock();
    int fired = 0;
    // Initial time 0s -> t0
    ksession.insert(new KeyA());
    fired = ksession.fireAllRules();
    clock.advanceTime(2, TimeUnit.SECONDS);
    assertEquals(0, fired);
    // t1 -> 2s 
    ksession.insert(new KeyA());
    fired = ksession.fireAllRules();
    clock.advanceTime(2, TimeUnit.SECONDS);
    assertEquals(0, fired);
    // t2 -> 4s 
    ksession.insert(new KeyA());
    fired = ksession.fireAllRules();
    clock.advanceTime(2, TimeUnit.SECONDS);
    assertEquals(0, fired);
    // t3 -> 6s 
    ksession.insert(new KeyA());
    fired = ksession.fireAllRules();
    clock.advanceTime(2, TimeUnit.SECONDS);
    assertEquals(1, fired);
    // t4 -> 8s
    ksession.insert(new KeyA());
    fired = ksession.fireAllRules();
    assertEquals(1, fired);
    ksession.dispose();
}
Also used : KeyA(com.salaboy.model.KeyA) SessionPseudoClock(org.drools.time.SessionPseudoClock) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) Test(org.junit.Test)

Example 37 with StatefulKnowledgeSession

use of org.drools.runtime.StatefulKnowledgeSession in project jBPM5-Developer-Guide by Salaboy.

the class ProcessAndEventIntegrationTest method processEventsWithListenerTest.

@Test
public void processEventsWithListenerTest() throws InterruptedException {
    // Let's create a kbuilder, kbase and ksession for running the process
    final StatefulKnowledgeSession processKsession = createProcessSession();
    // Let's create a kbuilder, kbase and ksession for analyzing the process events
    final StatefulKnowledgeSession eventsKsession = createEventsSession();
    final TaskSpeed taskSpeed = new TaskSpeed(1000L);
    eventsKsession.setGlobal("taskSpeed", taskSpeed);
    processKsession.getWorkItemManager().registerWorkItemHandler("Human Task", new WorkItemHandler() {

        public void executeWorkItem(WorkItem wi, WorkItemManager wim) {
            try {
                System.out.println(" >>> Working on Task! it will take: " + taskSpeed.getAmount() / 1000 + " seconds.");
                Thread.sleep(taskSpeed.getAmount());
            } catch (InterruptedException ex) {
                Logger.getLogger(ProcessAndEventIntegrationTest.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println(" >>> Completing Task! -> " + wi.getName() + " - id: " + wi.getId());
            wim.completeWorkItem(wi.getId(), null);
        }

        public void abortWorkItem(WorkItem wi, WorkItemManager wim) {
        // do nothing
        }
    });
    processKsession.addEventListener(new DefaultProcessEventListener() {

        @Override
        public void beforeProcessStarted(ProcessStartedEvent event) {
            System.out.println(" >>> Before Process Started: " + event.getProcessInstance().getProcessName());
            eventsKsession.insert(event);
        }

        @Override
        public void afterProcessCompleted(ProcessCompletedEvent event) {
            System.out.println(" >>> After Process Completed: " + event.getProcessInstance().getProcessName());
            eventsKsession.insert(event);
        }

        @Override
        public void beforeNodeLeft(org.drools.event.process.ProcessNodeLeftEvent event) {
            System.out.println(" >>> Before Node Left: " + event.getNodeInstance().getNodeName());
            eventsKsession.insert(event);
        }
    });
    for (int i = 0; i < 20; i++) {
        final int id = i;
        Person person = new Person("Salaboy-" + id, id);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("person", person);
        ProcessInstance processInstance = processKsession.createProcessInstance("com.salaboy.process.SimpleProcess", params);
        assertEquals(processInstance.getState(), ProcessInstance.STATE_PENDING);
        FactHandle processtHandle = processKsession.insert(processInstance);
        System.out.println("Starting Process Instance: " + processInstance.getId());
        processKsession.startProcessInstance(processInstance.getId());
        assertEquals(processInstance.getState(), ProcessInstance.STATE_COMPLETED);
        processKsession.retract(processtHandle);
    }
}
Also used : HashMap(java.util.HashMap) FactHandle(org.drools.runtime.rule.FactHandle) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) ProcessStartedEvent(org.drools.event.process.ProcessStartedEvent) TaskSpeed(com.salaboy.model.TaskSpeed) WorkItem(org.drools.runtime.process.WorkItem) ProcessCompletedEvent(org.drools.event.process.ProcessCompletedEvent) WorkItemHandler(org.drools.process.instance.WorkItemHandler) DefaultProcessEventListener(org.drools.event.process.DefaultProcessEventListener) ProcessInstance(org.drools.runtime.process.ProcessInstance) WorkItemManager(org.drools.runtime.process.WorkItemManager) Person(com.salaboy.model.Person)

Example 38 with StatefulKnowledgeSession

use of org.drools.runtime.StatefulKnowledgeSession in project jBPM5-Developer-Guide by Salaboy.

the class ProcessAndEventMultiThreadIntegrationTest method processEventsWithListenerTest.

@Test
public void processEventsWithListenerTest() throws InterruptedException {
    // Let's create a kbuilder, kbase and ksession for running the process
    final StatefulKnowledgeSession processKsession = createProcessSession();
    // Let's create a kbuilder, kbase and ksession for analyzing the process events
    final StatefulKnowledgeSession eventsKsession = createEventsSession();
    final TaskSpeed taskSpeed = new TaskSpeed(1000L);
    eventsKsession.setGlobal("taskSpeed", taskSpeed);
    processKsession.getWorkItemManager().registerWorkItemHandler("Human Task", new WorkItemHandler() {

        public void executeWorkItem(WorkItem wi, WorkItemManager wim) {
            try {
                System.out.println(" >>> Working on Task! it will take: " + taskSpeed.getAmount() / 1000 + " seconds.");
                Thread.sleep(taskSpeed.getAmount());
            } catch (InterruptedException ex) {
                Logger.getLogger(ProcessAndEventMultiThreadIntegrationTest.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println(" >>> Completing Task! -> " + wi.getName() + " - id: " + wi.getId());
            wim.completeWorkItem(wi.getId(), null);
        }

        public void abortWorkItem(WorkItem wi, WorkItemManager wim) {
        // do nothing
        }
    });
    ((StatefulKnowledgeSessionImpl) processKsession).addEventListener(new DefaultProcessEventListener() {

        @Override
        public void beforeProcessStarted(ProcessStartedEvent event) {
            System.out.println(" >>> Before Process Started: " + event.getProcessInstance().getProcessName());
            eventsKsession.insert(event);
        }

        @Override
        public void afterProcessCompleted(ProcessCompletedEvent event) {
            System.out.println(" >>> After Process Completed: " + event.getProcessInstance().getProcessName());
            eventsKsession.insert(event);
        }

        @Override
        public void beforeNodeLeft(org.drools.event.process.ProcessNodeLeftEvent event) {
            System.out.println(" >>> Before Node Left: " + event.getNodeInstance().getNodeName());
            eventsKsession.insert(event);
        }
    });
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 5; j++) {
            final int id1 = i;
            final int id2 = j;
            new Thread(new Runnable() {

                public void run() {
                    Person person = new Person("Salaboy-" + id1 + "_" + id2, id2);
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("person", person);
                    ProcessInstance processInstance = processKsession.createProcessInstance("com.salaboy.process.SimpleProcess", params);
                    assertEquals(processInstance.getState(), ProcessInstance.STATE_PENDING);
                    FactHandle processtHandle = processKsession.insert(processInstance);
                    System.out.println("Starting Process Instance: " + processInstance.getId());
                    processKsession.startProcessInstance(processInstance.getId());
                    assertEquals(processInstance.getState(), ProcessInstance.STATE_COMPLETED);
                    processKsession.retract(processtHandle);
                }
            }).start();
        }
        Thread.sleep(3000);
    }
}
Also used : HashMap(java.util.HashMap) FactHandle(org.drools.runtime.rule.FactHandle) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) ProcessStartedEvent(org.drools.event.process.ProcessStartedEvent) TaskSpeed(com.salaboy.model.TaskSpeed) WorkItem(org.drools.runtime.process.WorkItem) ProcessCompletedEvent(org.drools.event.process.ProcessCompletedEvent) WorkItemHandler(org.drools.process.instance.WorkItemHandler) StatefulKnowledgeSessionImpl(org.drools.impl.StatefulKnowledgeSessionImpl) DefaultProcessEventListener(org.drools.event.process.DefaultProcessEventListener) ProcessInstance(org.drools.runtime.process.ProcessInstance) WorkItemManager(org.drools.runtime.process.WorkItemManager) Person(com.salaboy.model.Person)

Example 39 with StatefulKnowledgeSession

use of org.drools.runtime.StatefulKnowledgeSession in project jBPM5-Developer-Guide by Salaboy.

the class MultiSessionsPatternsTest method createProcessOneKnowledgeSessionAndRegister.

private StatefulKnowledgeSession createProcessOneKnowledgeSessionAndRegister(String key, BusinessEntity interactionSessionEntity, EntityManager em) {
    final StatefulKnowledgeSession ksession = this.createProcessOneKnowledgeSession(key);
    // Registering a SessionLocator inside the interaction Session
    StatefulKnowledgeSession interactionSession = loadKnowldgeSession(interactionSessionEntity.getSessionId(), interactionSessionEntity.getBusinessKey(), em);
    Map<String, String> props = new HashMap<String, String>();
    props.put("process", "com.salaboy.process.AsyncInteractions");
    SessionLocator sessionLocator = new SessionLocator(ksession.getId(), key);
    sessionLocator.setProps(props);
    interactionSession.insert(sessionLocator);
    interactionSession.dispose();
    return ksession;
}
Also used : SessionLocator(com.salaboy.sessions.patterns.SessionLocator) HashMap(java.util.HashMap) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession)

Example 40 with StatefulKnowledgeSession

use of org.drools.runtime.StatefulKnowledgeSession in project jBPM5-Developer-Guide by Salaboy.

the class SessionsPatternsTestsBase method createKnowledgeSession.

/**
     * Creates a new Knowledge Base with the passed resources and returns a fresh
     * ksession from it. This method register the created kbase in {@link #kbases}
     * with the key passed as parameter. The returned session is configured as
     * persistent.
     * @param key the key used to register the generated kbase in {@link #kbases}.
     * @param resources The resources to be placed inside the generated kbase.
     * @return 
     */
protected StatefulKnowledgeSession createKnowledgeSession(String key, Map<Resource, ResourceType> resources) {
    //Creates a new kbuilder
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    //Adds al the given resources
    for (Map.Entry<Resource, ResourceType> entry : resources.entrySet()) {
        kbuilder.add(entry.getKey(), entry.getValue());
    }
    //If there is any compilation error then fail!
    if (kbuilder.hasErrors()) {
        for (KnowledgeBuilderError error : kbuilder.getErrors()) {
            System.out.println(">>> Error:" + error.getMessage());
        }
        Assert.fail(">>> Knowledge couldn't be parsed! ");
    }
    //Creates a new kbase
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    //Add the generated knowledge packages from kbuilder.
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    //Register the kbase in this.kbases
    kbases.put(key, kbase);
    //Creates a Persistence Knowledge Session
    System.out.println(" >>> Let's create a Persistent Knowledge Session");
    final StatefulKnowledgeSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, createEnvironment());
    return ksession;
}
Also used : KnowledgeBuilderError(org.drools.builder.KnowledgeBuilderError) KnowledgeBuilder(org.drools.builder.KnowledgeBuilder) KnowledgeBase(org.drools.KnowledgeBase) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) Resource(org.drools.io.Resource) ResourceType(org.drools.builder.ResourceType) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

StatefulKnowledgeSession (org.drools.runtime.StatefulKnowledgeSession)42 KnowledgeBase (org.drools.KnowledgeBase)28 KnowledgeBuilder (org.drools.builder.KnowledgeBuilder)26 KnowledgeBuilderError (org.drools.builder.KnowledgeBuilderError)26 ClassPathResource (org.drools.io.impl.ClassPathResource)25 HashMap (java.util.HashMap)24 Test (org.junit.Test)21 Person (com.salaboy.model.Person)17 ProcessInstance (org.drools.runtime.process.ProcessInstance)17 DefaultProcessEventListener (org.drools.event.process.DefaultProcessEventListener)12 QueryResults (org.drools.runtime.rule.QueryResults)9 FactHandle (org.drools.runtime.rule.FactHandle)7 Resources (com.salaboy.model.Resources)6 ProcessNodeLeftEvent (org.drools.event.process.ProcessNodeLeftEvent)6 Customer (com.salaboy.model.Customer)5 RatesToday (com.salaboy.model.RatesToday)5 BusinessEntity (com.salaboy.sessions.patterns.BusinessEntity)5 InitialContext (javax.naming.InitialContext)5 EntityManager (javax.persistence.EntityManager)5 UserTransaction (javax.transaction.UserTransaction)5