9.4. Executing Service Nodes
The process engine contains a WorkItemManager that delegates the work items to the WorkItemHandlers to execute the work item. The WorkItemHandlers notify the WorkItemManager when the work item has been completed. For executing notification work items, a NotificationWorkItemHandler should be created (implementing the WorkItemHandler interface):
package com.sample; import org.drools.runtime.process.WorkItem; import org.drools.runtime.process.WorkItemHandler; import org.drools.runtime.process.WorkItemManager; public class NotificationWorkItemHandler implements WorkItemHandler { public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { // extract parameters String from = (String) workItem.getParameter("From"); String to = (String) workItem.getParameter("To"); String message = (String) workItem.getParameter("Message"); String priority = (String) workItem.getParameter("Priority"); // send email EmailService service = ServiceRegistry.getInstance().getEmailService(); service.sendEmail(from, to, "Notification", message); // notify manager that work item has been completed manager.completeWorkItem(workItem.getId(), null); } public void abortWorkItem(WorkItem workItem, WorkItemManager manager) { // Do nothing, notifications cannot be aborted } }
This WorkItemHandler sends a notification as an email and then immediately notifies the WorkItemManager that the work item has been completed. Note that not all work items can be completed directly. In cases where executing a work item takes some time, execution can continue asynchronously and the work item manager can be notified later. If a work item is aborted before it has completed, the abort method should be used to specify how the item should be aborted.
WorkItemHandlers should be registered at the WorkItemManager using the following API:
ksession.getWorkItemManager().registerWorkItemHandler( "Notification", new NotificationWorkItemHandler());
Decoupling the execution of work items from the process itself has the following advantages:
- The process is more declarative, specifying what should be executed, not how.
- Changes to the environment can be implemented by adapting the work item handler. The process itself should not be changed.
- The same processes can be used in different environments, where the work item handler is responsible for integration with the right services.
- It is easy to share work item handlers across processes and projects (which would be more difficult if the code would be embedded in the process itself).
- Different work item handlers could be used depending on the context. For example, during testing or simulation, it might not be necessary to execute the work items. In this case, specialized dummy work item handlers could be used during testing.