Showing posts with label Drools. Show all posts
Showing posts with label Drools. Show all posts

Wednesday, February 29, 2012

jBPM - How to trace a lifecycle of a process

Just need to add a ProcesEventListener() to the ksession.
KnowledgeBase kbase = readKnowledgeBase();
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

CustomProcessEventListener customProcessEventListener = new CustomProcessEventListener();
ksession.addEventListener(customProcessEventListener);
...
...

ksession.startProcess("com.sample.MyTaskFlow", params);
And here is the sample CustomProcessEventListener();
private static class CustomProcessEventListener implements ProcessEventListener {

 @Override
 public void afterNodeLeft(ProcessNodeLeftEvent arg0) {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void afterNodeTriggered(ProcessNodeTriggeredEvent arg0) {
  // TODO Auto-generated method stub
 }

 @Override
 public void afterProcessCompleted(ProcessCompletedEvent arg0) {
  // TODO Auto-generated method stub
  logger.debug("Process has completed.");
  System.exit(0);
 }

 @Override
 public void afterProcessStarted(ProcessStartedEvent arg0) {
  // TODO Auto-generated method stub
 }

 @Override
 public void afterVariableChanged(ProcessVariableChangedEvent arg0) {
  // TODO Auto-generated method stub
   
  }

 @Override
 public void beforeNodeLeft(ProcessNodeLeftEvent arg0) {
  // TODO Auto-generated method stub
   
 }

 @Override
 public void beforeNodeTriggered(ProcessNodeTriggeredEvent arg0) {
  // TODO Auto-generated method stub
   
 }

 @Override
 public void beforeProcessCompleted(ProcessCompletedEvent arg0) {
  // TODO Auto-generated method stub
  logger.debug("Process is going to be completed.");
 }

 @Override
 public void beforeProcessStarted(ProcessStartedEvent arg0) {
  // TODO Auto-generated method stub
  
 }

 @Override
 public void beforeVariableChanged(ProcessVariableChangedEvent arg0) {
  // TODO Auto-generated method stub
  
 }
 
}
As you can see, you can do many things on every stage of a process.

Tuesday, February 28, 2012

Drools again, example for beginner

Who would foresee that I will get my hand dirty again with drools? Well, after 13 months, here I am, looking at drools, again... now with jbpm too.
Anyway, it was good. Got better understanding about it and yeah, as usual, share.

I successfully made this:

I am not posting the codes here, you can request for it if you want.

The first process flow (can be in .rf or .bpmn) shows how to use Script Tasks. In the "Question" script, I ran these:


System.out.println("Who is the smartest man in the world?");

java.io.BufferedReader br = new java.io.BufferedReader(new 
                         java.io.InputStreamReader(System.in));

String name = null;

try {
name = br.readLine();
} catch (java.io.IOException e) {
System.out.println("Error!");
}

kcontext.setVariable("smart_guy", name);


The gateway after the "Question" script I check for this:


return smart_guy.equals("frank");


The "Error message" script just print error message. I ran the process.


ksession.startProcess("interactiveJava");


It will keep on asking you who the question until you say "frank". Pretty basic but it gives you better understand about how things run.

Here is the sample output.

The learning issues here will be:

  • Define variable "smart_guy" in the flow/process.



  • In the "Question" script, we set the user input to the process variable. 



     kcontext.setVariable("smart_guy", name);




  • In the gateway constraint:


     return smart_guy.equals("frank");


For beginners, you should try it out your self.

Many thanks to Drools/jBPM development team and the community for their hard work. Many helpful resources are now available online compare to last year.

Monday, January 3, 2011

Drools 5.1 Human Task Example

It has been a while seen my last post. Lately I have been working on BPMS and Drools. I try to create a simple app using Drools Flow and Human task and now have some small success.
While learning and creating my simple app, looking for example online was difficult. Try google "Drools 5.1 Human Task Example" and see what you will get. So I decide to put more example online for reference. It may not be as complete but I'll show the parts that is working.

What I try to do is like this.
I start a flow, then it will run Action 1, then the Human Task, where it need human/external interaction, then Action 2 and finish.
Action 1 and Action 2 will just print some text on the screen. (System.out.println(...))
Human Task has these properties:
The ActorId "mina" is just a value. I think (haven't try) we can either set it at design time or run time.

I use eclipse (with Drools plugin (core and task)) to create a new drools project. I end up having these libraries in the project. Can still be clean up a bit but... let's continue.



[tricky part: Error is main-1.4.jar is missing.]
Ok. now we start with a simple java class with a main function. In the class, we have:

 private static KnowledgeBase readKnowledgeBase() throws Exception {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add(ResourceFactory.newClassPathResource("human_task_flow.bpmn"), ResourceType.BPMN2);
return kbuilder.newKnowledgeBase();
}
In the main function,


  try {
// load up the knowledge base
KnowledgeBase kbase = readKnowledgeBase();

EntityManagerFactory emf =
Persistence.createEntityManagerFactory( "org.drools.task" );
Environment env = KnowledgeBaseFactory.newEnvironment();
env.set( EnvironmentName.ENTITY_MANAGER_FACTORY, emf );

SystemEventListener systemEventListener = SystemEventListenerFactory.getSystemEventListener();

TaskService taskService = new TaskService(emf, systemEventListener);

TaskServiceSession taskSession = taskService.createSession();

taskSession.addUser(new User("Administrator"));
taskSession.addUser(new User("mina"));

MinaTaskServer server = new MinaTaskServer( taskService );
Thread thread = new Thread( server );
thread.start();

StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

WSHumanTaskHandler handler = new WSHumanTaskHandler();

ksession.getWorkItemManager().registerWorkItemHandler("Human Task", handler);

KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "test");
// start a new process instance
ksession.startProcess("HumanTaskSample");

// ksession.fireAllRules();

logger.close();
} catch (Throwable t) {
t.printStackTrace();
}

Now we run the app and you will notice a lot of stuff printed out in the console. Hopefully there is no error. :p
[tricky part: You need to create the default user "Administrator", OR ELSE...]

To know what is happening, use the Drools Audit View to view the log.

You can see that Action 1 and Human Task were triggered.
At this stage, a Task is created and saved in the database. (lazy to explain how)
Now we use Human Task View (from Drools Task plugin) to lookup for the task using UserId "mina". You will see the task with Status Reserved.

You can now select the task and complete it (click the "Complete" button).

Stage 1 works, but what if I want to programmaticly complete the task? So I also written some task client code.

package com.geneoz.drools;

import java.util.List;

import org.drools.SystemEventListenerFactory;
import org.drools.task.User;
import org.drools.task.query.TaskSummary;
import org.drools.task.service.TaskClient;
import org.drools.task.service.mina.MinaTaskClientConnector;
import org.drools.task.service.mina.MinaTaskClientHandler;
import org.drools.task.service.responsehandlers.BlockingTaskOperationResponseHandler;
import org.drools.task.service.responsehandlers.BlockingTaskSummaryResponseHandler;

public class GeneozTaskClient {

public static void main(String... args) {
TaskClient client = new TaskClient(new MinaTaskClientConnector("mina",
new MinaTaskClientHandler(
SystemEventListenerFactory.getSystemEventListener())));
try {
client.connect("127.0.0.1", 9123);
BlockingTaskSummaryResponseHandler summaryHandler = new BlockingTaskSummaryResponseHandler();
client.getTasksAssignedAsPotentialOwner("mina", "en-UK",
summaryHandler);
List tasks = summaryHandler.getResults();
TaskSummary task = null;
for (TaskSummary taskSummary : tasks) {
System.out.println(taskSummary.getId() + " : "
+ taskSummary.getName());
task = taskSummary;
}
   if (task != null) {
BlockingTaskOperationResponseHandler operationHandler = new BlockingTaskOperationResponseHandler();
client.release(task.getId(), "mina", operationHandler);
client.claim(task.getId(), "Administrator", operationHandler);
operationHandler.waitTillDone(10000);

operationHandler = new BlockingTaskOperationResponseHandler();
client.start(task.getId(), "Administrator", operationHandler);
operationHandler.waitTillDone(10000);

operationHandler = new BlockingTaskOperationResponseHandler();
client.complete(task.getId(), "Administrator", null, operationHandler);
operationHandler.waitTillDone(10000);

}

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
client.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);

}
}
}
Some explanation:
1. Create a Mina Task Client
2. Connect to default MinaTaskServer
3. Find tasks belong to "mina"
4. Release the task (from "Reserved" state to "Ready" state) so that it can be claimed by other user.
5. Start and complete the task.

And now you will have Human Task completed and Action 2 triggered.

So this is where I am currently at for the moment. Hope to discover more stuff as I move on.
Hope this example can be helpful. Sorry for the bad English. :p