JBoss.orgCommunity Documentation
The workbench contains an execution server (for executing processes and tasks), which also allows you to invoke various process and task related operations through a remote API. As a result, you can setup your process engine "as a service" and integrate this into your applications easily by doing remote requests and/or sending the necessary triggers to the execution server whenever necessary (without the need to embed or manage this as part of your application).
Both a REST and JMS based service are available (which you can use directly), and a Java remote client allows you to invoke these operations using the existing KieSession and TaskService interfaces (you also use for local interaction), making remote integration as easy as if you were interacting with a local process engine.
The Remote Java API provides KieSession
, TaskService
and
AuditService
interfaces to the JMS and REST APIs.
The interface implementations provided by the Remote Java API take care of the underlying
logic needed to communicate with the JMS or REST APIs. In other words, these implementations
will allow you to interact with a remote workbench instance (i.e. KIE workbench or the jBPM
Console) via known interfaces such as the KieSession
or TaskService
interface,
without having to deal with the underlying transport and serialization details.
While the KieSession
, TaskSerivce
and
AuditService
instances provided by the Remote Java API may "look" and "feel"
like local instances of the same interfaces, please make sure to remember that these instances
are only wrappers around a REST or jMS client that interacts with a remote REST or JMS
API.
This means that if a requested operation fails on the server, the
Remote Java API client instance on the client side will throw a
RuntimeException
indicating that the REST call failed. This is different from
the behaviour of a "real" (or local) instance of a KieSession
,
TaskSerivce
and AuditService
instance because the exception the
local instances will throw will relate to how the operation failed. Also, while local
instances require different handling (such as having to dispose of a KieSession
),
client instances provided by the Remote Java API hold no state and thus do not require any
special handling.
Lastly, operations on a Remote Java API client instance that would normally throw other
exceptions (such as the TaskService.claim(taskId, userId)
operation when called
by a user who is not a potential owner), will now throw a RuntimeException
instead when the requested operation fails on the server.
The first step in interacting with the remote runtime is to create either the
RemoteRestRuntimeFactory
or RemoteJmsRuntimeEngineFactory
, both of
which are instances of the RemoteRuntimeEngineFactory
interface.
The configuration for the Remote Java API is done when creating the
RemoteRuntimeEngineFactory
instance: there are a number of different constructors
for both the JMS and REST impelementations that allow the configuration of such things as the
base URL of the REST API, JMS queue location or timeout while waiting for responses.
Once the factory instances have been created, there are a couple of methods that can then be used to instantiate the client instance that you want to use:
Remote Java API Methods
This method instantiates a new RemoteRuntimeEngine (client) instance.
This method adds extra classes to the classpath available to the serialization mechanisms.
When passing instances of user-defined classes in a Remote Java API call, it's important to have added the classes via this method first so that the class instances can be serialized correctly.
This method instantiates a new (client) KieSession instance.
This method instantiates a new (client) TaskService instance.
This method instantiates a new (client) AuditService instance.
The RemoteRestRuntimeFactory
should indeed have been called the
RemoteRestRuntimeEngineFactory
! Sometimes it's the
easiest mistakes which are the hardest to catch. This will be corrected in future
releases.
The RemoteRestRuntimeFactory
has 4 constructor methods available. Besides
an "everything" constructor method which provides all of the options provided below, there are
also the following 3 constructors:
RemoteRestRuntimeFactory constructor method parameters
Table 17.1. Simple RemoteRestRuntimeFactory constructor parameters
Name | Type | Description |
---|---|---|
|
|
This is the name (id) of the deployment the |
|
|
This is the URL of the deployed jbpm-console, kie-wb or BPMS instance. For example: |
|
|
This is the user name needed to access the JMS queues. |
|
|
This is the password needed to access the JMS queues. |
Table 17.2. RemoteRestRuntimeFactory constructor parameters with (response message) timeout parameter
Name | Type | Description |
---|---|---|
|
|
This is the name (id) of the deployment the |
|
|
This is the URL of the deployed jbpm-console, kie-wb or BPMS instance. For example: |
|
|
This is the user name needed to access the REST API. |
|
|
This is the password needed to access the REST API. |
|
|
This maximum number of seconds to wait when waiting for a response from the server. |
Table 17.3. RemoteRestRuntimeFactory constructor parameters with form-based authorization parameter
Name | Type | Description |
---|---|---|
|
|
This is the name (id) of the deployment the |
|
|
This is the URL of the deployed jbpm-console, kie-wb or BPMS instance. For example: |
|
|
This is the user name needed to access the REST API. |
|
|
This is the password needed to access the REST API. |
|
|
Whether or not to use form-based authentication when making a REST call. Form-based authentication will be necessary on tomcat instances. |
The following example illustrates how the Remote Java API can be used with the REST API.
public void startProcessAndHandleTaskViaRestRemoteJavaAPI(URL instanceUrl, String deploymentId, String user, String password) {
// the serverRestUrl should contain a URL similar to "http://localhost:8080/jbpm-console/"
// Setup the factory class with the necessarry information to communicate with the REST services
RemoteRuntimeEngineFactory restSessionFactory
= new RemoteRestRuntimeFactory(deploymentId, instanceUrl, user, password);
// Create KieSession and TaskService instances and use them
RemoteRuntimeEngine engine = restSessionFactory.newRuntimeEngine();
KieSession ksession = engine.getKieSession();
TaskService taskService = engine.getTaskService();
// Each opertion on a KieSession, TaskService or AuditService (client) instance
// sends a request for the operation to the server side and waits for the response
// If something goes wrong on the server side, the client will throw an exception.
ProcessInstance processInstance
= ksession.startProcess("com.burns.reactor.maintenance.cycle");
long procId = processInstance.getId();
String taskUserId = user;
taskService = engine.getTaskService();
List<TaskSummary> tasks = taskService.getTasksAssignedAsPotentialOwner(user, "en-UK");
long taskId = -1;
for (TaskSummary task : tasks) {
if (task.getProcessInstanceId() == procId) {
taskId = task.getId();
}
}
if (taskId == -1) {
throw new IllegalStateException("Unable to find task for " + user + " in process instance " + procId);
}
taskService.start(taskId, taskUserId);
}
The Remote JMS Java RuntimeEngine works precisely the same as the REST variant, except that it has different constructors.
The RemoteJmsRuntimeEngineFactory
constructors can be grouped into 3 types.
The list below specifies the main arguments to each group type.
The URL of the execution server instance is given
The JMS remote access objects (such as the ConnectionFactory
and
Queue
) are given.
A remote InitialContext
instance (created using JNDI) from the server
is given.
Configuration using the server URL
. Configuration using only the URL of the server where the jBPM Console or KIE Workbench
instance is running, is the most straightforward. However, this is only possible when the
jBPM console or KIE Workbench instance is running on Wildfly or JBoss AS, or JBoss EAP.
The following table describes the parameters used when using an
InitialContext
to configure a RemoteJmsRuntimeEngineFactory
instance:
Table 17.4. RemoteJmsRuntimeFactory constructor arguments
Name | Type | Description |
---|---|---|
|
|
This is the name (id) of the deployment the |
|
|
This is the URL of the (JBoss) server instance.. |
|
|
This is the user name needed to access the JMS queues and JNDI InitialContext instance. |
|
|
This is the password needed to access the JMS queues and JNDI InitialContext instance. |
Configuration using an InitialContext
instance. When configuring the RemoteJmsRuntimeEngineFactory
with an
InitialContext
instance as a parameter, it's necessary to retrieve the
(remote) InitialContext
instance first from the remote server. The following
code illustrates how to do this.
The code below illustrates how this can be done with a JBoss AS 7 or EAP 6 server instance. Similar code is used in the constructor above.
However, regardless of which application server you use, it is necessary to
include in your classpath the class specified as the INITIAL_CONTEXT_FACTORY
(see below). For JBoss AS 7 and EAP 6, the artifact (jar) containing this class is the
org.jboss:jboss-remote-naming
artifact (jar), version
1.0.5.Final
or higher. Depending on the version of AS 7 or EAP 6 that you
use, this version may vary.
If you are using a different application server, please see your specific
application server documentation for the parameters and artifacts necessary to create an
InitialContextFactory
instance or otherwise get a remote
InitialContext
instance (via JNDI) from the application server instance.
public void startProcessAndTaskViaJmsRemoteJavaAPI(String serverHostName, String deploymentId, String user, String password) {
// Setup remote JMS runtime engine factory
InitialContext remoteInitialContext
= getRemoteInitialContext(serverHostName, user, password);
int maxTimeoutSecs = 5;
RemoteJmsRuntimeEngineFactory remoteJmsFactory
= new RemoteJmsRuntimeEngineFactory(deploymentId, remoteInitialContext, user, password, maxTimeoutSecs);
// Interface with JMS api
RuntimeEngine engine = remoteJmsFactory.newRuntimeEngine();
KieSession ksession = engine.getKieSession();
ProcessInstance processInstance = ksession.startProcess("com.burns.reactor.maintenance.cycle");
long procId = processInstance.getId();
TaskService taskService = engine.getTaskService();
List<Long> tasks = taskService.getTasksByProcessInstanceId(procId);
taskService.start(tasks.get(0), user);
}
private static InitialContext getRemoteInitialContext(String jbossServerHostName, String user, String password) {
// Configure the (JBoss AS 7/EAP 6) InitialContextFactory
Properties initialProps = new Properties();
initialProps.setProperty(InitialContext.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
initialProps.setProperty(InitialContext.PROVIDER_URL, "remote://"+ jbossServerHostName + ":4447");
initialProps.setProperty(InitialContext.SECURITY_PRINCIPAL, user);
initialProps.setProperty(InitialContext.SECURITY_CREDENTIALS, password);
for (Object keyObj : initialProps.keySet()) {
String key = (String) keyObj;
System.setProperty(key, (String) initialProps.get(key));
}
// Create the remote InitialContext instance
try {
return new InitialContext(initialProps);
} catch (NamingException e) {
throw new RuntimeException("Unable to create " + InitialContext.class.getSimpleName(), e);
}
}
The following table describes the parameters used when using an
InitialContext
to configure a RemoteJmsRuntimeEngineFactory
instance:
Table 17.5. RemoteJmsRuntimeFactory constructor arguments
Name | Type | Description |
---|---|---|
|
|
This is the name (id) of the deployment the |
|
|
This is a remote |
|
|
This is the user name needed to access the JMS queues. |
|
|
This is the password needed to access the JMS queues. |
|
|
This maximum number of seconds to wait when waiting for a response from the server. |
Configuration using ConnectionFactory
and Queue
instance parameters. Some users may have direct access to a ConnectionFactory
and the
Queue
instances needed to interact with the JMS API. In this case, they can
use the RemoteJmsRuntimeEngineFactory
constructor that uses the following
arguments:
Table 17.6. RemoteJmsRuntimeEngineFactory constructor arguments
Name | Type | Description |
---|---|---|
|
|
This is the name (id) of the deployment the |
|
|
This is a |
|
|
This is an instance of the |
|
|
This is an instance of the |
|
|
This is an instance of the |
|
|
This is the user name needed to access the JMS queues (in your application server configuration). |
|
|
This is the password needed to access the JMS queues (in your application server configuration). |
|
|
This maximum number of seconds to wait when waiting for a response from the server. |
As mentioned above, the Remote Java API provides client-like instances of the RuntimeEngine
, KieSession
,
TaskService
and AuditService
interfaces.
This means that while many of the methods in those interfaces are available, some are not. The following tables lists the methods
which are available. Methods not listed in the below, will throw an UnsupportedOperationException
explaining that the
called method is not available.
Table 17.7. Available process-related KieSession
methods
Returns | Method signature | Description |
---|---|---|
|
| Abort the process instance |
|
| Return the process instance |
|
| Return the process instance |
|
| Return all (active) process instances |
|
| Signal all (active) process instances |
|
| Signal the process instance |
|
| Start a new process and return the process instance (if the process instance has not immediately completed) |
|
| Start a new process and return the process instance (if the process instance has not immediately completed) |
Table 17.8. Available rules-related KieSession
methods
Returns | Method signature | Description |
---|---|---|
|
| Return the total fact count |
|
| Return a global fact |
|
| Return the id of the |
|
| Set a global fact |
|
| Fire all rules |
Table 17.9. Available WorkItemManager
methods
Returns | Method signature | Description |
---|---|---|
|
| Abort the work item |
|
| Complete the work item |
|
| Return the work item |
Table 17.10. Available task operation TaskService
methods
Returns | Method signature | Description |
---|---|---|
|
| Add a new task |
|
| Activate a task |
|
| Claim a task |
|
| Claim a task |
|
| Claim the next available task for a user |
|
| Claim the next available task for a user |
|
| Complete a task |
|
| Delegate a task |
|
| Exit a task |
|
| Fail a task |
|
| Forward a task |
|
| Nominate a task |
|
| Release a task |
|
| Remove a task |
|
| Resume a task |
|
| Skip a task |
|
| Start a task |
|
| Stop a task |
|
| Suspend a task |
Table 17.11. Available task retrieval and query TaskService
methods
Returns | Method signature |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Table 17.12. Available AuditService
methods
Returns | Method signature |
---|---|
|
|
|
|
|
|
ProcessInstanceLog |
|
List<ProcessInstanceLog> |
|
List<NodeInstanceLog> |
|
List<NodeInstanceLog> |
|
List<VariableInstanceLog> |
|
List<VariableInstanceLog> |
|
List<VariableInstanceLog> |
|
List<VariableInstanceLog> |
|
void |
|
REST API calls to the execution server allow you to remotely manage processes and tasks and retrieve various dynamic
information from the execution server. The majority of the calls are synchronous, which means that the call will only
finish once the requested operation has completed on the server. The exceptions to this are the deployment
POST
calls, which will return the status of the request while the actual operation requested will
asynchronously execute.
When using Java code to interface with the REST API, the classes used in POST operations or otherwise returned by
various operations can be found in the (org.kie.remote:)kie-services-client
JAR.
This section lists REST calls that interface with
The deploymentId component of the REST calls below must conform to the following regular expression:
[\w\.-]+(:[\w\.-]+){2,2}(:[\w\.-]*){0,2}
For information, see the Deployment calls section.
Starts a process.
Returns a JaxbProcessInstanceResponse
instance, that contains basic information about the process instance.
The prodessDefIdcomponent of the URL must conform to the following regex: [_a-zA-Z0-9-:\.]+
This operation takes map query parameters (see above), which will be used as parameters for the process instance.
Checks that exists the process idetified by prodessDefId on the given deployment and generates an URL to show the start form on a remote application.
Returns a JaxbProcessInstanceFormResponse
instance, that contains the URL to the start process form.
The prodessDefIdcomponent of the URL must conform to the following regex: [_a-zA-Z0-9-:\.]+
Does a (read only) retrieval of the process instance. This operation will fail (code 400) if the process instance has been completed.
Returns a JaxbProcessInstanceResponse
instance.
The procInstId component of the URL must conform to the following regex: [0-9]+
Aborts the process instance.
Returns a JaxbGenericResponse
indicating whether or not the operation has succeeded.
The procInstId component of the URL must conform to the following regex: [0-9]+
Signals the process instance.
Returns a JaxbGenericResponse
indicating whether or not the operation has succeeded.
The procInstId component of the URL must conform to the following regex: [0-9]+
This operation takes a signal
and a event
query parameter.
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 above.
Gets the list of process variables in a process instance.
Returns a JaxbVariablesResponse
The procInstId component of the URL must conform to the following regex: [0-9]+
Signals the KieSession
Returns a JaxbGenericResponse
indicating whether or not the operation has succeeded.
The procInstId component of the URL must conform to the following regex: [0-9]+
This operation takes a signal
and a event
query parameter.
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 above.
Gets a WorkItem
instance
Returns a JaxbWorkItem
instance
The workItemId component of the URL must conform to the following regex:
[0-9]+
Completes a WorkItem
Returns a JaxbGenericResponse
indicating whether or not the operation has succeeded
The workItemId component of the URL must conform to the following regex:
[0-9]+
This operation takes map query parameters, which are used as input to signify the results for completion of the work item.
Aborts a WorkItem
Returns a JaxbGenericResponse
indicating whether or not the operation has succeeded
The workItemId component of the URL must conform to the following regex:
[0-9]+
Starts a process and retrieves the list of variables associated with the process instance
Returns a JaxbProcessInstanceWithVariablesResponse
that contains:
Information about the process instance (with the same fields and behaviour as the
JaxbProcessInstanceResponse
A key-value list of the variables available in the process instance.
The processDefId component of the URL must conform to the following regex:
[_a-zA-Z0-9-:\.]+
Starts a process and retrieves the list of variables associated with the process instance
Returns a JaxbProcessInstanceWithVariablesResponse
(see the above REST call)
The processInstId component of the URL must conform to the following regex:
[0-9]+
Signals a process instance and retrieves the list of variables associated it
Returns a JaxbProcessInstanceWithVariablesResponse
(see above)
The processInstId component of the URL must conform to the following regex:
[0-9]+
This operation takes a signal
and a event
query parameter.
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 above.
Between the 6.0.0.Final and 6.0.1.Final releases, the History REST calls were udpated and fixed in order to make them both more robust and accessible. While the REST calls that were provided with 6.0.0.Final are still available in 6.0.1.Final, they will be removed in a future release.
Cleans (deletes) all history logs
Gets a list of ProcessInstanceLog
instances
Returns a JaxbHistoryLogList
instance that contains a list of JaxbProcessInstanceLog
instances
This operation responds to pagination parameters
Gets the ProcessInstanceLog
instance associated with the specified process instance
Returns a JaxbHistoryLogList
instance that contains a JaxbProcessInstanceLog
instance
The processInstId component of the URL must conform to the following regex:
[0-9]+
This operation responds to pagination parameters
Gets a list of ProcessInstanceLog
instances associated with any child/sub-processes
associated with the specified process instance
Returns a JaxbHistoryLogList
instance that contains a list of JaxbProcessInstanceLog
instances
The processInstId component of the URL must conform to the following regex:
[0-9]+
This operation responds to pagination parameters
Gets a list of NodeInstanceLog
instances associated with the specified process instance
Returns a JaxbHistoryLogList
instance that contains a list of JaxbNodeInstanceLog
instances
The processInstId component of the URL must conform to the following regex:
[0-9]+
This operation responds to pagination parameters
Gets a list of VariableInstanceLog
instances associated with the specified process instance
Returns a JaxbHistoryLogList
instance that contains a list of JaxbVariableInstanceLog
instances
The processInstId component of the URL must conform to the following regex:
[0-9]+
This operation responds to pagination parameters
Gets a list of NodeInstanceLog
instances associated with the specified process instance
that have the given (node) id
Returns a JaxbHistoryLogList
instance that contains a list of JaxbNodeInstanceLog
instances
The processInstId component of the URL must conform to the following regex:
[0-9]+
The nodeId component of the URL must conform to the following regex:
[a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Gets a list of VariableInstanceLog
instances associated with the specified process instance
that have the given (variable) id
Returns a JaxbHistoryLogList
instance that contains a list of
JaxbVariableInstanceLog
instances
The processInstId component of the URL must conform to the following regex:
[0-9]+
The varId component of the URL must conform to the following regex:
[a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Gets a list of ProcessInstanceLog
instances associated with the specified process definition
Returns a JaxbHistoryLogList
instance that contains a list of JaxbProcessInstanceLog
instances
The processDefId component of the URL must conform to the following regex:
[_a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Gets a list of VariableInstanceLog
instances associated with the specified variable id
Returns a JaxbHistoryLogList
instance that contains a list of JaxbVariableInstanceLog
instances
The varId component of the URL must conform to the following regex:
[a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Gets a list of VariableInstanceLog
instances associated with the specified variable id
that contain the value specified
Returns a JaxbHistoryLogList
instance that contains a list of
JaxbVariableInstanceLog
instances
Both the varId and value components of the URL must conform
to the following regex:
[a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Gets a list of ProcessInstance
instances that contain the variable specified by the
given variable id.
Returns a JaxbProcessInstanceListResponse
instance that contains a list of
JaxbProcessInstanceResponse
instances
The varId component of the URL must conform to the following regex:
[a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Gets a list of ProcessInstance
instances that contain the variable specified by
the given variable id which contains the (variable) value specified
Returns a JaxbProcessInstanceListResponse
instance that contains a list of
JaxbProcessInstanceResponse
instances
Both the varId and value components of the URL must conform
to the following regex: [a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Rest calls that contain
"rest/runtime/{deploymentId}/history
" have been
deprecated: the same functionality provided by these calls can be found in the history REST
calls described in the previous sections.
If you're using the 6.0.0.Final release, the following applies to the History REST calls:
The history calls in 6.0.0.Final are dependent on a deployment being available to call them. This is because
the History REST calls in 6.0.0.Final needed the persistence framework of a deployment in order to be executed.
This means that history REST calls listed below may sometimes fail when used with a deployment unit
that uses a PER_REQUEST
or PER_PROCESS_INSTANCE
strategy
(i.e. when the deployment is no longer available).
Cleans (deletes) all history logs
Gets a list of ProcessInstanceLog
instances
Returns a JaxbHistoryLogList
instance that contains a list of JaxbProcessInstanceLog
instances
This operation responds to pagination parameters
Gets the ProcessInstanceLog
instance associated with the specified process instance
Returns a JaxbHistoryLogList
instance that contains a JaxbProcessInstanceLog
instance
The processInstId component of the URL must conform to the following regex: [0-9]+
This operation responds to pagination parameters
Gets a list of ProcessInstanceLog
instances associated with any child/sub-processes associated with the specified process instance
Returns a JaxbHistoryLogList
instance that contains a list of JaxbProcessInstanceLog
instances
The processInstId component of the URL must conform to the following regex: [0-9]+
This operation responds to pagination parameters
Gets a list of NodeInstanceLog
instances associated with the specified process instance
Returns a JaxbHistoryLogList
instance that contains a list of JaxbNodeInstanceLog
instances
The processInstId component of the URL must conform to the following regex: [0-9]+
This operation responds to pagination parameters
Gets a list of VariableInstanceLog
instances associated with the specified process instance
Returns a JaxbHistoryLogList
instance that contains a list of JaxbVariableInstanceLog
instances
The processInstId component of the URL must conform to the following regex: [0-9]+
This operation responds to pagination parameters
Gets a list of NodeInstanceLog
instances associated with the specified process instance that have the given (node) id
Returns a JaxbHistoryLogList
instance that contains a list of JaxbNodeInstanceLog
instances
The processInstId component of the URL must conform to the following regex:[0-9]+
The nodeId component of the URL must conform to the following regex: [a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Gets a list of VariableInstanceLog
instances associated with the specified process instance that have the given (variable) id
Returns a JaxbHistoryLogList
instance that contains a list of JaxbVariableInstanceLog
instances
The processInstId component of the URL must conform to the following regex: [0-9]+
The varId component of the URL must conform to the following regex: [a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Gets a list of ProcessInstanceLog
instances associated with the specified process definition
Returns a JaxbHistoryLogList
instance that contains a list of JaxbProcessInstanceLog
instances
The processDefId component of the URL must conform to the following regex: [_a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Gets a list of VariableInstanceLog
instances associated with the specified variable id
Returns a JaxbHistoryLogList
instance that contains a list of JaxbVariableInstanceLog
instances
The varId component of the URL must conform to the following regex: [a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Gets a list of VariableInstanceLog
instances associated with the specified variable id that contain the value specified
Returns a JaxbHistoryLogList
instance that contains a list of JaxbVariableInstanceLog
instances
Both the varId and value components of the URL must conform to the following regex: [a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Gets a list of ProcessInstance
instances that contain the variable specified by the given variable id.
Returns a JaxbProcessInstanceListResponse
instance that contains a list of JaxbProcessInstanceResponse
instances
The varId component of the URL must conform to the following regex: [a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
Gets a list of ProcessInstance
instances that contain the variable specified by the given variable id which contains the (variable) value specified
Returns a JaxbProcessInstanceListResponse
instance that contains a list of JaxbProcessInstanceResponse
instances
Both the varId and value components of the URL must conform to the following regex: [a-zA-Z0-9-:\.]+
This operation responds to pagination parameters
The following section describes the three different types of task calls:
Task REST operations that mirror the TaskService
interface, allowing the user to interact
with the remote TaskService
instance
The Task query REST operation, that allows users to query for Task
instances
Other Task REST operations that retrieve information
Task operation authorizations. Task REST operations use the user information (used to authorize and authenticate the HTTP call) to check whether or not the requested operations can happen. This also applies to REST calls that retrieve information, such as the task query operation. REST calls that request information will only return information about tasks that the user is allowed to see.
With regards to retrieving information, only users associated with a task may retrieve information about the task. However, the authorizations of progress and other modifications of task information are more complex. See the Task Permissions section in the Task Service documentation for more infomration.
Given that many users have expressed the wish for a "super-task-user" that can execute task REST operations on all tasks, regardless of the users associated with the task, there are now plans to implement that feature. However, for the 6.0.x releases, this feature is not available.
All of the task operation calls described in this section use the user (id) used in the REST basic authorization as input for the user parameter in the specific call.
Some of the operations take an optional lanaguage
query parameter. If this parameter is not given
as a element of the URL itself, the default value of "en-UK
" is used.
The taskId component of the REST calls below must conform to the following regex:
[0-9]+
Activates a task
Returns a JaxbGenericResponse
with the status of the operation
Claims a task
Returns a JaxbGenericResponse
with the status of the operation
Claims the next available task
Returns a JaxbGenericResponse
with the status of the operation
Takes an optional language
query parameter.
Completes a task
Returns a JaxbGenericResponse
with the status of the operation
Takes map query parameters, which are the "results" input for the complete operation
Delegates a task
Returns a JaxbGenericResponse
with the status of the operation
Requires a targetId
query parameter, which identifies the user or group
to which the task is delegated
Exits a task
Returns a JaxbGenericResponse
with the status of the operation
Fails a task
Returns a JaxbGenericResponse
with the status of the operation
Delegates a task
Returns a JaxbGenericResponse
with the status of the operation
Requires a targetId
query parameter, which identifies the user or group
to which the task is forwarded
Nominates a task
Returns a JaxbGenericResponse
with the status of the operation
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
Releases a task
Returns a JaxbGenericResponse
with the status of the operation
Resumes a task
Returns a JaxbGenericResponse
with the status of the operation
Skips a task
Returns a JaxbGenericResponse
with the status of the operation
Starts a task
Returns a JaxbGenericResponse
with the status of the operation
Stops a task
Returns a JaxbGenericResponse
with the status of the operation
Suspends a task
Returns a JaxbGenericResponse
with the status of the operation
Checks that the task idetified by taskId exists and generates an URL to show the task form on a remote application.
Returns a JaxbTaskFormResponse
instance, that contains the URL to the task form.
The /task/query
operation queries all non-archived tasks based on the parameters given.
Queries the available non-archived tasks
Returns a JaxbTaskSummaryListResponse
with a list of TaskSummaryImpl
instances.
Takes the following (case-insensitive) query parameters listed below:
businessAdministrator
Specifies that the returned tasks should have the business administrator identified by this parameter
This parameter may be repeated
potentialOwner
Specifies that the returned tasks should have the potential owner identified by this parameter
This parameter may be repeated
processInstanceId
Specifies that the returned tasks should be associated with the process instance identified by this parameter
This parameter may be repeated
status
Specifies that the returned tasks should have the status identified by this parameter
This parameter may be repeated
taskId
Specifies that the returned tasks should have the (task) id identified by this parameter
This parameter may be repeated
taskOwner
Specifies that the returned tasks should have the task owner (initiator) identified by this parameter
This parameter may be repeated
workItemId
Specifies that the returned tasks should be associated with the work item identified by this parameter
This parameter may be repeated
language
Specifies the language that the returned tasks should be associated with
This parameter may be repeated
union
This specifies whether the query should query the union or intersection of the parameters. See below for more info.
This parameter must only be passed once
Example 17.1. 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`
Gets the task content from a task identified by the given task id
Returns a JaxbContent
with the content of the task
The taskId component of the URL must conform to the following regex:
[0-9]+
Gets the task content from a task identified by the given content id
Returns a JaxbContent
with the content of the task
The contentId component of the URL must conform to the following regex:
[0-9]+
The calls described in this section allow users to manage deployments. Deployments are in fact
KieModule
JARs which can be deployed or undeployed, either via the UI or via the REST calls described
below. Configuration options, such as the runtime strategy, should be specified when deploying the deployment:
the configuration of a deployment can not be changed after it has already been deployed.
The above deploymentId regular expression describes an expression that contains the following elements, separated from eachother by a :
character:
The group id
The artifact id
The version
The (optional) kbase id
The (optional) ksession id
In a more formal sense, the deploymentId component of the REST calls below must conform to the following regex:
[\w\.-]+(:[\w\.-]+){2,2}(:[\w\.-]*){0,2}
This regular expression is explained as follows:
The [\w\.-]
element, which occurs 3 times in the above regex, refers to a character set that
can contain the following character sets:
[A-Z] | [0-9] | . | ||
[a-z] | _ | - |
This [\w\.-]
element occurs at least 3 times and at most 5 times, separated by a ':
' character
each time.
Example 17.2. Accepted deploymentId
's
com.wonka:choco-maker:67.190
These example deploymentId
's contain the optional kbase and
ksession id groups.
com.wonka:choco-maker:67.190:oompaBase
com.wonka:choco-maker:67.190:oompaLoompaBase:gloopSession
There are 2 operations that can be used to modify the status of a deployment:
/deployments/{deploymentId}/deploy
/deployments/{deploymentId}/undeploy
These POST
deployment calls are both asynchronous, which
means that the information returned by the POST
request does not reflect the
eventual final status of the operation itself.
As noted above, both the /deploy
and /undeploy
operations are
asynchronous REST operations. Successfull requests to these URLs will return the
status 202
upon the request completion. RFC 2616 defines the 202
status
as meaning that
“the request has been accepted for processing, but the processing has not been completed.”
This means the following:
While the request may have been accepted "successfully", the operation itself (deploying or undeploying the deployment unit) may actually fail.
Furthermore, information about deployments, such as that retrieved by calling the
GET
operations described below, are snapshots and the information
(including the status of the deployment unit) may have changed by the time the user client receives
the answer to the GET
request.
Returns a list of all the available deployed instances in a
JaxbDeploymentUnitList
instance
Returns a JaxbDeploymentUnit
instance containing th e information
(including the configuration) of the deployment unit.
This operation will fail when the URL uses a deployementId that refers to a deployment unit that does not exist or for which the deployment has not yet been completed.
This operation may succeed for deployment units for which an undeploy operation request has not yet completed.
Deploys the deployment unit referenced by the deploymentId
Returns a JaxbDeploymentJobResult
instance with the status of the
request
Takes a strategy
query parameter:
This parameter describes the runtime strategy used for the deployment.
This parameter takes the following (case- in sensitive) values:
SINGLETON
PER_REQUEST
PER_PROCESS_INSTANCE
The default runtime strategy used for a deployment is
SINGLETON
.
The deploy operation is an asynchronous operation. The
status of the deployment can be retrieved using the GET
calls described
above.
The request can fail for the reasons described
It is possible to post a deployment descriptor (or a fragment of it) while submitting deploy request. That allows to override other deployment descriptors in the hierarchy. To do so the content type of the request must be set to application/xml and the request body should be a a valid deployment descriptor content.
For example to change the audit logging mode from default JPA to JMS submit following partial deployment descriptor:
<deployment-descriptor xsi:schemaLocation="http://www.jboss.org/jbpm deployment-descriptor.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<audit-mode>JMS</audit-mode>
</deployment-descriptor>
Since deployment descriptors can be merged differently, there is a possibility to provide the merge mode as part of deploy request by adding query parameter:
mergemode where values should be one of the following - KEEP_ALL, OVERRIDE_ALL, OVERRIDE_EMPTY, MERGE_COLLECTIONS
Undeploys the deployment unit referenced by the deploymentId
Returns a JaxbDeploymentJobResult
instance with the status of the
request
The undeploy operation is an asynchronous operation. The
status of the deployment can be retrieved using the GET
calls described
above.
While there is a /runtime/{id}/execute
and a task/execute
method, both will take all types
of commands. This is possible because execute takes a JaxbCommandsRequest object, which contains a list of
(org.kie.api.command.)Command
objects. The JaxbCommandsRequest
has fields to store the proper
deploymentId
and processInstanceId
information.
Of course, if you send a request with a command that needs this information (deploymentId
, for example)
and don't fill the deploymentId
in, the request will fail.
Executes a
Command
, assumed to be related to tasks.
Returns a
JaxbCommandResponse
implementation with the result of the operation
Executes a
Command
, assumed to be related to business processes or the knowledge session.
Returns a
JaxbCommandResponse
implementation with the result of the operation
Runtime commands.
AbortWorkItemCommand | GetProcessInstancesCommand | GetGlobalCommand |
CompleteWorkItemCommand | SetProcessInstanceVariablesCommand | GetIdCommand |
GetWorkItemCommand | SignalEventCommand | SetGlobalCommand |
AbortProcessInstanceCommand | StartCorrelatedProcessCommand | DeleteCommand |
GetProcessIdsCommand | StartProcessCommand | FireAllRulesCommand |
GetProcessInstanceByCorrelationKeyCommand | GetVariableCommand | InsertObjectCommand |
GetProcessInstanceCommand | GetFactCountCommand | UpdateCommand |
Task commands.
ActivateTaskCommand | FailTaskCommand | GetTasksOwnedCommand |
AddTaskCommand | ForwardTaskCommand | NominateTaskCommand |
CancelDeadlineCommand | GetAttachmentCommand | ProcessSubTaskCommand |
ClaimNextAvailableTaskCommand | GetContentCommand | ReleaseTaskCommand |
ClaimTaskCommand | GetTaskAssignedAsBusinessAdminCommand | ResumeTaskCommand |
CompleteTaskCommand | GetTaskAssignedAsPotentialOwnerCommand | SkipTaskCommand |
CompositeCommand | GetTaskByWorkItemIdCommand | StartTaskCommand |
DelegateTaskCommand | GetTaskCommand | StopTaskCommand |
ExecuteTaskRulesCommand | GetTasksByProcessInstanceIdCommand | SuspendTaskCommand |
ExitTaskCommand | GetTasksByStatusByProcessInstanceIdCommand |
Task commands.
ClearHistoryLogsCommand | FindProcessInstanceCommand | FindSubProcessInstancesCommand |
FindActiveProcessInstancesCommand | FindProcessInstancesCommand | FindVariableInstancesByNameCommand |
FindNodeInstancesCommand | FindSubProcessInstancesCommand | FindVariableInstancesCommand |
Except for the Execute calls, all other REST calls described below can use either JAXB or JSON.
All REST calls, unless otherwise specified, will use JAXB serialization.
When using JSON, make sure to add the JSON media type ("application/json"
) to the
ACCEPT
header of your REST call.
Sometimes, users may wish to pass instances of their own classes as parameters to commands sent in a REST request or JMS message. In order to do this, there are a number of requirements.
The user-defined class satisfy the following in order to be property serialized and deserialized by the JMS API:
The user-defined class must be correctly annotated with JAXB annotations, including the following:
The user-defined class must be annotated with a
javax.xml.bind.annotation.XmlRootElement
annotation with a
non-empty name
value
All fields or getter/setter methods must be annotated with a
javax.xml.bind.annotation.XmlElement
or
javax.xml.bind.annotation.XmlAttribute
annotations.
Furthermore, the following usage of JAXB annotations is recommended:
Annotate the user-defined class with a
javax.xml.bind.annotation.XmlAccessorType
annotation
specifying that fields should be used,
(javax.xml.bind.annotation.XmlAccessType.FIELD
). This also
means that you should annotate the fields (instead of the getter or setter
methods) with @XmlElement
or @XmlAttribute
annotations.
Fields annotated with @XmlElement
or
@XmlAttribute
annotations should also be annotated with
javax.xml.bind.annotation.XmlSchemaType
annotations
specifying the type of the field, even if the fields contain primitive
values.
Use objects to store primitive values. For example, use the
java.lang.Integer
class for storing an integer value, and
not the int
class. This way it will always be obvious if the
field is storing a value.
The user-defined class definition must implement a no-arg constructor.
Any fields in the user-defined class must either be object primitives (such
as a Long
or String
) or otherwise be objects that
satisfy the first 2 requiremends in this list (correct usage of JAXB annotations
and a no-arg constructor).
The class definition must be included in the deployment jar of the deployment that the JMS message content is meant for.
The sender must set a “deploymentId” string property on the JMS bytes message to the name of the deploymentId. This property is necessary in order to be able to load the proper classes from the deployment itself before deserializing the message on the server side.
While submitting an instance of a user-defined class is possible via both the JMS and REST API's, retrieving an instance of the process variable is only possible via the REST API.
When interacting with the Remote API, users may want to pass instances of their own classes as parameters to certain operations. As mThis will only be possible if the KJar for a deployment includes these classes.
REST calls that involve the TaskService
(e.g. that start with /task
..), often do not
contain any information about the associated deployment. In that case, an extra query parameter will have to be
added to the REST call so that the server can find the appropriate deployment with the class (definition) and
correctly deserialize the information passed with the call.
For these REST calls which do not contain the deployment id, you'll need to add the following parameter:
Table 17.13. Deployment id query parameter
Parameter name | Description |
---|---|
deploymentId
|
Value (must match the regex |
Some of the REST calls below return lists of information. The results of these operations can be paginated , which means that the lists can be split up and returned according to the parameters sent by the user.
For example, if the REST call parameters indicate that page 2 with page size 10 should be returned for the results, then results 10 to (and including) 19 will be returned.
The first page is always page 1 (as opposed to page "0").
Table 17.14. Pagination query parameter syntax
Parameter name | Description |
---|---|
page
|
The page number requested. The default value is 1. |
p
|
Synonym for the above
|
pageSize
|
The number of elements per page to return. The default value is 10. |
s
|
Synonym for the above
|
If both a "long" pagination parameter and its synonym are used, then only the value from the "long" variant is used. For
example, if
the
page
is given with a value of 11 and the
p
parameter is given with a value of 37, then the value of the
page
parameter,
11
, will be used and the
p
parameter will be ignored.
For the following operations, pagination is always used. See above for the default values used.
Table 17.15. REST operations using pagination
REST call URL | Short Description |
---|---|
|
Returns a list of
|
|
Returns a list of
|
|
Returns a list of
|
|
Returns a list of
|
|
Returns a list of
|
|
Returns a list of
|
|
Returns a list of
|
|
Returns a list of
|
|
Returns a list of
|
|
Returns a list of
|
|
Returns a list of
|
|
Returns a list of
|
|
Returns a list of
|
If you're triggering an operation with a REST API call that would normally (e.g. when interacting the same operation on a
local
KieSession
or
TaskService
instance) take an instance of a
java.util.Map
as one of its parameters,
you can submit key-value pairs to the operation to simulate this behaviour by passing a query parameter whose name starts with
map_
.
Example 17.3.
If you pass the query parameter
map_kEy=vAlue
in a REST call, then the
Map
that's passed to the
actual underlying
KieSession
or
TaskService
operation will contain this (
String, String
) key value pair:
"kEy" => "vAlue"
.You could pass this parameter like so:
http://localhost:8080/kie-wb/rest/runtime/myproject/process/wonka.factory.loompa.hire/start?map_kEy=vAlue
Map query parameters also use the object query parameter syntax described below, so the following query parameter,
map_total=5000
will be translated into a key-value pair in a map where the key is the String "total" and the value is a Long with the
value of 5000. For example:
http://localhost:8080/kie-wb/rest/runtime/myproject/process/wonka.factory.oompa.chocolate/start?map_total=5000
The following operations take query map parameters:
/runtime/{deploymentId}/process/{processDefId}/start
/runtime/{deploymentId}/workitem/{processItemId}/complete
/runtime/{deploymentId}/withvars/process/{processDefId}/start
/task/{taskId}/complete
/task/{taskId}/fail
While REST calls obviously only take strings as query parameters, using the following notation for query parameters will mean that the string is translated into a different type of object when the value of the string is used in the actual operation:
The REST calls allow access to the underlying deployments, regardless of whether these deployments use the
Singleton
,
Per-Process-Instance
or
Per-Request
strategies.
While there's enough information in the URL in order to access deployments that use the
Singleton
, or
Per-Request
strategies, that's not always the case with the
Per-Process-Instance
runtimes because the REST operation will obviously
need the process instance id in order to identify the deployment.
Therefore, for REST calls for which the URL does not contain the process instance id, you'll need to add the following parameter:
Table 17.17. Per-Process-Instance runtime query parameter
Parameter name | Description |
---|---|
runtimeProcInstId
|
Value (must match the regex
Will have no effect if the underlying deployment uses the
|
The URL templates in the table below are relative the following URL:
http://server:port/business-central/rest
Table 17.18. runtime REST calls
URL Template | Type | Description |
---|---|---|
/runtime/{deploymentId}/process/{procDefID}/start | POST | start a process instance based on the Process definition (accepts query map parameters) |
/runtime/{deploymentId}/process/{procDefID}/startform | POST | returns a valid URL to the start process form to be shown on a client aplication. |
/runtime/{deploymentId}/process/instance/{procInstanceID} | GET | return a process instance details |
/runtime/{deploymentId}/process/instance/{procInstanceID}/abort | POST | abort the process instance |
/runtime/{deploymentId}/process/instance/{procInstanceID}/signal | POST | send a signal event to process instance (accepts query map parameters) |
/runtime/{deploymentId}/process/instance/{procInstanceID}/variable/{varId} | GET | return a variable from a process instance |
/runtime/{deploymentId}/signal/{signalCode} | POST | send a signal event to deployment |
/runtime/{deploymentId}/workitem/{workItemID}/complete | POST | complete a work item (accepts query map parameters) |
/runtime/{deploymentId}/workitem/{workItemID}/abort | POST | abort a work item |
/runtime/{deploymentId}/withvars/process/{procDefinitionID}/start | POST |
start a process instance and return 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. |
/runtime/{deploymentId}/withvars/process/instance/{procInstanceID}/ | GET |
return a process instance with its variables |
/runtime/{deploymentId}/withvars/process/instance/{procInstanceID}/signal | POST |
send a signal event to the process instance (accepts query map parameters) The following query parameters are accepted:
|
Table 17.19. task REST calls
URL Template | Type | Description |
---|---|---|
/task/query | GET |
return a TaskSummary list |
/task/content/{contentID} | GET |
returns the content of a task |
/task/{taskID} | GET |
return the task |
/task/{taskID}/activate | POST |
activate the task |
/task/{taskID}/claim | POST |
claim the task |
/task/{taskID}/claimnextavailable | POST |
claim the next available task |
/task/{taskID}/complete | POST |
complete the task (accepts query map paramaters) |
/task/{taskID}/delegate | POST |
delegate the task |
/task/{taskID}/exit | POST |
exit the task |
/task/{taskID}/fail | POST |
fail the task |
/task/{taskID}/forward | POST |
forward the task |
/task/{taskID}/nominate | POST |
nominate the task |
/task/{taskID}/release | POST |
release the task |
/task/{taskID}/resume | POST |
resume the task (after suspending) |
/task/{taskID}/skip | POST |
skip the task |
/task/{taskID}/start | POST |
start the task |
/task/{taskID}/stop | POST |
stop the task |
/task/{taskID}/suspend | POST |
suspend the task |
/task/{taskID}/content | GET |
returns the content of a task |
/task/{taskID}/showTaskForm | GET |
returns a valid URL to the task form to be shown on a client aplication. |
Table 17.20. history REST calls
URL Template | Type | Description |
---|---|---|
/history/clear/ | POST | delete all process, node and history records |
/history/instances | GET | return the list of all process instance history records |
/history/instance/{procInstId} | GET | return a list of process instance history records for a process instance |
/history/instance/{procInstId}/child | GET | return a list of process instance history records for the subprocesses of the process instance |
/history/instance/{procInstId}/node | GET | return a list of node history records for a process instance |
/history/instance/{procInstId}/node/{nodeId} | GET | return a list of node history records for a node in a process instance |
/history/instance/{procInstId}/variable | GET | return a list of variable history records for a process instance |
/history/instance/{procInstId}/variable/{variableId} | GET | return a list of variable history records for a variable in a process instance |
/history/process/{procDefId} | GET | return a list of process instance history records for process instances using a given process definition |
/history/variable/{varId} | GET | return a list of variable history records for a variable |
/history/variable/{varId}/instances | GET | return a list of process instance history records for process instances that contain a variable with the given variable id |
/history/variable/{varId}/value/{value} | GET | return a list of variable history records for variable(s) with the given variable id and given value |
/history/variable/{varId}/value/{value}/instances | GET | return a list of process instance history records for process instances with the specified variable that contains the specified variable value |
Table 17.21. deployment REST calls
URL Template | Type | Description |
---|---|---|
/deployments | GET | return a list of (deployed) deployments |
/deployment/{deploymentId} | GET | return the status and information about the deployment |
/deployment/{deploymentId}/deploy | POST |
submit a request to deploy a deployment |
/deployment/{deploymentId}/undeploy | POST |
submit a request to undeploy a deployment |
The Java Message Service (JMS) is an API that allows Java Enterprise components to communicate with each other asynchronously and reliably.
Operations on the runtime engine and tasks can be done via the JMS API exposed by the jBPM console and KIE workbench. However, it's not possible to manage deployments or the knowledge base via this JMS API.
Unlike the REST API, it is possible to send a batch of commands to the JMS API that will all be processed in one request after which the responses to the commands will be collected and return in one response message.
When the Workbench is deployed on the JBoss AS or EAP server, it automatically creates 3 queues:
jms/queue/KIE.SESSION
jms/queue/KIE.TASK
jms/queue/KIE.RESPONSE
The KIE.SESSION
and KIE.TASK
queues should be used
to send request messages to the JMS API. Command response messages will be then placed on the
KIE.RESPONSE
queues. Command request messages that involve starting and
managing business processes should be sent to the KIE.SESSION
and command request
messages that involve managing human tasks, should be sent to the KIE.TASK
queue.
Although there are 2 different input queues, KIE.SESSION
and KIE.TASK
, this is only in order to provide multiple
input queues so as to optimize processing: command request messages will be processed in the same manner regardless of which queue they're sent to.
However, in some cases, users may send many more requests involving human tasks than requests involving business processes, but then not want the
processing of business process-related request messages to be delayed by the human task messages. By sending the appropriate command request
messages to the appropriate queues, this problem can be avoided.
The term "command request message" used above refers to a JMS byte message that contains a serialized
JaxbCommandsRequest
object. At the moment, only XML serialization (as opposed to, JSON or protobuf, for example) is supported.
While it is possible to interact with a BPMS or KIE workbench server instance by sending and processing JMS messages that you create yourself,
it will always be easier to use the remote Java API that's supplied by the kie-services-client
jar.
For more information about how to use the remote Java API to interact with the JMS API of a server instance, see the Remote Java API section.
The JMS API accepts ByteMessage
instances that contain serialized
JaxbCommandsRequest
objects. These JaxbCommandsRequest
instances
can be filled with multiple command objects. In this way, it's possible to send a batch of
commands for processing to the JMS API.
When users wish to include their own classes with requests, there a number of requirements that must be met for the user-defined classes. For more information about these requirements, see the Sending and receiving user class instances section in the REST API documentation.
The following is a rather long example that shows how to use the JMS API. The numbers ("callouts") along the side of the example refer to notes below that explain particular parts of the example. It's supplied for those advanced users that do not wish to use the jBPM Remote Java API.
The jBPM Remote Java API, described here, will otherwise take care of all of the logic shown below.
// normal java imports skipped import org.drools.core.command.runtime.process.StartProcessCommand; import org.jbpm.services.task.commands.GetTaskAssignedAsPotentialOwnerCommand; import org.kie.api.command.Command; import org.kie.api.runtime.process.ProcessInstance; import org.kie.api.task.model.TaskSummary; import org.kie.services.client.api.command.exception.Remote
CommunicationException; import org.kie.services.client.serialization.JaxbSerializationProvider; import org.kie.services.client.serialization.SerializationConstants; import org.kie.services.client.serialization.SerializationException; import org.kie.services.client.serialization.jaxb.impl.JaxbCommandResponse; import org.kie.services.client.serialization.jaxb.impl.JaxbCommandsRequest; import org.kie.services.client.serialization.jaxb.impl.JaxbCommandsResponse; import org.kie.services.client.serialization.jaxb.rest.JaxbExceptionResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DocumentationJmsExamples { protected static final Logger logger = LoggerFactory.getLogger(DocumentationJmsExamples.class); public void sendAndReceiveJmsMessage() { String USER = "charlie"; String PASSWORD = "ch0c0licious"; String DEPLOYMENT_ID = "test-project"; String PROCESS_ID_1 = "oompa-processing"; URL serverUrl; try { serverUrl = new URL("http://localhost:8080/jbpm-console/"); } catch (MalformedURLException murle) { logger.error("Malformed URL for the server instance!", murle); return; } // Create JaxbCommandsRequest instance and add commands Command<?> cmd = new StartProcessCommand(PROCESS_ID_1); int oompaProcessingResultIndex = 0;
JaxbCommandsRequest req = new JaxbCommandsRequest(DEPLO
YMENT_ID, cmd); req.getCommands().add(new GetTaskAssignedAsPotentialOwnerCommand(USER, "en-UK")); int loompaMonitoringResultIndex = 1;
// Get JNDI context from server InitialContext context = getRemoteJbossInitialContext(serverUrl, USER, PASSWORD); // Create JMS connection ConnectionFactory connectionFactory; try { connectionFactory = (ConnectionFactory) context.lookup("jms/RemoteConnectionFactory"); } catch (NamingException ne) { throw new RuntimeException("Unable to lookup JMS connection factory.", ne); } // Setup queues Queue sendQueue, responseQueue; try { sendQueue = (Queue) context.lookup("jms/queue/KIE.SESSION"); responseQueue = (Queue) context.lookup("jms/queue/KIE.RESPONSE"); } catch (NamingException ne) { throw new RuntimeException("Unable to lookup send or response queue", ne); } // Send command request Long processInstanceId = null; // needed if you're doing an operation on a PER_PROCESS_INSTANCE deployment String humanTaskUser = USER; JaxbCommandsResponse cmdResponse = sendJmsCommands( DEPLOYMENT_ID, processInstanceId, humanTaskUser, req, connectionFactory, sendQueue, responseQueue, USER, PASSWORD, 5); // Retrieve results ProcessInstance oompaProcInst = null; List<TaskSummary> charliesTasks = null; for (JaxbCommandResponse<?> response : cmdResponse.getR
esponses()) { if (response instanceof JaxbExceptionResponse) { // something went wrong on the server side JaxbExceptionResponse exceptionResponse = (JaxbExceptionResponse) response; throw new RuntimeException(exceptionResponse.getMessage()); } if (response.getIndex() == oompaProcessingResultIndex
) { oompaProcInst = (ProcessInstance) response.getResul
t(); } else if (response.getIndex() == loompaMonitoringRes
ultIndex) { charliesTasks = (List<TaskSummary>) response.getRes
ult(); } } } private JaxbCommandsResponse sendJmsCommands(String deploymentId, Long processInstanceId, String user, JaxbCommandsRequest req, ConnectionFactory factory, Queue sendQueue, Queue responseQueue, String jmsUser, String jmsPassword, int timeout) { req.setProcessInstanceId(processInstanceId); req.setUser(user); Connection connection = null; Session session = null; String corrId = UUID.randomUUID().toString(); String selector = "JMSCorrelationID = '" + corrId + "'"; JaxbCommandsResponse cmdResponses = null; try { // setup MessageProducer producer; MessageConsumer consumer; try { if (jmsPassword != null) { connection = factory.createConnection(jmsUser, jmsPassword); } else { connection = factory.createConnection(); } session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); producer = session.createProducer(sendQueue); consumer = session.createConsumer(responseQueue, selector); connection.start(); } catch (JMSException jmse) { throw new RemoteCommunicationException("Unable to setup a JMS connection.", jmse); } JaxbSerializationProvider serializationProvider = new JaxbSerializationProvider(); // if necessary, add user-created classes here: // xmlSerializer.addJaxbClasses(MyType.class, AnotherJaxbAnnotatedType.class); // Create msg BytesMessage msg; try { msg = session.createBytesMessage();
// set properties msg.setJMSCorrelationID(corrId);
msg.setIntProperty(SerializationConstants.SERIALIZA
TION_TYPE_PROPERTY_NAME, JaxbSerializationProvider.JMS_SERIALIZATION_TYPE); Collection<Class<?>> extraJaxbClasses = serializationProvider.getExtraJaxbClasses(); if (!extraJaxbClasses.isEmpty()) { String extraJaxbClassesPropertyValue = JaxbSerializationProvider .classSetToCommaSeperatedString(extraJaxbClasses); msg.setStringProperty(SerializationConstants.EXTRA_JAXB_CLASSES_PROPERTY_NAME, extraJaxbClassesPropertyValue); msg.setStringProperty(SerializationConstants.DEPLOYMENT_ID_PROPERTY_NAME, deploymentId); } // serialize request String xmlStr = serializationProvider.serialize(req
); msg.writeUTF(xmlStr); } catch (JMSException jmse) { throw new RemoteCommunicationException("Unable to create and fill a JMS message.", jmse); } catch (SerializationException se) { throw new RemoteCommunicationException("Unable to deserialze JMS message.", se.getCause()); } // send try { producer.send(msg); } catch (JMSException jmse) { throw new RemoteCommunicationException("Unable to send a JMS message.", jmse); } // receive Message response; try { response = consumer.receive(timeout); } catch (JMSException jmse) { throw new RemoteCommunicationException("Unable to receive or retrieve the JMS response.", jmse); } if (response == null) { logger.warn("Response is empty, leaving"); return null; } // extract response assert response != null : "Response is empty."; try { String xmlStr = ((BytesMessage) response).readUTF(); cmdResponses = (JaxbCommandsResponse) serialization
Provider.deserialize(xmlStr); } catch (JMSException jmse) { throw new RemoteCommunicationException("Unable to extract " + JaxbCommandsResponse.class.getSimpleName() + " instance from JMS response.", jmse); } catch (SerializationException se) { throw new RemoteCommunicationException("Unable to extract " + JaxbCommandsResponse.class.getSimpleName() + " instance from JMS response.", se.getCause()); } assert cmdResponses != null : "Jaxb Cmd Response was null!"; } finally { if (connection != null) { try { connection.close(); session.close(); } catch (JMSException jmse) { logger.warn("Unable to close connection or session!", jmse); } } } return cmdResponses; } private InitialContext getRemoteJbossInitialContext(URL url, String user, String password) { Properties initialProps = new Properties(); initialProps.setProperty(InitialContext.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory"); String jbossServerHostName = url.getHost(); initialProps.setProperty(InitialContext.PROVIDER_URL, "remote://"+ jbossServerHostName + ":4447"); initialProps.setProperty(InitialContext.SECURITY_PRINCIPAL, user); initialProps.setProperty(InitialContext.SECURITY_CREDENTIALS, password); for (Object keyObj : initialProps.keySet()) { String key = (String) keyObj; System.setProperty(key, (String) initialProps.get(key)); } try { return new InitialContext(initialProps); } catch (NamingException e) { throw new RemoteCommunicationException("Unable to create " + InitialContext.class.getSimpleName(), e); } } }
These classes can all be found in the | |
The A deployment id is required for command request messages that deal with business processes. Command request messages that only contain human task-related commands do not require a deployment id. | |
Note that the JMS message sent to the remote JMS API must be constructed as follows:
| |
The same serialization mechanism used to serialize the request message will be used to serialize the response message. | |
In order to match the response to a command, to the initial command, use the | |
Since many of the results returned by various commands are not serializable, the jBPM JMS Remote API converts these results
into JAXB equivalents, all of which implement the For example, in the code above, the However, not all methods that can be called on a normal |