Search in sources :

Example 21 with KnowledgeBuilder

use of org.drools.builder.KnowledgeBuilder in project jBPM5-Developer-Guide by Salaboy.

the class PersistentProcessTest method processInstancesAndLocalHTPlusFailTest.

@Test
public void processInstancesAndLocalHTPlusFailTest() throws Exception {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("process-async-interactions.bpmn"), ResourceType.BPMN2);
    if (kbuilder.hasErrors()) {
        for (KnowledgeBuilderError error : kbuilder.getErrors()) {
            System.out.println(">>> Error:" + error.getMessage());
        }
        fail(">>> Knowledge couldn't be parsed! ");
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    Environment env = EnvironmentFactory.newEnvironment();
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("org.jbpm.runtime.ht");
    env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, emf);
    env.set(EnvironmentName.TRANSACTION_MANAGER, TransactionManagerServices.getTransactionManager());
    // Let's create a Persistence Knowledge Session
    System.out.println(" >>> Let's create a Persistent Knowledge Session");
    final StatefulKnowledgeSession ksession = JPAKnowledgeService.newStatefulKnowledgeSession(kbase, null, env);
    int sessionId = ksession.getId();
    assertNotNull(sessionId);
    assertTrue(sessionId != 0);
    // We need to register the WorkItems and Listeners that the session will use
    TaskService client = createTaskService(emf);
    LocalHTWorkItemHandler localHTWorkItemHandler = new LocalHTWorkItemHandler(client, ksession);
    MockFaultWorkItemHandler mockFaultWorkItemHandler = new MockFaultWorkItemHandler();
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", localHTWorkItemHandler);
    ksession.getWorkItemManager().registerWorkItemHandler("External Service Call", mockFaultWorkItemHandler);
    // KnowledgeRuntimeLoggerFactory.newConsoleLogger(ksession);
    // Let's create a Process Instance
    Person person = new Person("Salaboy", 29);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("person", person);
    // Each Command will generate an interaction
    System.out.println(">>> Let's Create Process Instance");
    ProcessInstance processInstance = ksession.createProcessInstance("com.salaboy.process.AsyncInteractions", params);
    System.out.println(">>> Let's Start the Process Instance");
    UserTransaction ut = (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction");
    ut.begin();
    ksession.startProcessInstance(processInstance.getId());
    ut.commit();
    System.out.println(" >>> Looking for Salaboy's Tasks");
    List<TaskSummary> salaboysTasks = client.getTasksAssignedAsPotentialOwner("salaboy", "en-UK");
    assertTrue(salaboysTasks.size() == 1);
    TaskSummary salaboyTask = salaboysTasks.get(0);
    System.out.println(" >>> Starting Salaboy's Task");
    client.start(salaboyTask.getId(), "salaboy");
    System.out.println(" >>> Completing Salaboy's Task");
    ut.begin();
    try {
        client.complete(salaboyTask.getId(), "salaboy", null);
        ut.commit();
    } catch (WorkflowRuntimeException e) {
        System.out.println("Rolling back transaction" + e);
        ut.rollback();
    }
    System.out.println(" >>> Looking for Salaboy's Tasks");
    Task salaboysTask = client.getTask(salaboyTask.getId());
    assertNotNull(salaboysTask);
    assertEquals("InProgress", salaboysTask.getTaskData().getStatus().name());
    // We need to dispose the session, because the reference to this ksession object will no longer be valid
    // because another thread could load the same session and execute a different command.
    System.out.println(" >>> Disposing Session");
    ksession.dispose();
}
Also used : UserTransaction(javax.transaction.UserTransaction) KnowledgeBuilderError(org.drools.builder.KnowledgeBuilderError) Task(org.jbpm.task.Task) HashMap(java.util.HashMap) LocalTaskService(org.jbpm.task.service.local.LocalTaskService) TaskService(org.jbpm.task.TaskService) WorkflowRuntimeException(org.jbpm.workflow.instance.WorkflowRuntimeException) ClassPathResource(org.drools.io.impl.ClassPathResource) InitialContext(javax.naming.InitialContext) KnowledgeBuilder(org.drools.builder.KnowledgeBuilder) KnowledgeBase(org.drools.KnowledgeBase) EntityManagerFactory(javax.persistence.EntityManagerFactory) TaskSummary(org.jbpm.task.query.TaskSummary) ProcessInstance(org.drools.runtime.process.ProcessInstance) Person(com.salaboy.model.Person) LocalHTWorkItemHandler(org.jbpm.process.workitem.wsht.LocalHTWorkItemHandler)

Example 22 with KnowledgeBuilder

use of org.drools.builder.KnowledgeBuilder in project jBPM5-Developer-Guide by Salaboy.

the class HumanTasksAndRulesTest method simpleTest.

@Test
public void simpleTest() throws InterruptedException {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    // Adds resources to the builder
    kbuilder.add(new ClassPathResource("rules/SimpleRulesAndTask.drl"), ResourceType.DRL);
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    // Checks for errors
    if (errors.size() > 0) {
        for (KnowledgeBuilderError error : errors) {
            System.out.println(error.getMessage());
        }
        throw new IllegalStateException("Error building kbase!");
    }
    // Creates a new kbase and add all the packages from the builder
    KnowledgeBaseConfiguration kbaseConf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    kbaseConf.setOption(EventProcessingOption.STREAM);
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(kbaseConf);
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    KnowledgeSessionConfiguration ksessionConf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();
    ksessionConf.setOption(ClockTypeOption.get("pseudo"));
    final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(ksessionConf, null);
    HornetQHTWorkItemHandler hornetQHTWorkItemHandler = new HornetQHTWorkItemHandler(ksession);
    ksession.getWorkItemManager().registerWorkItemHandler("Human Task", hornetQHTWorkItemHandler);
    KnowledgeRuntimeLoggerFactory.newConsoleLogger(ksession);
    // ksession.addEventListener(new DebugAgendaEventListener());
    // Force Init
    TaskClientHelper.getInstance();
    Thread.sleep(3000);
    Task task = createTask();
    // new Thread(new Runnable() {
    // 
    // public void run() {
    // ksession.fireUntilHalt();
    // }
    // }).start();
    // Insert Tasks
    ksession.insert(task);
    // Insert Average
    ksession.insert(new Average(0.0));
    // Create and Insert Threshold
    Threshold avgThreshold = new Threshold("AverageThreshold", 2, -1);
    ksession.insert(avgThreshold);
    // Insert User
    ksession.insert(new User("salaboy"));
    clock = ksession.getSessionClock();
    System.out.println(">>> Time " + clock.getCurrentTime());
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(10.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(10.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(10.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(10.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(10.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    System.out.println(">>> Time " + clock.getCurrentTime());
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(10.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(10.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(10.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(10.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(10.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    System.out.println(">>> Time " + clock.getCurrentTime());
    org.drools.runtime.rule.QueryResults results = ksession.getQueryResults("getAverage", new Object[] {});
    for (QueryResultsRow row : results) {
        System.out.println(">>> Current Average: " + ((Average) row.get("$currentAverage")).getValue().toString());
        assertEquals("10.0", ((Average) row.get("$currentAverage")).getValue().toString());
    }
    Thread.sleep(3000);
    List<TaskSummary> tasks = TaskClientHelper.getInstance().getAssignedTasksByUser("salaboy");
    assertEquals(1, tasks.size());
    System.out.println(">>> Current Assigned Tasks: " + tasks.get(0).getName());
    System.out.println(">>> Time " + clock.getCurrentTime());
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(1.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(1.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(1.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(1.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(1.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    System.out.println(">>> Time " + clock.getCurrentTime());
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(1.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(1.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(1.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(1.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    ksession.getWorkingMemoryEntryPoint("water-events").insert(new WaterFlowingEvent(1.0));
    ksession.fireAllRules();
    clock.advanceTime(1000, TimeUnit.MILLISECONDS);
    System.out.println(">>> Time " + clock.getCurrentTime());
    results = ksession.getQueryResults("getAverage", new Object[] {});
    Thread.sleep(3000);
    for (QueryResultsRow row : results) {
        System.out.println(">>> Current Average: " + ((Average) row.get("$currentAverage")).getValue().toString());
        assertEquals("1.0", ((Average) row.get("$currentAverage")).getValue().toString());
    }
    Thread.sleep(3000);
    tasks = TaskClientHelper.getInstance().getAssignedTasksByUser("salaboy");
    assertEquals(0, tasks.size());
    System.out.println(">>> I don't have any task assigned now!");
    Thread.sleep(3000);
}
Also used : KnowledgeBuilderError(org.drools.builder.KnowledgeBuilderError) Task(org.jbpm.task.Task) User(org.jbpm.task.User) KnowledgeBuilderErrors(org.drools.builder.KnowledgeBuilderErrors) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) ClassPathResource(org.drools.io.impl.ClassPathResource) KnowledgeBuilder(org.drools.builder.KnowledgeBuilder) HornetQHTWorkItemHandler(org.jbpm.process.workitem.wsht.HornetQHTWorkItemHandler) KnowledgeBase(org.drools.KnowledgeBase) KnowledgeBaseConfiguration(org.drools.KnowledgeBaseConfiguration) QueryResultsRow(org.drools.runtime.rule.QueryResultsRow) KnowledgeSessionConfiguration(org.drools.runtime.KnowledgeSessionConfiguration) TaskSummary(org.jbpm.task.query.TaskSummary) Test(org.junit.Test)

Example 23 with KnowledgeBuilder

use of org.drools.builder.KnowledgeBuilder in project jBPM5-Developer-Guide by Salaboy.

the class AutoMappingVariablesTest method processVariablesAutoMappingTest.

@Test
public void processVariablesAutoMappingTest() throws InterruptedException {
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(new ClassPathResource("evolution/mapping.drl"), ResourceType.DRL);
    kbuilder.add(new ClassPathResource("evolution/scoring_processVariables.drl"), ResourceType.DRL);
    kbuilder.add(new ClassPathResource("evolution/process-automapping-decision.bpmn"), ResourceType.BPMN2);
    if (kbuilder.hasErrors()) {
        for (KnowledgeBuilderError error : kbuilder.getErrors()) {
            System.out.println(">>> Error:" + error.getMessage());
        }
        fail(">>> Knowledge couldn't be parsed! ");
    }
    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    KnowledgeRuntimeLoggerFactory.newConsoleLogger(ksession);
    Person person = new Person("Salaboy", 28);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("person", person);
    ProcessInstance processInstance = ksession.createProcessInstance("com.salaboy.process.SimpleDecision", params);
    System.out.println("Variables: " + ((WorkflowProcessInstanceImpl) processInstance).getVariables());
    assertEquals(processInstance.getState(), ProcessInstance.STATE_PENDING);
    FactHandle processtHandle = ksession.insert(processInstance);
    ksession.fireAllRules();
    ksession.startProcessInstance(processInstance.getId());
    assertEquals(processInstance.getState(), ProcessInstance.STATE_COMPLETED);
    QueryResults queryResults = ksession.getQueryResults("allProcessVariables", new Object[] {});
    Iterator<QueryResultsRow> iterator = queryResults.iterator();
    while (iterator.hasNext()) {
        QueryResultsRow next = iterator.next();
        assertEquals(person, ((ProcessVariable) next.get("$pv")).getValue());
    }
    ksession.retract(processtHandle);
}
Also used : KnowledgeBuilderError(org.drools.builder.KnowledgeBuilderError) HashMap(java.util.HashMap) FactHandle(org.drools.runtime.rule.FactHandle) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) WorkflowProcessInstanceImpl(org.jbpm.workflow.instance.impl.WorkflowProcessInstanceImpl) ClassPathResource(org.drools.io.impl.ClassPathResource) QueryResults(org.drools.runtime.rule.QueryResults) KnowledgeBuilder(org.drools.builder.KnowledgeBuilder) KnowledgeBase(org.drools.KnowledgeBase) QueryResultsRow(org.drools.runtime.rule.QueryResultsRow) ProcessInstance(org.drools.runtime.process.ProcessInstance) Person(com.salaboy.model.Person)

Example 24 with KnowledgeBuilder

use of org.drools.builder.KnowledgeBuilder in project jBPM5-Developer-Guide by Salaboy.

the class ProcessAndEventIntegrationTest method createProcessSession.

private StatefulKnowledgeSession createProcessSession() {
    KnowledgeBuilder processKbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    processKbuilder.add(new ClassPathResource("process-events-simple.bpmn"), ResourceType.BPMN2);
    if (processKbuilder.hasErrors()) {
        for (KnowledgeBuilderError error : processKbuilder.getErrors()) {
            System.out.println(">>> Error:" + error.getMessage());
        }
        fail(">>> Knowledge couldn't be parsed! ");
    }
    KnowledgeBase processKbase = KnowledgeBaseFactory.newKnowledgeBase();
    processKbase.addKnowledgePackages(processKbuilder.getKnowledgePackages());
    return processKbase.newStatefulKnowledgeSession();
}
Also used : KnowledgeBuilderError(org.drools.builder.KnowledgeBuilderError) KnowledgeBuilder(org.drools.builder.KnowledgeBuilder) KnowledgeBase(org.drools.KnowledgeBase) ClassPathResource(org.drools.io.impl.ClassPathResource)

Example 25 with KnowledgeBuilder

use of org.drools.builder.KnowledgeBuilder in project jBPM5-Developer-Guide by Salaboy.

the class ProcessAndEventIntegrationTest method createEventsSession.

private StatefulKnowledgeSession createEventsSession() {
    KnowledgeBuilder eventsKbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    eventsKbuilder.add(new ClassPathResource("analyze-process-events.drl"), ResourceType.DRL);
    if (eventsKbuilder.hasErrors()) {
        for (KnowledgeBuilderError error : eventsKbuilder.getErrors()) {
            System.out.println(">>> Error:" + error.getMessage());
        }
        fail(">>> Knowledge couldn't be parsed! ");
    }
    KnowledgeBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
    config.setOption(EventProcessingOption.STREAM);
    KnowledgeBase eventsKbase = KnowledgeBaseFactory.newKnowledgeBase(config);
    eventsKbase.addKnowledgePackages(eventsKbuilder.getKnowledgePackages());
    StatefulKnowledgeSession eventsKsession = eventsKbase.newStatefulKnowledgeSession();
    ((StatefulKnowledgeSessionImpl) eventsKsession).getInternalWorkingMemory().addEventListener(new DefaultWorkingMemoryEventListener() {

        @Override
        public void objectInserted(ObjectInsertedEvent event) {
            event.getWorkingMemory().fireAllRules();
        }

        @Override
        public void objectUpdated(ObjectUpdatedEvent event) {
            event.getWorkingMemory().fireAllRules();
        }

        @Override
        public void objectRetracted(ObjectRetractedEvent event) {
            event.getWorkingMemory().fireAllRules();
        }
    });
    ((StatefulKnowledgeSessionImpl) eventsKsession).getInternalWorkingMemory().addEventListener(new DefaultAgendaEventListener() {

        @Override
        public void activationCreated(ActivationCreatedEvent event, WorkingMemory workingMemory) {
            workingMemory.fireAllRules();
        }
    });
    return eventsKsession;
}
Also used : KnowledgeBuilderError(org.drools.builder.KnowledgeBuilderError) WorkingMemory(org.drools.WorkingMemory) StatefulKnowledgeSession(org.drools.runtime.StatefulKnowledgeSession) ClassPathResource(org.drools.io.impl.ClassPathResource) KnowledgeBuilder(org.drools.builder.KnowledgeBuilder) KnowledgeBase(org.drools.KnowledgeBase) KnowledgeBaseConfiguration(org.drools.KnowledgeBaseConfiguration)

Aggregations

KnowledgeBuilder (org.drools.builder.KnowledgeBuilder)49 KnowledgeBase (org.drools.KnowledgeBase)48 KnowledgeBuilderError (org.drools.builder.KnowledgeBuilderError)48 ClassPathResource (org.drools.io.impl.ClassPathResource)45 StatefulKnowledgeSession (org.drools.runtime.StatefulKnowledgeSession)26 HashMap (java.util.HashMap)20 ProcessInstance (org.drools.runtime.process.ProcessInstance)20 Person (com.salaboy.model.Person)16 Test (org.junit.Test)13 DefaultProcessEventListener (org.drools.event.process.DefaultProcessEventListener)11 KnowledgeBuilderErrors (org.drools.builder.KnowledgeBuilderErrors)10 DefaultAgendaEventListener (org.drools.event.rule.DefaultAgendaEventListener)10 QueryResults (org.drools.runtime.rule.QueryResults)9 Resources (com.salaboy.model.Resources)6 EntityManagerFactory (javax.persistence.EntityManagerFactory)6 KnowledgeBaseConfiguration (org.drools.KnowledgeBaseConfiguration)6 ProcessNodeLeftEvent (org.drools.event.process.ProcessNodeLeftEvent)6 Customer (com.salaboy.model.Customer)5 RatesToday (com.salaboy.model.RatesToday)5 ProcessNodeTriggeredEvent (org.drools.event.process.ProcessNodeTriggeredEvent)5