Appendix B. Service Tasks: WS Task, Email Task, REST Task

Service task is a task that uses a service, such as a mail service, web service, or another service.

Red Hat JBoss BPM Suite contains the following predefined service tasks:

  • A Web Service task for invoking a web service from a BPMN2 process.
  • An Email task for sending emails through a mail server.
  • A Log task that calls the SystemOutWorkItemHandler class.
  • A REST task for sending REST calls.

Note that since the tasks extend the service task, their attributes are implemented as Data Input Set assignments, and Data Output Set assignments, not as separate properties.

To use the service tasks in your process:

  1. In Business Central, click AuthoringProject Authoring.
  2. In Project Explorer, locate the project and the respective process under BUSINESS PROCESSES.
  3. Open the process in Process Designer and click 3898 to expand the Object Library.
  4. Expand the Service Tasks section and drag and drop the selected service task to the required position on the canvas.

    user guide service tasks

For more information about service tasks, see Section B.1, “WS Task”, Section B.2, “Email Task”, and Section B.3, “REST Task”.

If you require other task types, implement your task as instructed in Section 4.14, “Domain-Specific Tasks”.

B.1. WS Task

The Web Service task implements the WebServiceWorkItemHandler class. The Web Service task serves as a web service client with the web service response stored as String. To invoke a Web Service task from a BPMN process, the correct task type must be used.

B.1.1. Multiple Parameters

The Web Service task can be used to invoke a web service method with multiple parameters. To do so, the following changes must be made to the BPMN2 process definitions:

  1. In the Process Designer, click 3897 to open the Properties panel.
  2. Select the Variable Definitions property and create a process variable called pVar with the custom type Object[].
  3. Click the WS task in the Process Designer and click 3897 to open the Properties panel.
  4. Click getting started guide 6563 next to the Assignments property.
  5. Change the Parameter input variable from String to Custom and enter Object[]. Select pVar in the Source field. Click Ok.
  6. In the property panel of the WS task, enter the following in the On Entry Actions property:

    Object[] params = {"firstParam", "secondParam"}; kcontext.setVariable("pVar", params);

B.1.2. Custom Objects

In addition to primitive object types, the WebService task can use custom objects, such as Person or Employee.

To use custom objects:

  1. Create a custom model object using either the Data Modeler in Business Central, or using an external tool, like Red Hat JBoss Developer Studio.
  2. Use this custom model class in one of the WS tasks.
  3. Generate WSDL for this web service.
  4. Use Red Hat JBoss Developer Studio to generate Java classes from the WSDL.
  5. Create a .jar file that includes the model class generated from the WSDL file. Add kmodule.xml under the META-INF of the .jar.
  6. Upload the .jar to the Artifact Repository. In Business Central, add it to the list of project’s dependencies that includes the configured Web Service task. This Web Service task must have new classes generated, and cannot rely on the original ones.
  7. Modify the project configuration using the Deployment descriptor as follows:

    <kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <kbase name="defaultKieBase" default="true" eventProcessingMode="stream" equalsBehavior="identity" packages="*">
        <ksession name="defaultKieSession" type="stateful" default="true" clockType="realtime">
          <workItemHandlers>
            <workItemHandler type="new org.jbpm.process.workitem.webservice.WebServiceWorkItemHandler(ksession, runtimeManager.getEnvironment().getClassLoader())" name="WebService"/>
          </workItemHandlers>
        </ksession>
      </kbase>
    </kmodule>

    The above configuration utilizes the WebServiceWorkItemHandler.

B.1.3. Web Service Task Example

This example demonstrates a process that obtains a weather forecast for given ZIP codes. The process looks as follows:

user guide ws process
  1. In the first human task, the process asks for ZIP codes.
  2. Next, the result of the first human task is transformed into a collection that is used as an input for the service task with multiple instances.
  3. Based on the input collection, the process creates several service task instances for querying the weather forecast service.
  4. Once all the service task instances are completed, the result is logged to the console.
  5. Another human task then shows the weather forecast for the chosen ZIP codes.

After the process instance is started, the user is prompted to select the mode of the service task: synchronous or asynchronous. Note that the difference between the two can be noticeable depending on the particular service.

Input Attributes

Endpoint
The endpoint location of the web service you want to invoke.
Parameter
The object or array to be sent for the operation.
Mode
Can be SYNC, ASYNC, or ONEWAY.
Interface
The name of a service, for example Weather.
Namespace
The namespace of the web service, such as http://ws.cdyne.com/WeatherWS/.
URL
The web service URL, such as http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL.
Operation
The method name to call.

Output Attributes

Result
An object with the result.

B.2. Email Task

The Email task sends an email based on the task properties.

Registering Email Task in Business Central

Email task is not registered by default in Business Central, and therefore must be registered by the user.

Follow the procedure below to configure Business Central to use Email service task.

  1. Design a BPMN2 process definition in the Process Designer of Business Central. Add the Email task to the workflow.
  2. Select the Email task and click 3140 to open the Properties panel.
  3. Open Assignments and fill in the To, From, Subject, and Body properties, and any other relevant input attributes.

    user guide Emailtask2

    Alternatively, values can be mapped to properties using Process Variable to Task Variable mapping assignments.

    From the Process Designer, open the Properties panel and select the Variable Definitions property to map variables.

Registering EmailWorkItemHandler

EmailWorkItemHandler is the work item handler implementation of the Email Service task. The Email work item is included in the work item definition file by default, however EmailWorkItemHandler is not a part of the default kie-deployment-descriptor.xml file, and therefore must be explicitly registered by the user.

To register EmailWorkItemHandler:

  1. Open the Project Editor and click Project Settings: Project General Settings → Deployment descriptor from the menu.
  2. Scroll down to the Work Item handlers list and click Add to add the EmailWorkItemHandler to the list. For example:

    new org.jbpm.process.workitem.email.EmailWorkItemHandler("localhost","25","me@localhost","password");

    Alternatively, email server parameters can be supplied using a constructor in the ProcessMain.java file:

    EmailWorkItemHandler emailWorkItemHandler = new EmailWorkItemHandler("localhost", "1125", "", "",true); ksession.getWorkItemManager().registerWorkItemHandler("Email", emailWorkItemHandler );

Configuring Deadline

You can configure the Deadline email feature in two ways:

  1. Mail Session on Container Level

    With this method, the Deadline email feature uses EmailSessionProducer to look up the mail/jbpmMailSession using JNDI. The following example is for Red Hat JBoss EAP standalone.xml:

    <system-properties>
    ...
      <property name="org.kie.mail.session" value="java:jboss/mail/mail/jbpmMailSession"/>
    ...
    </system-properties>
    ...
    <subsystem xmlns="urn:jboss:domain:mail:1.2">
      <mail-session name="default" jndi-name="mail/jbpmMailSession" >
        <smtp-server outbound-socket-binding-ref="mail-smtp" tls="true">
          <login name="email@gmail.com" password="___"/>
        </smtp-server>
      </mail-session>
    </subsystem>
    ...
    <outbound-socket-binding name="mail-smtp">
      <remote-destination host="smtp.gmail.com" port="587"/>
    </outbound-socket-binding>
  2. Using email.properties

    If the mail/jbpmMailSession is not found, Red Hat JBoss BPM Suite searches for /email.properties on the class path with content similar to the following:

    mail.smtp.host=localhost
    mail.smtp.port=25
    mail.from=xxx@xxx.com
    mail.replyto=xxx@xxx.com

Input Attributes

The following parameters are required by default:

To
The email address of the email recipient. Separate multiple addresses by a semicolon (;).
From
The email address of the sender of the email.
Subject
The subject of the email.
Body
The HTML body of the email.

The following parameters are optional, and can be configured by mapping values assigned to these properties using Process Variable to Task Variable mapping in Assignments:

Reply-To
Sets the reply recipient address to the From address of the received message. Separate multiple addresses by a semicolon (;).
Cc
The email address of the carbon copy recipient. Separate multiple addresses by a semicolon (;).
Bcc
The email address of the blind carbon copy recipient. Separate multiple addresses by a semicolon (;).
Attachments
The URL of the files you want to attach to the email. Multiple attachments can be added to the email using a comma (,) to separate each URL in the list.
Debug

A boolean value related to the execution of the Email work item. For example:

"Success" = true

The Email task is completed immediately and cannot be aborted.

B.3. REST Task

The REST task performs REST calls and outputs the response as an object.

RestWorkItemHandler is capable of interacting with the REST service, and supports both types of services:

  • Secured: requires authentication.
  • Open: does not require authentication.

Authentication methods currently supported are:

  • BASIC
  • FORM_BASED

Authentication information can be given on handler initialization and can be overridden using work item parameters. All other configuration options must be given in the work item parameters map:

Input Attributes

Url

Target URL to be invoked. This attribute is mandatory.

It is often necessary to configure the URL attribute with an expression. This gives you the ability to change the URL dynamically throughout the runtime. For example:

http://DOMAIN:PORT/restService/getCars?brand=#{carBrand}

In this example, carBrand is replaced by the value of the carBrand process variable during runtime.

Method
The method of the request, such as GET, POST, or other. The default method is GET.
ContentType
The data type if you are sending data. The supported data types are application/json and application/xml. This attribute is mandatory for POST and PUT requests. If you want to use this attribute, map it as a data input variable in the Data I/O dialogue of the task.
Content
The data you want to send. This attribute is mandatory for POST and PUT requests. This is an optional parameter. If you want to use it, map it as a data input variable in the Data I/O dialogue of the task.
ConnectTimeout
The connection timeout. The default value is 60 seconds.
ReadTimeout
The timeout on response. The default value is 60 seconds.
Username
The user name for authentication. This attribute overrides the handler initialization user name.
Password

The password for authentication. This attribute overrides the handler initialization password.

User name and password for basic authentication can be passed at construction time using the following:

RESTWorkItemHandler(String username, String password);
AuthUrl

The URL that is handling authentication when using the AuthenticationType.FORM_BASED authentication method.

Use the following constructor for FORM_BASED authentication:

public RESTWorkItemHandler(String username, String password, String authUrl, ClassLoader classLoader) {
  this();
  this.username = username;
  this.password = password;
  this.type = AuthenticationType.FORM_BASED;
  this.authUrl = authUrl;
  this.classLoader = classLoader;
}

The following is an example of how the constructor must be used in Deployment descriptor:

new org.jbpm.process.workitem.rest.RESTWorkItemHandler("username","password","http://mydomain.com/my-j-security-check-url",classLoader)
Important

AuthUrl configuration requires the typical implementation for FORM_BASED authentication in Java EE servers, and therefore should point to the j_security_check URL. Similarly, inputs for user name and password must be bound to j_username and j_password when using FORM_BASED authentication, otherwise authentication may fail.

ResultClass
This attribute determines the class to which the value from the Result attribute will be converted. If not provided, the default value is String.
HandleResponseErrors
An optional parameter that instructs the handler to throw errors in case of unsuccessful response codes. For information on how to handle response errors, see the section called “Handling REST Response Error”.

Output Attributes

Result
The result returned by the REST service.
Status
The variable contains a value from interval 200 to 300 if the REST request was successful, or an error response code if the request was unsuccessful. This variable is not mapped by default. If you want to use this variable, map it manually as an output variable of the REST task.
StatusMsg
If the service returned an error response, this variable will contain the error response message. This variable is not mapped by default. If you want to use this variable, map it manually as an output variable of the REST task.

All output attributes are String by default.

Handling REST Response Error

HandleResponseErrors can be handled in two ways:

  1. In the Process Definition Workflow

    1. Status: When RESTWorkItemHandler produces a Status output variable that includes an HTTP response code. This can be mapped to a process variable and used in a XOR gateway to determine the service outcome.

      user guide REST1
    2. StatusMsg: The output variable StatusMsg includes additional messages sent by the server, and is filled only when the HTTP Code is not between 200 and 300.
  2. Using a Boundary Event

    To enable this feature, set the REST work item input variable HandleResponseErrors to true.

    Important

    The HandleResponse must have a valid boolean expression or be left empty, which is equivalent to false. Otherwise, the REST task will throw an exception.

    When the REST work item input variable HandleResponseErrors is set to true, the RESTWorkItemHandler handler will, upon receiving an HTTP response code outside of the 200-300 interval, throw the following Java exception:

    public RESTServiceException(int status, String response, String endpoint) {
      super("Unsuccessful response from REST server (status " + status +", endpoint " + endoint +", response " + response +"");

    With the HandleResponseErrors option enabled, this error can be caught using a boundary event:

    user guide REST2

    The provided example includes:

    • A WorkItemHandlerRuntimeException restError process variable.
    • A WorkItemHandlerRuntimeException BoundaryError event-defined output variable that has been mapped to the restError process variable.
    • A Script task that includes the following code:

      org.jbpm.process.workitem.rest.RESTServiceException x = (org.jbpm.process.workitem.rest.RESTServiceException) restError.getCause().getCause();

      This code allows RestServiceException to be extracted from WorkItemHandlerRuntimeException. Using RestServiceException provides access to the following methods:

    • getResponse
    • getStatus
    • getEndpoint

      The next line in the Script task is:

      System.out.println("response:"+x.getResponse());

      This provides the full error message as returned by the server.