13.3. Runtime REST API

Runtime REST API are calls to the Execution Server and to the Process Execution Engine, Task Execution Engine, and Business Rule Engine. As such they allow you to request and manipulate runtime data.
Except the Execute calls, all other REST calls can either use JAXB or JSON
The calls are synchronous and return the requested data as JAXB objects.
While using JSON, the JSON media type ("application/json") should be added to the ACCEPT header of the REST Call.
Their parameters are defined as query string parameters. To add a query string parameter to a runtime REST API call, add the ? symbol to the REQUEST_BODY and the parameter with the parameter value; for example, rest/task/query?workItemId=393 returns a TaskSumamry list of all tasks based on the work item with ID 393. Note that parameters and their values are case-sensitive.
When a runtime REST API call requires a Map parameter, you can submit key-value pairs to the operation using a query parameter prefixed with the keyword map_ keyword; for example,
map_age=5000
is translated as
{ "age" => Long.parseLong("5000") }
Note that all runtime calls return a JAXB object.

Example 13.7. A GET call that returns all tasks to a locally running application using curl

curl -v -H 'Accept: application/json' -u eko 'localhost:8080/kie/rest/tasks/'
To perform runtime REST calls from your Java application you need to create a RemoteRestSessionFactory object and request a newRuntimeEngine() object from the RemoteRestSessionFactory. The RuntimeEngine can be then used to create a KieSession.

Example 13.8. A GET call that returns a task details to a locally running application in Java with the direct tasks/TASKID request

public Task getTaskInstanceInfo(long taskId) throws Exception {
    URL address = new URL(url + "/task/" + taskId);
    ClientRequest restRequest = createRequest(address);

    ClientResponse<JaxbTaskResponse> responseObj = restRequest.get(JaxbTaskResponse.class);
    ClientResponse<InputStream> taskResponse = responseObj.get(InputStream.class);
    JAXBContext jaxbTaskContext = JAXBContext.newInstance(JaxbTaskResponse.class);
    StreamSource source  = new StreamSource(taskResponse.getEntity());
    return jaxbTaskContext.createUnmarshaller().unmarshal(source, JaxbTaskResponse.class).getValue();
       
}

private ClientRequest createRequest(URL address) {
    return getClientRequestFactory().createRequest(address.toExternalForm());
    }

private ClientRequestFactory getClientRequestFactory() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST,
    AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(userId, password));
    ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);
    return new ClientRequestFactory(clientExecutor, ResteasyProviderFactory.getInstance());
}
Note that if you want to send multiple commands to an entity, in this case task, consider using the execute call (refer to Section 13.3.4, “Execute operations”).
While interacting with the Remote API, some classes are to be included in the deployment to enable a user to pass instances of their own classes as parameters to certain operations. REST calls that start with /task often do not contain any information about the associated deployment. In such a case and extra query parameter (deploymentId) is added to the REST call allowing the server to find the appropriate deployment class and deserialize the information passed with the call.

13.3.1. Usage Information

13.3.1.1. Pagination

The pagination parameters allow you to define pagination of the results a REST call returns. The following pagination parameters are available:
page or p
number of the page to be returned (by default set to 1, that is, page number 1 is returned)
pageSize or s
number of items per page (default value 10)
If both, the long option and the short option, are included in a URL, the longer version of the parameter takes precedence. When no pagination parameters are included, the returned results are not paginated.
Pagination parameters can be applied to the following REST requests:
/task/query
/history/instance
/history/instance/{id: [0-9]+}
/history/instance/{id: [0-9]+}/child
/history/instance/{id: [0-9]+}/node
/history/instance/{id: [0-9]+}/node/{id: [a-zA-Z0-9-:\\.]+}
/history/instance/{id: [0-9]+}/variable/
/history/instance/{id: [0-9]+}/variable/{id: [a-zA-Z0-9-:\\.]+}
/history/process/{id: [a-zA-Z0-9-:\\.]+}

Example 13.9. REST request body with the pagination parameter

/history/instance?page=3&pageSize=20   
/history/instance?p=3&s=20

13.3.1.2. Object data type parameters

By default, any object parameters provided in a REST call are considered to be Strings. If you need to explicitly define the data type of a parameter of a call, you can do so by adding one of the following values to the parameter:
  • \d+i: Integer
  • \d+l: Long

Example 13.10. REST request body with the Integer mySignal parameter

/rest/runtime/business-central/process/org.jbpm.test/instance/2/signal?mySignal=1234i
Note that the intended use of these object parameters is to define data types of send Signal and Process variable values (consider for example the use in the startProcess command in the execute call; refer to Section 13.3.4, “Execute operations”).

13.3.2. Runtime calls

Runtime REST calls allow you to acquire and manage data related to the runtime environment; you can provide direct REST calls to the Process Engine and Task Engine of the Process Server (refer to the Components section of the Administration and Configuration Guide.
To send calls to other Execution Engine components or issue calls that are not available as direct REST calls, use the generic execute call to runtime (/runtime/{deploymentId}/execute/{CommandObject}; refer to Section 13.3.4, “Execute operations”).

13.3.2.1. Process calls

The REST /runtime/{deploymentId}/process/ calls are send to the Process Execution Engine.
The following process calls are provided:
/runtime/{deploymentId}/process/{procDefID}/start
creates and starts a Process instance of the provided Process definition [POST]
/runtime/{deploymentId}/process/instance/{procInstanceID}
returns the details of the given Process instance [GET]
/runtime/{deploymentId}/process/instance/{procInstanceID}/signal
sends a signal event to the given Process instance [POST]
The call accepts query map parameter with the Signal details.

Example 13.11. A local signal invocation and its REST version

ksession.signalEvent("MySignal", "value", 23l);
curl -v -u admin 'localhost:8080/business-central/rest/runtime/myDeployment/process/instance/23/signal?signal=MySignal&event=value'
/runtime/{deploymentId}/process/instance/{procInstanceID}/abort
aborts the Process instance [POST]
/runtime/{deploymentId}/process/instance/{procInstanceID}/variables
returns variable of the Process instance [GET]
Variables are returned as JaxbVariablesResponse objects. Note that the returned variable values are strings.

13.3.2.2. Signal calls

The REST signal/ calls send a signal defined by the provided query map parameters either to the deployment or to a particular process instance.
The following signal calls are provided:
/runtime/{deploymentId}/process/instance/{procInstanceID}/signal
sends a signal to the given process instance [POST]
See the previous subsection for an example of this call.
/runtime/{deploymentId}/signal
This operation takes a signal and a event query parameter and sends a signal to the deployment [POST].
- The signal parameter value is used as the name of the signal. This parameter is required.
- The event parameter value is used as the value of the event. This value may use the number query parameter syntax described earlier.

Example 13.12. Signal Call Example

/runtime/{deploymentId}/signal?signal={signalCode}
This call is equivalent to the ksession.signal("signalName", eventValue) method.

13.3.2.3. Work item calls

The REST /runtime/{deploymentId}/workitem/ calls allow you to complete or abort a particular work item.
The following task calls are provided:
/runtime/{deploymentId}/workitem/{workItemID}/complete
completes the given work item [POST]
The call accepts query map parameters containing information about the results.

Example 13.13. A local invocation and its REST version

Map<String, Object> results = new HashMap<String, Object>();
results.put("one", "done");
results.put("two", 2);
kieSession.getWorkItemManager().completeWorkItem(23l, results);
curl -v -u admin 'localhost:8080/business-central/rest/runtime/myDeployment/workitem/23/complete?map_one=done&map_two=2i'
/runtime/{deploymentId}/workitem/{workItemID}/abort
aborts the given work item [POST]

13.3.2.4. History calls

The REST /history/ calls administer logs of process instances, their nodes, and process variables.

Note

While the REST /history/calls specified in 6.0.0.GA of BPMS are still available, as of 6.0.1.GA, the /history/ calls have been made independent of any deployment, which is also reflected in the URLS used.
The following history calls are provided:
/history/clear
clears all process, variable, and node logs [POST]
/history/instances
returns logs of all Process instances [GET]
/history/instance/{procInstanceID}
returns all logs of Process instance (including child logs) [GET]
/history/instance/{procInstanceID}/child
returns logs of child Process instances [GET]
/history/instance/{procInstanceID}/node
returns logs of all nodes of the Process instance [GET]
/history/instance/{procInstanceID}/node/{nodeID}
returns logs of the node of the Process instance [GET]
/history/instance/{procInstanceID}/variable
returns variables of the Process instance with their values [GET]
/history/instance/{procInstanceID}/variable/{variableID}
returns the log of the process instance that have the given variable id [GET]
/history/process/{procInstanceID}
returns the logs of the given Process instance excluding logs of its nodes and variables [GET]
History calls that search by variable
The following REST calls can be used using variables to search process instance, variables and their values.
The REST calls below also accept an optional activeProcesses parameter that limits the selection to information from active process instances.
/history/variable/{varId}
returns the variable logs of the specified process variable [GET]
/history/variable/{varId}/instances
returns the process instance logs for processes that contain the specified process variable [GET]
/history/variable/{varId}/value/{value}
returns the variable logs for specified process variable with the specified value [GET]

Example 13.14. A local invocation and its REST version

auditLogService.findVariableInstancesByNameAndValue("countVar", "three", true);
curl -v -u admin 'localhost:8080/business-central/rest/history/variable/countVar/value/three?activeProcesses=true'
/history/variable/{varId}/value/{value}/instances
returns the process instance logs for process instances that contain the specified process variable with the specified value [GET]

13.3.2.5. Calls to process variables

The REST /runtime/{deploymentId}/withvars/ calls allow you to work with Process variables. Note that all variable values are returned as strings in the JaxbVariablesResponse object.
The following withvars calls are provided:
/runtime/{deploymentId}/withvars/process/{procDefinitionID}/start
creates and starts Process instance and returns the Process instance with its variables Note that even if a passed variable is not defined in the underlying Process definition, it is created and initialized with the passed value. [POST]
/runtime/{deploymentId}/withvars/process/instance/{procInstanceID}
returns Process instance with its variables [GET]
/runtime/{deploymentId}/withvars/process/instance/{procInstanceID}/signal
sends signal event to Process instance (accepts query map parameters).

13.3.3. Task calls

The REST task calls are send to the Task Execution Engine.
The following task calls are provided:
/task/{taskId: \\d+}
returns the task in JAXB format [GET]
Further call paths are provided to perform other actions on tasks; refer to Section 13.3.3.1, “Task ID operations”)
/task/query
returns a TaskSummary list returned [GET]
Further call paths are provided to perform other actions on task/query; refer to Section 13.3.3.3, “Query operations”).
/task/content/{contentId: \\d+}
returns the task content in the JAXB format [GET]
For further information, refer to Section 13.3.3.2, “Content operations”)

13.3.3.1. Task ID operations

The task/{taskId: \\d+}/ACTION calls allow you to execute an action on the given task (if no action is defined, the call is a GET call that returns the JAXB representation of the task).
The following actions can be invoked on a task using the call:

Table 13.1. Task Actions

Task Action
activate activate task (taskId as query param.. )
claim claim task [POST] (The user used in the authentication of the REST url call claims it.)
claimnextavailable claim next available task [POST] (This operation claims the next available task assigned to the user.)
complete complete task [POST] (accepts "query map parameters".)
delegate delegate task [POST] (Requires a targetIdquery parameter, which identifies the user or group to which the task is delegated.)
exit exit task [POST]
fail fail task [POST]
forward forward task [POST]
release release task [POST]
resume resume task [POST]
skip skip task [POST]
start start task [POST]
stop stop task [POST]
suspend suspend task [POST]
nominate nominate task [POST] (Requires at least one of either the user or group query parameter, which identify the user(s) or group(s) that are nominated for the task.)

13.3.3.2. Content operations

The task/content/{contentId: \\d+} and task/{taskId: \\d+}/content operations return the serialized content associated with the given task.
The content associated with a task is stored in the human-task database schema in serialized form either as a string with XML content or a map with several different key-value pairs. The content is serialized using the protobuf based algorithm. This serialization process is normally carried out by the static methods in the org.jbpm.services.task.utils.ContentMarshallerHelper class.
If the client that call the REST operation do not have access to the org.jbpm.services.task.utils.ContentMarshallerHelper class, they cannot deserialize the task content. When using the REST call to obtain task content, the content is first deserialized usint the ContentMarshallerHelper class and then serialized with the common Java serialization mechanism.
Due to restrictions of REST operations, only the objects for which the following is true can be returned to the task content operations:
  • The requested objects are instances of a class that implements the Serializable interface. In the case of Map objects, they only contain values that implement the Serializable interface.
  • The objects are not instances of a local class, an anonymous class or arrays of a local or anonymous class.
  • The object classes are present on the class path of the server .

13.3.3.3. Query operations

The /task/query call is a GET call that returns a TaskSummary list of the tasks that meet the criteria defined in the call parameters. Note that you can use the pagination feature to define the amount of data to be return.
Parameters
The following parameters can be used with the task/query call:
  • workItemId: returns only tasks based on the work item.
  • taskId: returns only the task with the particular ID.
  • businessAdministrator: returns task with an identified business administrator.
  • potentialOwner: returns tasks that can be claimed by the potentialOwner user.
  • status: returns tasks that are in the given status (Created, Ready, Reserved, InProgress, Completed or Failed);
  • taskOwner: returns tasks assigned to the particular user (Created, Ready, Reserved, InProgress, Suspended, Completed, Failed, Error, Exited, or Obsolete).
  • processInstanceId: returns tasks generated by the Process instance.
  • union: specifies whether the query should query the union or intersection of the parameters.
At the moment, although the name of a parameter is interpreted regardless of case, please make sure use the appropriate case for the values of the parameters.

Example 13.15. Query usage

This call retrieves the task summaries of all tasks that have a work item id of 3, 4, or 5. If you specify the same parameter multiple times, the query will select tasks that match any of that parameter.
  • http://server:port/rest/task/query?workItemId=3&workItemId=4&workItemId=5
The next call will retrieve any task summaries for which the task id is 27 and for which the work item id is 11. Specifying different parameters will result in a set of tasks that match both (all) parameters.
  • http://server:port/rest/task/query?workItemId=11&taskId=27
The next call will retrieve any task summaries for which the task id is 27 or the work item id is 11. While these are different parameters, the union parameter is being used here so that the union of the two queries (the work item id query and the task id query) is returned.
  • http://server:port/rest/task/query?workItemId=11&taskId=27&union=true
The next call will retrieve any task summaries for which the status is `Created` and the potential owner of the task is `Bob`. Note that the letter case for the status parameter value is case-insensitve.
  • http://server:port/rest/task/query?status=creAted&potentialOwner=Bob
The next call will return any task summaries for which the status is `Created` and the potential owner of the task is `bob`. Note that the potential owner parameter is case-sensitive. `bob` is not the same user id as `Bob`!
  • http://server:port/rest/task/query?status=created&potentialOwner=bob
The next call will return the intersection of the set of task summaries for which the process instance is 201, the potential owner is `bob` and for which the status is `Created` or `Ready`.
  • http://server:port/rest/task/query?status=created&status=ready&potentialOwner=bob&processInstanceId=201
That means that the task summaries that have the following characteristics would be included:
  • process instance id 201, potential owner `bob`, status `Ready`
  • process instance id 201, potential owner `bob`, status `Created`
And that following task summaries will not be included:
  • process instance id 183, potential owner `bob`, status `Created`
  • process instance id 201, potential owner `mary`, status `Ready`
  • process instance id 201, potential owner `bob`, status `Complete`
Usage
The parameters can be used by themselves or in certain combinations. If an unsupported parameter combination is used, the system returns an empty list.
You can use certain parameters multiple times with different values: the returned result will contain the union of the entities that met at least one of the defined parameter value. This applies to the workItemId, taskId, businessAdministrator, potentialOwner, taskOwner, and processInstanceId. If entering the status parameter multiple times, the intersection of tasks that have any of the status values and union of tasks that satisfy the other criteria.
Note that the language parameter is required and if not defined the en-UK value is used. The parameter can be defined only once.

13.3.4. Execute operations

Important

The execute operations were created in order to support the Java Remote Runtime API. As a result, these calls are also available to the user. However, all of the functionality that these operations expose can be more easily accessed either via other REST operations or via the Java Remote Runtime API.
The Java Remote Runtime API, described in a following section, provides a programmatic interface to the REST and JMS APIs and takes care of the underlying details of sending and receiving commands via REST or JMS.
Advanced users looking to send a batch of commands via the REST API can use the execute operation. This is the only way to have the REST API process multiple commands in one operation.
To execute multiple commands in a single REST call, it is convenient to use the execute call: the call takes the JaxbCommandsRequest object as its parameter. The JaxbCommandsRequest object contains a List of org.kie.api.COMMAND.Command objects (the commands are "stored" in the JaxbCommandsRequest object as Strings and send via the execute REST call). The JaxbCommandsRequest parameters are deploymentId, if applicable processInstanceId, and a Command object.
  public List<JaxbCommandResponse<?>> executeCommand(String deploymentId, List<Command<?>> commands) throws Exception {
         URL address = new URL(url + "/runtime/" + deploymentId + "/execute");
         ClientRequest restRequest = createRequest(address);
         
         JaxbCommandsRequest commandMessage = new JaxbCommandsRequest(deploymentId, commands);
         String body = JaxbSerializationProvider.convertJaxbObjectToString(commandMessage);
         restRequest.body(MediaType.APPLICATION_XML, body);

         ClientResponse<JaxbCommandsResponse> responseObj = restRequest.post(JaxbCommandsResponse.class);
         checkResponse(responseObj);
         JaxbCommandsResponse cmdsResp = responseObj.getEntity();
         return cmdsResp.getResponses();
     }
     	    private ClientRequest createRequest(URL address) {
         return getClientRequestFactory().createRequest(address.toExternalForm());
     }
     
     private ClientRequestFactory getClientRequestFactory() {
         DefaultHttpClient httpClient = new DefaultHttpClient();
         httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST,
                 AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(userId, password));
         ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient);
         return new ClientRequestFactory(clientExecutor, ResteasyProviderFactory.getInstance());
     }

Figure 13.1. Method implementing the execute REST call

The following is a list of commands that the execute operation will accept. See the constructor and set methods on the actual command classes for further information about which parameters these commands will accept.
The following is the list of accepted commands used to interact with the process engine:
AbortWorkItemCommand SignalEventCommand
CompleteWorkItemCommand StartCorrelatedProcessCommand
GetWorkItemCommand StartProcessCommand
AbortProcessInstanceCommand GetVariableCommand
GetProcessIdsCommand GetFactCountCommand
GetProcessInstanceByCorrelationKeyCommand GetGlobalCommand
GetProcessInstanceCommand GetIdCommand
GetProcessInstancesCommand FireAllRulesCommand
SetProcessInstanceVariablesCommand  
The following is the list of accepted commands that interact with task instances:
ActivateTaskCommand GetTaskAssignedAsPotentialOwnerCommand
AddTaskCommand GetTaskByWorkItemIdCommand
CancelDeadlineCommand GetTaskCommand
ClaimNextAvailableTaskCommand GetTasksByProcessInstanceIdCommand
ClaimTaskCommand GetTasksByStatusByProcessInstanceIdCommand
CompleteTaskCommand GetTasksOwnedCommand
CompositeCommand NominateTaskCommand
DelegateTaskCommand ProcessSubTaskCommand
ExecuteTaskRulesCommand ReleaseTaskCommand
ExitTaskCommand ResumeTaskCommand
FailTaskCommand SkipTaskCommand
ForwardTaskCommand StartTaskCommand
GetAttachmentCommand StopTaskCommand
GetContentCommand SuspendTaskCommand
GetTaskAssignedAsBusinessAdminCommand  
The following is the list of accepted commands for managing and retrieving historical (audit) information:
ClearHistoryLogsCommand FindSubProcessInstancesCommand
FindActiveProcessInstancesCommand FindSubProcessInstancesCommand
FindNodeInstancesCommand FindVariableInstancesByNameCommand
FindProcessInstanceCommand FindVariableInstancesCommand
FindProcessInstancesCommand