Search in sources :

Example 21 with StatefulKnowledgeSession

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

the class MultiSessionsPatternsTest method multiSessionsCollaboration.

/*
     * This test shows how a master session can automatically complete a work 
     * item handler in a slave session when the required information is present. 
     */
@Test
public void multiSessionsCollaboration() throws Exception {
    //Creates an entity manager and get the user transaction. We are going
    //to need them later to interact with the business entities persisted
    //by the work item handlers we have configured in our session.
    EntityManager em = getEmf().createEntityManager();
    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    //Creates and persists a new BusinessEntity containing the information
    //required by this test.
    StatefulKnowledgeSession interactionSession = null;
    BusinessEntity interactionSessionEntity = null;
    try {
        // This needs to happen in the same transaction if I want to keep it consistent
        ut.begin();
        //Creates a new session.
        interactionSession = createProcessInteractionKnowledgeSession("InteractionSession", em);
        //persists the required business entity.
        interactionSessionEntity = new BusinessEntity(interactionSession.getId(), 0, 0, "InteractionSession");
        // I need to join the Drools/jBPM transaction 
        em.joinTransaction();
        em.persist(interactionSessionEntity);
        ut.commit();
    } catch (Exception e) {
        System.out.println("Rolling Back because of: " + e.getMessage());
        ut.rollback();
        fail(e.getMessage());
    }
    assertNotNull(interactionSessionEntity);
    assertNotNull(interactionSessionEntity.getId());
    //Dispose the session.
    interactionSession.dispose();
    //Initial parameters for process instance #1
    Person person = new Person("Salaboy", 29);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("person", person);
    //Creates the ksession for process instance #1
    StatefulKnowledgeSession ksession = createProcessOneKnowledgeSession(person.getId());
    registerWorkItemHandlers(ksession, person.getId(), em);
    //Starts process instance #1
    ksession.startProcess("com.salaboy.process.AsyncInteractions", params);
    //Disposes the session.
    ksession.dispose();
    // The interaction Session has the responsability of mapping the WorkItems Ids with their corresponding
    // Business Interactions. This can be done with a Map/Registry or with a Knowledge Session to 
    // describe more complex patterns
    BusinessEntity sessionInteractionKey = getBusinessEntity("InteractionSession", em);
    interactionSession = loadKnowldgeSession(sessionInteractionKey.getSessionId(), "InteractionSession", em);
    interactionSession.setGlobal("em", em);
    interactionSession.setGlobal("ksessionSupport", this);
    // Look for all the pending Business Keys which represent an interaction and insert them into the interaction session
    List<BusinessEntity> pendingBusinessEntities = getActiveBusinessEntities(em);
    for (BusinessEntity be : pendingBusinessEntities) {
        if (!be.getBusinessKey().equals("InteractionSession")) {
            interactionSession.insert(be);
        }
    }
    // As soon as we add Data the completion will be triggered and the process will continue
    interactionSession.insert(new Data());
    interactionSession.fireAllRules();
    ksession.dispose();
}
Also used : UserTransaction(javax.transaction.UserTransaction) HashMap(java.util.HashMap) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) Data(com.salaboy.model.Data) BusinessEntity(com.salaboy.sessions.patterns.BusinessEntity) InitialContext(javax.naming.InitialContext) EntityManager(javax.persistence.EntityManager) Person(com.salaboy.model.Person) Test(org.junit.Test)

Example 22 with StatefulKnowledgeSession

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

the class MultiSessionsPatternsTest method multiSessionsWithSessionLocator.

/**
     * This test uses the concept of a SessionLocator to register slaves sessions.
     * Based on rules, the master session decides which (process definition), 
     * when (declaratively expressed with rules) and where (in which slave session)
     * to start a process instance.
     */
@Test
public void multiSessionsWithSessionLocator() throws Exception {
    EntityManager em = getEmf().createEntityManager();
    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    StatefulKnowledgeSession interactionSession = null;
    BusinessEntity interactionSessionEntity = null;
    try {
        // This needs to happen in the same transaction if I want to keep it consistent
        ut.begin();
        interactionSession = createProcessInteractionKnowledgeSession("InteractionSession", em);
        interactionSessionEntity = new BusinessEntity(interactionSession.getId(), 0, 0, "InteractionSession");
        // I need to join the Drools/jBPM transaction 
        em.joinTransaction();
        em.persist(interactionSessionEntity);
        ut.commit();
    } catch (Exception e) {
        System.out.println("Rolling Back because of: " + e.getMessage());
        ut.rollback();
    }
    assertNotNull(interactionSessionEntity);
    assertNotNull(interactionSessionEntity.getId());
    interactionSession.dispose();
    // Let's create a session which contains a process and register it in the interaction session:
    StatefulKnowledgeSession processSession = createProcessOneKnowledgeSessionAndRegister("My Business Unit Session", interactionSessionEntity, em);
    processSession.dispose();
    Person person = new Person("Salaboy", 29);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("person", person);
    interactionSession = loadKnowldgeSession(interactionSessionEntity.getSessionId(), "InteractionSession", em);
    KnowledgeRuntimeLoggerFactory.newConsoleLogger(interactionSession);
    interactionSession.setGlobal("em", em);
    interactionSession.setGlobal("ksessionSupport", this);
    // Let's insert a fact in the master session and let the rules choose the appropriate session for us to start a process
    interactionSession.insert(person);
    // The process will be selected and started. Because it contains an async activity a new BusinessEntity will be created
    interactionSession.fireAllRules();
    // Look for all the pending Business Keys which represent an interaction and insert them into the interaction session
    List<BusinessEntity> pendingBusinessEntities = em.createQuery("select be from BusinessEntity be where  " + " be.active = true").getResultList();
    for (BusinessEntity be : pendingBusinessEntities) {
        if (!be.getBusinessKey().equals("InteractionSession")) {
            interactionSession.insert(be);
        }
    }
    // As soon as we add Data the completion will be triggered and the process will continue
    interactionSession.insert(new Data());
    interactionSession.fireAllRules();
    interactionSession.dispose();
}
Also used : UserTransaction(javax.transaction.UserTransaction) HashMap(java.util.HashMap) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) Data(com.salaboy.model.Data) BusinessEntity(com.salaboy.sessions.patterns.BusinessEntity) InitialContext(javax.naming.InitialContext) EntityManager(javax.persistence.EntityManager) Person(com.salaboy.model.Person) Test(org.junit.Test)

Example 23 with StatefulKnowledgeSession

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

the class MultiSessionsPatternsTest method createProcessInteractionKnowledgeSession.

/**
     * Creates a new ksession containing a single rules resource: 
     * 'interaction-rules.drl'.
     * This method uses {@link #createKnowledgeSession(java.lang.String, java.util.Map)}
     * in order to create the ksession.
     * @param key The key used to register the kbase created with the resources
     * used by this method.
     * @param em The entity manager registered as a global in the created
     * session.
     * @return a new ksession containing a single process definition.
     */
private StatefulKnowledgeSession createProcessInteractionKnowledgeSession(String key, EntityManager em) {
    Map<Resource, ResourceType> resources = new HashMap<Resource, ResourceType>();
    resources.put(ResourceFactory.newClassPathResource("interaction-rules.drl"), ResourceType.DRL);
    //creates the session
    StatefulKnowledgeSession ksession = this.createKnowledgeSession(key, resources);
    //register globals
    ksession.setGlobal("em", em);
    ksession.setGlobal("ksessionSupport", this);
    return ksession;
}
Also used : HashMap(java.util.HashMap) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) Resource(org.drools.io.Resource) ResourceType(org.drools.builder.ResourceType)

Example 24 with StatefulKnowledgeSession

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

the class SessionsPatternsTestsBase method loadKnowldgeSession.

/**
     * Same as {@link #loadKnowldgeSession(int, java.lang.String, java.lang.String, javax.persistence.EntityManager) 
     * loadKnowldgeSession(id, sessionName, sessionName, em)}
     */
@Override
public StatefulKnowledgeSession loadKnowldgeSession(int id, String sessionName, EntityManager em) {
    StatefulKnowledgeSession ksession = JPAKnowledgeService.loadStatefulKnowledgeSession(id, getKbase(sessionName), null, createEnvironment());
    registerWorkItemHandlers(ksession, sessionName, em);
    return ksession;
}
Also used : StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession)

Example 25 with StatefulKnowledgeSession

use of org.drools.runtime.StatefulKnowledgeSession in project sling by apache.

the class AbstractUsingBundleListMojo method rewriteBundleList.

private void rewriteBundleList(BundleList bundleList) throws MojoExecutionException {
    if (rewriteRuleFiles != null) {
        KnowledgeBase knowledgeBase = createKnowledgeBase(rewriteRuleFiles);
        StatefulKnowledgeSession session = knowledgeBase.newStatefulKnowledgeSession();
        try {
            session.setGlobal("mavenSession", mavenSession);
            session.setGlobal("mavenProject", project);
            session.insert(bundleList);
            session.fireAllRules();
        } finally {
            session.dispose();
        }
    }
}
Also used : KnowledgeBase(org.drools.KnowledgeBase) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession)

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