4.14. Domain-specific Tasks

A domain-specific Task represents a custom Task element with custom properties and handling specific tasks for the given field or company. It is used repeatedly in different business processes and typically accommodates interactions with other technical system.
In Red Hat JBoss BPM Suite, domain-specific task nodes are referred to as custom work items or custom service nodes.
When creating custom work items, you define the following:
work item handler
The work item handler is a Java class that defines how to execute the custom task type. (Just like all Process elements, Tasks are executed in the Execution Engine (more precisely in the Task Engine), which contains a work item handler class, that defines how to handle the particular work item. Therefore, to allow the Execution Engine to execute your custom work item, you need to create a work item handler class for the custom work item and register it with the Execution Engine.)
work item definition
The work item definition defines how the custom task is presented (its name, icon, parameters).

Note

In BPMN2, custom work items are defined either as types of <task> nodes or <serviceTask> or <sendTask> nodes.

4.14.1. Work item definition

A work item definition is a resource in a project that defines how a work item is presented (its name, icon, parameters), that is, it defines the what part (the how part is implemented as a class that implements WorkItemHandler).
Depending on the Process Designer you are using, you define a work item definition in the following ways:
Web Process Designer
A work item definition is defined as an MVEL construct in a project resource (the custom work item node will appear on the palette; refer to Section 4.14.1.2, “Creating a work item definition”).
JBoss Developer Studio Process Designer
The BPMN2 <task> or <task>-type elements can be modified to work with WorkItemHandler implementations.
To do so, create a WID_NAME.wid file under $PROJECT_HOME/src/main/resources/META-INF folder. The contents of this file will be the same as the ones that you will create as if under Business Central (Web Process Designer). If there are any icons, create these icons under a folder $PROJECT_HOME/src/main/resources/, and store the icon images files in icon folder.
Once you save this file, you can use your custom service task with the JBDS Process Designer. You can find your task in the CustomTasks category on a pallet.
A work item has the following properties:
  • name unique in the given work item set
  • description with arbitrary text
  • version number
  • parameters with a set of work item parameters used as properties
  • displayName used in the palette
  • icon with the path to the icon file for the Task element
  • category the node is added to in the palette (if the defined category does not exit, a new category is created)
  • defaultHandler with the class that implements the WorkItemHandler class and is used to execute the work item
  • dependencies the defaultHandler requires for its execution

Important

Work item definition contains a collection of work item definitions. Therefore make sure to use square brackets correctly.
Also make sure you import any used classes and that you validate the definition once finished.

Example 4.8. Calendar work item definition

import org.drools.core.process.core.datatype.impl.type.StringDataType;

[
  [
    "name" : "Google Calendar",
    "description" : "Create a meeting in Google Calendar",
    "version" : "1.0",
    "parameters" : [
    	"FilePath" : new StringDataType(),
    	"User" : new StringDataType(),
    	"Password" : new StringDataType(),
    	"Body" : new StringDataType()
    ],
    "displayName" : "Google Calendar",
    "icon" : "calendar.gif",
    "eclipse:customEditor" : "org.drools.eclipse.flow.common.editor.editpart.work.SampleCustomEditor",
    "category" : "Google",
    "defaultHandler" : "org.jbpm.process.workitem.google.calendar.GoogleCalendarWorkItemHandler",
    "dependencies" : [
    ]
  ]
]

4.14.1.1. Work item handler

A work item handler is a Java class used to execute or abort work items (work items need to be aborted if their execution is to be asynchronous). The class defines the business logic of the work item, for example how to contact another system and request information which is then parsed into the custom Task parameters. Every work item handler must implement the org.kie.api.runtime.process.WorkItemHandler interface.

Note

You can customize how a custom work item is processed on a particular system by registering different work item handlers on different systems. You can also substitute a work item handler with a mock WorkItemHandler for testing.
Red Hat JBoss BPM Suite comes with multiple work item handlers in the following modules:
  • The jbpm-bpm2 module in the org.jbpm.bpmn2.handler package contains the following work item handlers:
    • ReceiveTaskHandler (for the BPMN <receiveTask> element)
    • SendTaskHandler (for the BPMN <sendTask> element)
    • ServiceTaskHandler (for the BPMN <serviceTask> element)
  • The jbpm-workitems module in packages within org.jbpm.process.workitem contains work item handlers, some of which are listed below:
    • ArchiveWorkItemHandler creates a ZIP archive (it takes a list of files as its parameter, which are included in the archive)
    • WebServiceWorkItemHandler
    • TransformWorkItemHandler
    • RSSWorkItemHandler
    • RESTWorkItemHandler
    • JavaInvocationWorkItemHandler
    • JabberWorkItemHandler
    • JavaHandlerWorkItemHandler
    • FTPUploadWorkItemHandler
    • ExecWorkItemHandler
    • EmailWorkItemHandler
The work item handlers must define the executeWorkItem() and abortWorkItem() methods as defined by the WorkItemHandler interface. These are called during runtime on work item execution.
When a work item is executed, the following is performed:
  1. Information about the Task are extracted from the WorkItem instance.
  2. The work item business logic is performed.
  3. The Process instance is informed that the work item execution finished (completed or aborted) using the respective method of the WorkItemManager:
    • for completing execution:
      import org.kie.api.runtime.process.WorkItemManager;
      ...
      WorkItemManager.completeWorkItem(long workItemId, Map<String, Object> results)
    • for aborting execution:
      import org.kie.api.runtime.process.WorkItemManager;
      ...
      WorkItemManager.abortWorkItem(long workItemId, Map<String, Object> results)
If a work item cannot be completed immediately and it is required that the Process execution continues while the work item completes the execution, the Process execution can continue asynchronously and the work item manager can be notified about the work item completion later.
To abort the work item, use the WorkItemHandler.abortWorkItem() before it is completed Section 5.1.4.1, “Asynchronous execution”.

4.14.1.2. Creating a work item definition

To create and define a work item definition in Web Process Designer, do the following:
  1. In the Project Explorer panel (the Project Authoring perspective), select your project.
  2. In the perspective menu, click New ItemWork Item Definition.
  3. In the Create new dialogue box, define the definition details:
    • In the Name field provide the definition name.
    • Click the OK button.
  4. A new tab with the work item definition template opens up in the Work Item editor.

    Note

    Whenever a user creates a new business process in some project, the default WID will be created. Users will be able to reuse or directly alter the WID file whenever necessary. In addition, there will always be a default WID once the BPMN process is created.
  5. In the editor, edit the source of the MVEL work item definition. The definition is stored in the current package.
    If you are planning to add the work item using the service repository as opposed to adding the work item handler to the classpath, make sure to define its dependencies, category, etc.
    If you are creating the definition out of Business Central, your project directory structure should be similar to PROJECT_NAME/src/main/resources/PACKAGE_NAME/WID_NAME.wid (visible in the Repository view).

    Example 4.9. Example wid file

    import org.drools.core.process.core.datatype.impl.type.StringDataType;
    import org.drools.core.process.core.datatype.impl.type.ObjectDataType;
    
    [
      [
        "name" : "MyTask", 
        "parameters" : [ 
            "MyFirstParam" : new StringDataType(), 
            "MySecondParam" : new StringDataType(), 
            "MyThirdParam" : new ObjectDataType() 
        ], 
        "results" : [ 
            "Result" : new ObjectDataType("java.util.Map") 
        ], 
        "displayName" : "My Task", 
        "icon" : "" 
      ]
    ]
  6. Upload and assign an icon to the Work Item:
    1. Click New ItemUploaded file.
    2. In the Create new Uploaded file dialogue box, define the resource name and make sure to include the file's extension in the name. Click the Choose File... option to locate and upload the file (png or gif, 16x16 pixels). Click Ok.
    3. Make sure your mouse is positioned within the blank " " of the icon parameter:
          "icon" : " "
      Click the Select icon to add drop-down and click the icon file. The icon path will appear within the parameter:
          "icon" : "ExampleIcon.png"
  7. In the Process Designer, check if your work item is available in the palette.

4.14.1.3. Creating a work item handler

Once you have created the work item definition, do the following:
  1. Create a maven project with your implementation of a work item handler with the required business logic. Make sure to call the completeWorkItem() function to finish the business logic execution and add the kie-api artifact with the 6.x.x.redhat-x version value as the project dependency.

    Example 4.10. Notification work item handler

    package com.sample;
    
    import org.kie.api.runtime.process.WorkItem;
    import org.kie.api.runtime.process.WorkItemHandler;
    import org.kie.api.runtime.process.WorkItemManager;
    
    public class NotificationWorkItemHandler implements WorkItemHandler {
    
      public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
        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.
      The ServiceRegistry class is an example class implementing the task business logic. 
    */
        EmailService service = ServiceRegistry.getInstance().getEmailService();
        service.sendEmail(from, to, "Notification", message);
    
    /* 
      Notify manager that work item has been completed.
      The completeWorkItem() call completes the work item execution.
    */
        manager.completeWorkItem(workItem.getId(), null);
      }
    
      public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
      // Do nothing, notifications cannot be aborted
      }
    
    }

    Important

    If the WorkItemManager is not notified about the work item completion, the process engine is never notified that your work item node has completed.
  2. Register the work item handler in the DEPLOY_DIR/business-central.war/WEB-INF/classes/META-INF/CustomWorkItemHandlers.conf file.
    The CustomWorkItemHandlers.conf file contains information like the following:
    [
      "Log": new org.jbpm.process.instance.impl.demo.SystemOutWorkItemHandler(),
      "WebService": new org.jbpm.process.workitem.webservice.WebServiceWorkItemHandler(ksession),
      "Rest": new org.jbpm.process.workitem.rest.RESTWorkItemHandler()
    ]
    Notice the "Rest" value in the previous file. This indicates the WorkItemHandler is capable of interacting with REST services. It supports both secured/authenticated and open/not authenticated services.
    This REST value is defined in the project's WID file in the following manner:
    [
      "name" : "Rest",
      "parameters" : [
      
      //Url - Mandatory resource location to be invoked.
          "Url" : new StringDataType(),
          
      //Method - Defaults to GET and is the HTTP method that will be executed.
          "Method" : new StringDataType(),
          
      //ConnectionTimeout - Defaults to 60 seconds for the connection timeout.
          "ConnectTimeout" : new StringDataType(),
      
      //ReadTimeout - Defaults to 60 seconds for the read timeout.
          "ReadTimeout" : new StringDataType(),
          
      //Username - The username for authentication that overrides the one given on handler initialization.
          "Username" : new StringDataType(),
          
      //Password - The password for authentication that overrides the one given on handler initialization.
          "Password" : new StringDataType()
      ],
      "results" : [
          "Result" : new ObjectDataType(),
      ],
      "displayName" : "REST",
      "icon" : "defaultservicenodeicon.png"
    ]
    The configuration options displayed about must be given via the work item parameter. The authentication information can be given on handler initialization, but it can be overridden via the work item parameter.
  3. Compile the project. The resulting JAR file should be placed in (DEPLOY_DIR/business-central.war/WEB-INF/lib/).
  4. Restart the server.
Registering via kmodule.xml
An alternative to registering work item handlers in CustomWorkItemHandlers.conf is to configure them with kmodule.xml. This is beneficial in that it avoids a complete server restart.
  1. Register the work item handler in the Administration menu path PROJECT_NAME/src/main/resources/META-INF/kmodule.xml
  2. Make sure the work item handler is given as a MVEL expression; for example, new org.jbpm.wih.CustomHandler() or FQCN expression: org.jbpm.wih.CustomHandler.
  3. Compile the project. Upload the work item handler JAR into Business Central via the Artifact Repository. Then add it as a dependency for the project where the user wants to use this handler.

4.14.1.4. Registering a Work Item handler

When executing processes in Business Central, WorkItemHandlers are registered in the ksession automatically. However, in order for them to be used in embedded mode, the WorkItemManager registers WorkItemHandler instances. Likewise, in the example below, the NotificationWorkItemHandler needs to be registered in order for it to be used with a process containing a Notification work item:
  1. Register the work item handler like the following:
    /* Create the drools name of the <task> and the custom work item handler instance */
    KieSession kieSession = kieBase.newKieSession();
    ksession.getWorkItemManager().registerWorkItemHandler(
      "Notification", 
      new NotificationWorkItemHandler()
    );
    
  2. Look at the BPMN2 syntax for the process. The previous registration example would appear as follows:
    <?xml version="1.0" encoding="UTF-8"?> 
    <definitions id="Definition"
                 xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
                 xs:schemaLocation="http://www.omg.org/spec/BPMN/20100524/MODEL BPMN20.xsd"
    ...
                 xmlns:tns="http://www.jboss.org/drools">
    
    ...
    
        <process isExecutable="true" id="myCustomProcess" name="Domain-Specific Process" >
    
    ...
    <!-- The tns:taskName attribute in the <task> node is necessary for the WorkItemManager to be able to see which WorkItemHandler instance should be used with which task or work item. -->
        <task id="_5" name="Notification Task" tns:taskName="Notification" >
    
    ...

Note

Different work item handlers could be used depending on the context. For example, during testing or simulation, it might not be necessary to actually execute the work items.

4.14.2. Service repository

The service repository feature allows you to import an already existing work item from a repository directly into your project. It allows multiple users to reuse generic work items , such as work items allowing integration with Twitter, performing file system operations, etc. Imported work items are automatically added to your palette and ready to use.

Important

A public service repository with various predefined work items is available at http://docs.jboss.org/jbpm/v6.0/repository/.

Note

Although you can import any of these work items, please note that in Red Hat JBoss BPM Suite, only the following work items are available by default (and supported): Log, Email, Rest, WS. You can still import the other work items, but they are not supported by Red Hat.

4.14.2.1. Importing from a service repository

To import a work item from a service repository, do the following:
  1. Open your Process in the Web Process Designer.
  2. In the editor menu, click the Connect to a Service Repository button.
  3. In the Service Repository Connection window, define the location of the repository on the location input line and click Connect.
    Service Repository Connection window with loaded content

    Figure 4.26. Establishing connection to a service repository

  4. Double-click the asset to import it.

Important

Every work item must be registered in the DEPLOY_DIRECTORY/business-central.war/WEB-INF/classes/META-INF/CustomWorkItemHandler.conf file. If a work item is not registered in the file, it will not be available for use.

4.14.2.2. Setting up a service repository

A service repository can be any repository, local or remote, with the index.conf file in its root directory.
Repository configuration file
The index.conf file must be located in the root directory of the service repository. It contains a list of any directory within the repository that are to be considered directories of the service repository.

Example 4.11. index.conf

Email
FileSystem
ESB
FTP
Google
Java
Jabber
Rest
RSS
Transform
Twitter
Each directory contains either another index.conf file so as to serve as a directory or work item resources. Note that the hierarchical structure of the repository is not shown when browsing the repository using the import wizard, as the category property in the configuration file is used for that.
Work items and their resources
Directories with work items must contain:
  • A work item configuration file is a file with the same name as the parent directory (for example, Twitter.conf) that contains details about the work item resources in the service repository. The file is an extension of the work item definition file (refer to Section 4.14.1, “Work item definition”). Note, that the configuration file must contain references to any dependencies the work item handler requires. Optionally, it can define the documentation property with a path to documentation and category which defines the category the custom work item is placed under in the repository.

    Example 4.12. Work item configuration file

    import org.drools.core.process.core.datatype.impl.type.StringDataType;
    [ 
      [
      "name" : "Twitter",
      "description" : "Send a twitter message",
      "parameters" : [
      "Message" : new StringDataType()
      ],
      "displayName" : "Twitter",
      "eclipse:customEditor" : "org.drools.eclipse.flow.common.editor.editpart.work.SampleCustomEditor",
      "icon" : "twitter.gif",
      "category" : "Communication",
      "defaultHandler" : "org.jbpm.process.workitem.twitter.TwitterHandler",
      "documentation" : "index.html",
      //Every work item definition should specify dependencies even if it doesn't have one.
      "dependencies" : []
        [
      	"file:./lib/jbpm-twitter.jar",
      	"file:./lib/twitter4j-core-2.2.2.jar"
        ]
      ]
    ]
  • All resources referenced in the work item configuration file: icon, documentation, and dependencies.