Blog Posts BPMN DMN

Running Custom Tasks in jBPM With Work Item Handlers

Blog: Drools & jBPM Blog

Running Custom Tasks in jBPM with work item handlers

Introduction

You can use a WorkItemHandler to run custom tasks during the execution of a process in jBPM. In this article, you will run through the steps to create a custom task and use it in a process.

IMPORTANT: This tutorial uses version 7.72.0.Final of jBPM.

The application you’re going to create is a process that concatenates first and last names, and prints the result to the console.

The concatenation is going to be processed in a custom task. So, start by creating the WorkItemHandler.

NOTE: If you don’t want to create the project, you can clone it from GitHub.

Creating the WorkItemHandler

  1. Run the following command to create a work item handler project:

    mvn archetype:generate 
      -DarchetypeGroupId=org.jbpm 
      -DarchetypeArtifactId=jbpm-workitems-archetype 
      -DarchetypeVersion=7.72.0.Final 
      -DgroupId=org.acme  
      -DartifactId=myconcatworkitem 
      -Dversion=1.0.0-SNAPSHOT 
      -DclassPrefix=MyConcat
  2. Replace the content of src/main/java/org/acme/MyConcatWorkItemHandler.java file with the following:

    package org.acme;
    
    import org.jbpm.process.workitem.core.AbstractLogOrThrowWorkItemHandler;
    import org.jbpm.process.workitem.core.util.RequiredParameterValidator;
    import org.jbpm.process.workitem.core.util.Wid;
    import org.jbpm.process.workitem.core.util.WidMavenDepends;
    import org.jbpm.process.workitem.core.util.WidParameter;
    import org.jbpm.process.workitem.core.util.WidResult;
    import org.jbpm.process.workitem.core.util.service.WidAction;
    import org.jbpm.process.workitem.core.util.service.WidAuth;
    import org.jbpm.process.workitem.core.util.service.WidService;
    import org.kie.api.runtime.process.WorkItem;
    import org.kie.api.runtime.process.WorkItemManager;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @Wid(widfile = "MyConcatDefinitions.wid", name = "MyConcatDefinitions",
            displayName = "MyConcatDefinitions",
            defaultHandler = "mvel: new org.acme.MyConcatWorkItemHandler()",
            documentation = "myconcatworkitem/index.html",
            category = "myconcatworkitem",
            icon = "MyConcatDefinitions.png",
            parameters = {
                    @WidParameter(name = "FirstName"),
                    @WidParameter(name = "LastName")
            },
            results = {
                    @WidResult(name = "FullName")
            },
            mavenDepends = {
                    @WidMavenDepends(group = "org.acme", artifact = "myconcatworkitem", version = "1.0.0-SNAPSHOT")
            },
            serviceInfo = @WidService(category = "myconcatworkitem", description = "${description}",
                    keywords = "",
                    action = @WidAction(title = "Sample Title"),
                    authinfo = @WidAuth(required = true, params = {"FirstName", "LastName"},
                            paramsdescription = {"First name", "Last name"},
                            referencesite = "referenceSiteURL")
            )
    )
    public class MyConcatWorkItemHandler extends AbstractLogOrThrowWorkItemHandler {
    
        public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
            try {
                RequiredParameterValidator.validate(this.getClass(), workItem);
    
                String firstName = (String) workItem.getParameter("FirstName"); // Gets the "FirstName" parameter
                String lastName = (String) workItem.getParameter("LastName"); // Gets the "LastName" parameter
    
                String fullName = firstName + " " + lastName; // Concatenates the "firstName" and "lastName"
    
                Map results = new HashMap();
                results.put("FullName", fullName); // Adds "fullName" to the "results" object
    
                manager.completeWorkItem(workItem.getId(), results);
            } catch (Throwable cause) {
                handleException(cause);
            }
        }
    
        @Override
        public void abortWorkItem(WorkItem workItem,
                                  WorkItemManager manager) {
        }
    }
  3. Update the src/test/java/org/acme/MyConcatWorkItemHandlerTest.java test file with the following:

    package org.acme;
    
    import org.drools.core.process.instance.impl.WorkItemImpl;
    import org.jbpm.process.workitem.core.TestWorkItemManager;
    import org.jbpm.test.AbstractBaseTest;
    import org.junit.Test;
    
    import static org.junit.Assert.assertEquals;
    import static org.junit.Assert.assertNotNull;
    import static org.junit.Assert.assertTrue;
    
    public class MyConcatWorkItemHandlerTest extends AbstractBaseTest {
    
        @Test
        public void testHandler() {
            WorkItemImpl workItem = new WorkItemImpl();
            workItem.setParameter("FirstName", "John");
            workItem.setParameter("LastName", "Doe");
    
            TestWorkItemManager manager = new TestWorkItemManager();
    
            MyConcatWorkItemHandler handler = new MyConcatWorkItemHandler();
            handler.setLogThrownException(true);
            handler.executeWorkItem(workItem, manager);
    
            assertNotNull(manager.getResults());
            assertEquals(1, manager.getResults().size());
            assertEquals("John Doe", manager.getResults().get(0L).get("FullName"));
            assertTrue(manager.getResults().containsKey(workItem.getId()));
        }
    }
  4. Package and install the work item handler project into your Maven local repository.

    From the myconcatworkitem directory, run:

    mvn clean install

    You should see the generated myconcatworkitem-1.0.0-SNAPSHOT.jar file in the target directory.

Adding the work item handler to Business Central as a Custom Task

  1. Open Business Central
  2. Click the gear icon in the upper-right corner
  3. Click "Custom Tasks Administration"
  4. Click the "Add Custom Task" button
  5. Upload the myconcatworkitem-1.0.0-SNAPSHOT.jar file. After the upload, the Custom Task should appear in the list of Custom Tasks in the same window as the "Add Custom Task" button
  6. Locate the Custom Task (MyConcatDefinitions) in the list and activate it

Installing the Custom Task in your project

  1. Open your project in Business Central and click "Settings"
  2. Click "Custom Tasks" on the left corner
  3. Click the "Install" button of the Custom Task (MyConcatDefinitions)
  4. Click the "Save" button
  5. On the left side of the screen, click "Dependencies"
  6. Click "Add from Repository" and then search for the "myconcatworkitem" artifact and select it
  7. Click the "Save" button and confirm the dialog

Using the Custom Task

  1. Create a new Business Process

  2. Add three process variables to the process. In "Properties", expand "Process Data" and add the following String variables:

    • firstName
    • lastName
    • fullName
  3. Add a new Start Event

  4. Add a new End Event

  5. Click "Custom Tasks" (gear button on the left side of the screen), select "MyConcatDefinitions" and add it to the process

  6. Select the node you just added and in Properties, expand "Data Assignments" and click the edit button

  7. Bind the process variables to the Custom Task parameters and click OK

  8. Add a Script Task to the process

  9. Select the node you just added and in Properties, expand "Implementation/Execution" and add the following script:

    System.out.println(fullName);
  10. Connect all the nodes in the process

    Start - MyConcatDefinitions - Task - End
  11. Save and deploy the process

When you start a new process instance, you’ll be asked to enter the first and last names. After submitting, you will see the concatenated fullName in the console.

Conclusion

In this tutorial, you’ve learned how to create and use a custom work item handler in jBPM by creating a process that concatenates the first and last names received as parameters.

The post Running Custom Tasks in jBPM With Work Item Handlers appeared first on KIE Community.

Leave a Comment

Get the BPI Web Feed

Using the HTML code below, you can display this Business Process Incubator page content with the current filter and sorting inside your web site for FREE.

Copy/Paste this code in your website html code:

<iframe src="https://www.businessprocessincubator.com/content/running-custom-tasks-in-jbpm-with-work-item-handlers/?feed=html" frameborder="0" scrolling="auto" width="100%" height="700">

Customizing your BPI Web Feed

You can click on the Get the BPI Web Feed link on any of our page to create the best possible feed for your site. Here are a few tips to customize your BPI Web Feed.

Customizing the Content Filter
On any page, you can add filter criteria using the MORE FILTERS interface:

Customizing the Content Filter

Customizing the Content Sorting
Clicking on the sorting options will also change the way your BPI Web Feed will be ordered on your site:

Get the BPI Web Feed

Some integration examples

BPMN.org

XPDL.org

×