16.5. Running in KIE

16.5.1. KieRuntime

The KieRuntime provides methods that are applicable to both rules and processes, such as setting globals and registering channels. ("Exit point" is an obsolete synonym for "channel".)

16.5.2. Globals in KIE

Globals are named objects that are made visible to the rule engine, but in a way that is fundamentally different from the one for facts: changes in the object backing a global do not trigger reevaluation of rules. Still, globals are useful for providing static information, as an object offering services that are used in the RHS of a rule, or as a means to return objects from the rule engine. When you use a global on the LHS of a rule, make sure it is immutable, or, at least, don't expect changes to have any effect on the behavior of your rules.
A global must be declared in a rules file, and then it needs to be backed up with a Java object.
global java.util.List list
With the Knowledge Base now aware of the global identifier and its type, it is now possible to call ksession.setGlobal() with the global's name and an object, for any session, to associate the object with the global. Failure to declare the global type and identifier in DRL code will result in an exception being thrown from this call.
List list = new ArrayList();
ksession.setGlobal("list", list);
Make sure to set any global before it is used in the evaluation of a rule. Failure to do so results in a NullPointerException.

16.5.3. Event Packages

The event package provides means to be notified of rule engine events, including rules firing, objects being asserted, etc. This allows separation of logging and auditing activities from the main part of your application (and the rules).
The KieRuntimeEventManager interface is implemented by the KieRuntime which provides two interfaces, RuleRuntimeEventManager and ProcessEventManager. We will only cover the RuleRuntimeEventManager here.
The RuleRuntimeEventManager allows for listeners to be added and removed, so that events for the working memory and the agenda can be listened to.
The following code snippet shows how a simple agenda listener is declared and attached to a session. It will print matches after they have fired.

Example 16.15. Adding an AgendaEventListener

import org.kie.api.runtime.process.EventListener;
		
ksession.addEventListener( new DefaultAgendaEventListener() {
    public void afterMatchFired(AfterMatchFiredEvent event) {
        super.afterMatchFired( event );
        System.out.println( event );
    }
});
JBoss BRMS also provides DebugRuleRuntimeEventListener and DebugAgendaEventListener which implement each method with a debug print statement. To print all Working Memory events, you add a listener like this:

Example 16.16. Adding a DebugRuleRuntimeEventListener

ksession.addEventListener( new DebugRuleRuntimeEventListener() );
All emitted events implement the KieRuntimeEvent interface which can be used to retrieve the actual KnowlegeRuntime the event originated from.
The events currently supported are:
  • MatchCreatedEvent
  • MatchCancelledEvent
  • BeforeMatchFiredEvent
  • AfterMatchFiredEvent
  • AgendaGroupPushedEvent
  • AgendaGroupPoppedEvent
  • ObjectInsertEvent
  • ObjectDeletedEvent
  • ObjectUpdatedEvent
  • ProcessCompletedEvent
  • ProcessNodeLeftEvent
  • ProcessNodeTriggeredEvent
  • ProcessStartEvent

16.5.4. Logger Implementations

JBoss BPM Suite provides a listener for creating an audit log to the console or the a file on the file system. You can use these logs for debugging purposes as it contains all the events occurring at runtime. JBoss BPM Suite provides the following logger implementations:
  • Console logger: This logger writes out all the events to the console. The KieServices provides you a KieRuntimeLogger that you can add to your session. When you create a console logger, pass the knowledge session as an argument.
  • File logger: This logger writes out all the events to a file using an XML representation. You can use this log file in your IDE to generate a tree-based visualization of the events that occurs during execution. For the file logger, you need to provide name.
  • Threaded file logger: As a file logger writes the events to disk only when closing the logger or when the number of events in the logger reaches a predefined level, you can not ise it when debugging processes at runtime. A threaded file logger writes the events to a file after a specified time interval, making it possible to use the logger to visualize the progress in real-time, while debugging processes. For the threaded file logger, you need to provide the interval (in milliseconds) after which the events must be saved. You must always close the logger at the end of your application.
Here is an example of using FileLogger:

Example 16.17. FileLogger

  import org.kie.api.KieServices;

  import org.kie.api.logger.KieRuntimeLogger;

  ...

  KieRuntimeLogger logger = KieServices.Factory.get().getLoggers().newFileLogger(ksession, "test");

  // add invocations to the process engine here,

  // e.g. ksession.startProcess(processId);

  ...

  logger.close();
The KieRuntimeLogger uses the comprehensive event system in JBoss BRMS to create an audit log that can be used to log the execution of an application for later inspection, using tools such as the JBoss Developer Studio's' audit viewer.

16.5.5. CommandExecutor Interface

KIE has the concept of stateful or stateless sessions. Stateful sessions have already been covered, which use the standard KieRuntime, and can be worked with iteratively over time. Stateless is a one-off execution of a KieRuntime with a provided data set. It may return some results, with the session being disposed at the end, prohibiting further iterative interactions. You can think of stateless as treating an engine like a function call with optional return results.
The foundation for this is the CommandExecutor interface, which both the stateful and stateless interfaces extend. This returns an ExecutionResults:
The CommandExecutor allows for commands to be executed on those sessions, the only difference being that the StatelessKieSession executes fireAllRules() at the end before disposing the session. The commands can be created using the CommandExecutor .The Javadocs provide the full list of the allowed comands using the CommandExecutor.
setGlobal and getGlobal are two commands relevant to BRMS.
Set Global calls setGlobal underneath. The optional boolean indicates whether the command should return the global's value as part of the ExecutionResults. If true it uses the same name as the global name. A String can be used instead of the boolean, if an alternative name is desired.

Example 16.18. Set Global Command

import org.kie.api.runtime.StatelessKieSession;
import org.kie.api.runtime.ExecutionResults;
			
StatelessKieSession ksession = kbase.newStatelessKieSession();
ExecutionResults bresults =
    ksession.execute( CommandFactory.newSetGlobal( "stilton", new Cheese( "stilton" ), true);
Cheese stilton = bresults.getValue( "stilton" );
Allows an existing global to be returned. The second optional String argument allows for an alternative return name.

Example 16.19. Get Global Command

import org.kie.api.runtime.StatelessKieSession;
import org.kie.api.runtime.ExecutionResults;

StatelessKieSession ksession = kbase.newStatelessKieSession();
ExecutionResults bresults =
    ksession.execute( CommandFactory.getGlobal( "stilton" );
Cheese stilton = bresults.getValue( "stilton" );
All the above examples execute single commands. The BatchExecution represents a composite command, created from a list of commands. It will iterate over the list and execute each command in turn. This means you can insert some objects, start a process, call fireAllRules and execute a query, all in a single execute(...) call, which is quite powerful.
The StatelessKieSession will execute fireAllRules() automatically at the end. However the keen-eyed reader probably has already noticed the FireAllRules command and wondered how that works with a StatelessKieSession. The FireAllRules command is allowed, and using it will disable the automatic execution at the end; think of using it as a sort of manual override function.
Any command, in the batch, that has an out identifier set will add its results to the returned ExecutionResults instance.

Example 16.20. BatchExecution Command

import org.kie.api.runtime.StatelessKieSession;
import org.kie.api.runtime.ExecutionResults;
		
StatelessKieSession ksession = kbase.newStatelessKieSession();

List cmds = new ArrayList();
cmds.add( CommandFactory.newInsertObject( new Cheese( "stilton", 1), "stilton") );
cmds.add( CommandFactory.newStartProcess( "process cheeses" ) );
cmds.add( CommandFactory.newQuery( "cheeses" ) );
ExecutionResults bresults = ksession.execute( CommandFactory.newBatchExecution( cmds ) );
Cheese stilton = ( Cheese ) bresults.getValue( "stilton" );
QueryResults qresults = ( QueryResults ) bresults.getValue( "cheeses" );
In the above example multiple commands are executed, two of which populate the ExecutionResults. The query command defaults to use the same identifier as the query name, but it can also be mapped to a different identifier.

16.5.6. Available API

XML marshalling and unmarshalling of the Jboss BRMS Commands requires the use of special classes. This section describes these classes.
The following urls show sample script examples for jaxb, xstream and json marshalling using:

XStream

To use the XStream commands marshaller, you need to use the DroolsHelperProvider to obtain an XStream instance. It is required because it has the commands converters registered. Also ensure that the drools-compiler library is present on the classpath.
  • Marshalling
    BatchExecutionHelper.newXStreamMarshaller().toXML(command);
  • Unmarshalling
    BatchExecutionHelperProviderImpl.newXStreamMarshaller().fromXML(xml)
The fully-qualified class name of the BatchExecutionHelper class is org.kie.internal.runtime.helper.BatchExecutionHelper.

JSON

JSON API to marshalling/unmarshalling is similar to XStream API:
  • Marshalling
    BatchExecutionHelper.newJSonMarshaller().toXML(command);
  • Unmarshalling
    BatchExecutionHelper.newJSonMarshaller().fromXML(xml)

JAXB

There are two options for using JAXB. You can define your model in an XSD file or have a POJO model. In both cases you have to declare your model inside JAXBContext. In order to do this, you need to use Drools Helper classes. Once you have the JAXBContext, you need to create the Unmarshaller/Marshaller as needed.

Using an XSD file to define the model

With your model defined in a XSD file, you need to have a KBase that has your XSD model added as a resource.
To do this, add the XSD file as a XSD ResourceType into the KBase. Finally you can create the JAXBContext using the KBase (created with the KnowledgeBuilder).
Ensure that the drools-compiler and jaxb-xjc
libraries are present on the classpath.
import org.kie.api.conf.Option;
import org.kie.api.KieBase;
	
Options xjcOpts = new Options();
xjcOpts.setSchemaLanguage(Language.XMLSCHEMA);
JaxbConfiguration jaxbConfiguration = KnowledgeBuilderFactory.newJaxbConfiguration( xjcOpts, "xsd" );
kbuilder.add(ResourceFactory.newClassPathResource("person.xsd", getClass()), ResourceType.XSD, jaxbConfiguration);
KieBase kbase = kbuilder.newKnowledgeBase();

List<String> classesName = new ArrayList<String>();
classesName.add("org.drools.compiler.test.Person");
   
JAXBContext jaxbContext = KnowledgeBuilderHelper.newJAXBContext(classesName.toArray(new String[classesName.size()]), kbase);

Using a POJO model

In this case you need to use DroolsJaxbHelperProviderImpl to create the JAXBContext. This class has two parameters:
  1. classNames: A list with the canonical name of the classes that you want to use in the marshalling/unmarshalling process.
  2. properties: JAXB custom properties
List<String> classNames = new ArrayList<String>();
classNames.add("org.drools.compiler.test.Person");
JAXBContext jaxbContext = DroolsJaxbHelperProviderImpl.createDroolsJaxbContext(classNames, null);
Marshaller marshaller = jaxbContext.createMarshaller();
Ensure that the drools-compiler and jaxb-xjc
libraries are present on the classpath. The fully-qualified class name of the DroolsJaxbHelperProviderImpl class is org.drools.compiler.runtime.pipeline.impl.DroolsJaxbHelperProviderImpl.

16.5.7. Supported JBoss BRMS Commands

JBoss BRMS supports the following list of commands:
  • BatchExecutionCommand
  • InsertObjectCommand
  • RetractCommand
  • ModifyCommand
  • GetObjectCommand
  • InsertElementsCommand
  • FireAllRulesCommand
  • StartProcessCommand
  • SignalEventCommand
  • CompleteWorkItemCommand
  • AbortWorkItemCommand
  • QueryCommand
  • SetGlobalCommand
  • GetGlobalCommand
  • GetObjectsCommand

Note

The code snippets provided in the examples for these commands use a POJO org.drools.compiler.test.Person with the following fields:
  • name: String
  • age: Integer

16.5.7.1. BatchExecutionCommand

The BatchExecutionCommand command contains a list of commands that are sent to the Decision Server and executed. It has the following attributes:

Table 16.3. BatchExecutionCommand Attributes

Name Description Required
lookup Sets the knowledge session id on which the commands are going to be executed true
commands List of commands to be executed false
Creating BatchExecutionCommand

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
InsertObjectCommand insertObjectCommand = new InsertObjectCommand(new Person("john", 25));
FireAllRulesCommand fireAllRulesCommand = new FireAllRulesCommand();
command.getCommands().add(insertObjectCommand);
command.getCommands().add(fireAllRulesCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <insert>
    <org.drools.compiler.test.Person>
      <name>john</name>
      <age>25</age>
    </org.drools.compiler.test.Person>
  </insert>
  <fire-all-rules/>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":[{"insert":{"object":{"org.drools.compiler.test.Person":{"name":"john","age":25}}}},{"fire-all-rules":""}]}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <insert>
        <object xsi:type="person" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <age>25</age>
            <name>john</name>
        </object>
    </insert>
    <fire-all-rules max="-1"/>
</batch-execution>

16.5.7.2. InsertObjectCommand

The InsertObjectCommand command is used to insert an object in the knowledge session. It has the following attributes:

Table 16.4. InsertObjectCommand Attributes

Name Description Required
object The object to be inserted true
outIdentifier Id to identify the FactHandle created in the object insertion and added to the execution results false
returnObject Boolean to establish if the object must be returned in the execution results. Default value: true false
entryPoint Entrypoint for the insertion false
Creating InsertObjectCommand

List<Command> cmds = ArrayList<Command>();

Command insertObjectCommand = CommandFactory.newInsert(new Person("john", 25), "john", false, null);
cmds.add( insertObjectCommand );

BatchExecutionCommand command = CommandFactory.createBatchExecution(cmds, "ksession1" );

XML output

XStream:

<batch-execution lookup="ksession1">
  <insert out-identifier="john" entry-point="my stream" return-object="false">
    <org.drools.compiler.test.Person>
      <name>john</name>
      <age>25</age>
    </org.drools.compiler.test.Person>
  </insert>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"insert":{"entry-point":"my stream", "out-identifier":"john","return-object":false,"object":{"org.drools.compiler.test.Person":{"name":"john","age":25}}}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <insert out-identifier="john" entry-point="my stream" >
        <object xsi:type="person" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <age>25</age>
            <name>john</name>
        </object>
    </insert>
</batch-execution>

16.5.7.3. RetractCommand

The RetractCommand command is used to retract an object from the knowledge session. It has the following attributes:

Table 16.5. RetractCommand Attributes

Name Description Required
handle The FactHandle associated to the object to be retracted true
Creating RetractCommand

There are two ways to create RetractCommand. You can either create the Fact Handle from a string, with the same output result as shown below:

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
RetractCommand retractCommand = new RetractCommand();
retractCommand.setFactHandleFromString("123:234:345:456:567");
command.getCommands().add(retractCommand);
Or set the Fact Handle that you received when the object was inserted, as shown below:
BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
RetractCommand retractCommand = new RetractCommand(factHandle);
command.getCommands().add(retractCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <retract fact-handle="0:234:345:456:567"/>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"retract":{"fact-handle":"0:234:345:456:567"}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <retract fact-handle="0:234:345:456:567"/>
</batch-execution>

16.5.7.4. ModifyCommand

The ModifyCommand command allows you to modify a previously inserted object in the knowledge session. It has the following attributes:

Table 16.6. ModifyCommand Attributes

Name Description Required
handle The FactHandle associated to the object to be retracted true
setters List of setters object's modifications true
Creating ModifyCommand

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
ModifyCommand modifyCommand = new ModifyCommand();
modifyCommand.setFactHandleFromString("123:234:345:456:567");
List<Setter> setters = new ArrayList<Setter>();
setters.add(new SetterImpl("age", "30"));
modifyCommand.setSetters(setters);
command.getCommands().add(modifyCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <modify fact-handle="0:234:345:456:567">
    <set accessor="age" value="30"/>
  </modify>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"modify":{"fact-handle":"0:234:345:456:567","setters":{"accessor":"age","value":30}}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <modify fact-handle="0:234:345:456:567">
        <set value="30" accessor="age"/>
    </modify>
</batch-execution>

16.5.7.5. GetObjectCommand

The GetObjectCommand command is used to get an object from a knowledge session. It has the following attributes:

Table 16.7. BatchExecutionCommand Attributes

Name Description Required
factHandle The FactHandle associated to the object to be retracted true
outIdentifier Id to identify the FactHandle created in the object insertion and added to the execution results false
Creating GetObjectCommand

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
GetObjectCommand getObjectCommand = new GetObjectCommand();
getObjectCommand.setFactHandleFromString("123:234:345:456:567");
getObjectCommand.setOutIdentifier("john");
command.getCommands().add(getObjectCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <get-object fact-handle="0:234:345:456:567" out-identifier="john"/>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"get-object":{"fact-handle":"0:234:345:456:567","out-identifier":"john"}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <get-object out-identifier="john" fact-handle="0:234:345:456:567"/>
</batch-execution>

16.5.7.6. InsertElementsCommand

The InsertElementsCommand command is used to insert a list of objects. It has the following attributes:

Table 16.8. InsertElementsCommand Attributes

Name Description Required
objects The list of objects to be inserted on the knowledge session true
outIdentifier Id to identify the FactHandle created in the object insertion and added to the execution results false
returnObject Boolean to establish if the object must be returned in the execution results. Default value: true false
entryPoint Entrypoint for the insertion false
Creating InsertElementsCommand

List<Command> cmds = ArrayList<Command>();

List<Object> objects = new ArrayList<Object>();
objects.add(new Person("john", 25));
objects.add(new Person("sarah", 35));

Command insertElementsCommand = CommandFactory.newInsertElements( objects );
cmds.add( insertElementsCommand );

BatchExecutionCommand command = CommandFactory.createBatchExecution(cmds, "ksession1" );

XML output

XStream:

<batch-execution lookup="ksession1">
  <insert-elements>
    <org.drools.compiler.test.Person>
      <name>john</name>
      <age>25</age>
    </org.drools.compiler.test.Person>
    <org.drools.compiler.test.Person>
      <name>sarah</name>
      <age>35</age>
    </org.drools.compiler.test.Person>
  </insert-elements>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"insert-elements":{"objects":[{"containedObject":{"@class":"org.drools.compiler.test.Person","name":"john","age":25}},{"containedObject":{"@class":"Person","name":"sarah","age":35}}]}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <insert-elements return-objects="true">
        <list>
            <element xsi:type="person" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <age>25</age>
                <name>john</name>
            </element>
            <element xsi:type="person" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <age>35</age>
                <name>sarah</name>
            </element>
        <list>
    </insert-elements>
</batch-execution>

16.5.7.7. FireAllRulesCommand

The FireAllRulesCommand command is used to allow execution of the rules activations created. It has the following attributes:

Table 16.9. FireAllRulesCommand Attributes

Name Description Required
max The max number of rules activations to be executed. default is -1 and will not put any restriction on execution false
outIdentifier Add the number of rules activations fired on the execution results false
agendaFilter Allow the rules execution using an Agenda Filter false
Creating FireAllRulesCommand

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
FireAllRulesCommand fireAllRulesCommand = new FireAllRulesCommand();
fireAllRulesCommand.setMax(10);
fireAllRulesCommand.setOutIdentifier("firedActivations");
command.getCommands().add(fireAllRulesCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <fire-all-rules max="10" out-identifier="firedActivations"/>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"fire-all-rules":{"max":10,"out-identifier":"firedActivations"}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
   <fire-all-rules out-identifier="firedActivations" max="10"/>
</batch-execution>

16.5.7.8. StartProcessCommand

The StartProcessCommand command allows you to start a process using the ID. Additionally, you can pass parameters and initial data to be inserted. It has the following attributes:

Table 16.10. StartProcessCommand Attributes

Name Description Required
processId The ID of the process to be started true
parameters A Map <String>, <Object> to pass parameters in the process startup false
data A list of objects to be inserted in the knowledge session before the process startup false
Creating StartProcessCommand

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
StartProcessCommand startProcessCommand = new StartProcessCommand();
startProcessCommand.setProcessId("org.drools.task.processOne");
command.getCommands().add(startProcessCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <start-process processId="org.drools.task.processOne"/>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"start-process":{"process-id":"org.drools.task.processOne"}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <start-process processId="org.drools.task.processOne">
        <parameter/>
    </start-process>
</batch-execution>

16.5.7.9. SignalEventCommand

The SignalEventCommand command is used to send a signal event. It has the following attributes:

Table 16.11. SignalEventCommand Attributes

Name Description Required
event-type The type of the incoming event true
processInstanceId The ID of the process instance to be started false
event The name of the incoming event false
Creating SignalEventCommand

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
SignalEventCommand signalEventCommand = new SignalEventCommand();
signalEventCommand.setProcessInstanceId(1001);
signalEventCommand.setEventType("start");
signalEventCommand.setEvent(new Person("john", 25));
command.getCommands().add(signalEventCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <signal-event process-instance-id="1001" event-type="start">
    <org.drools.pipeline.camel.Person>
      <name>john</name>
      <age>25</age>
    </org.drools.pipeline.camel.Person>
  </signal-event>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"signal-event":{"process-instance-id":1001,"@event-type":"start","event-type":"start","object":{"org.drools.pipeline.camel.Person":{"name":"john","age":25}}}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <signal-event event-type="start" process-instance-id="1001">
        <event xsi:type="person" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <age>25</age>
            <name>john</name>
        </event>
    </signal-event>
</batch-execution>

16.5.7.10. CompleteWorkItemCommand

The CompleteWorkItemCommand command allows you to complete a WorkItem. It has the following attributes:

Table 16.12. CompleteWorkItemCommand Attributes

Name Description Required
workItemId The ID of the WorkItem to be completed true
results The result of the WorkItem false
Creating CompleteWorkItemCommand

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
CompleteWorkItemCommand completeWorkItemCommand = new CompleteWorkItemCommand();
completeWorkItemCommand.setWorkItemId(1001);
command.getCommands().add(completeWorkItemCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <complete-work-item id="1001"/>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"complete-work-item":{"id":1001}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <complete-work-item id="1001"/>
</batch-execution>

16.5.7.11. AbortWorkItemCommand

The AbortWorkItemCommand command allows you abort a WorkItem (same as session.getWorkItemManager().abortWorkItem(workItemId)) It has the following attributes:

Table 16.13. AbortWorkItemCommand Attributes

Name Description Required
workItemId The ID of the WorkItem to be completed true
Creating AbortWorkItemCommand

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
AbortWorkItemCommand abortWorkItemCommand = new AbortWorkItemCommand();
abortWorkItemCommand.setWorkItemId(1001);
command.getCommands().add(abortWorkItemCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <abort-work-item id="1001"/>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"abort-work-item":{"id":1001}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <abort-work-item id="1001"/>
</batch-execution>

16.5.7.12. QueryCommand

The QueryCommand command executes a query defined in knowledge base. It has the following attributes:

Table 16.14. QueryCommand Attributes

Name Description Required
name The query name true
outIdentifier The identifier of the query results. The query results are going to be added in the execution results with this identifier false
arguments A list of objects to be passed as a query parameter false
Creating QueryCommand

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
QueryCommand queryCommand = new QueryCommand();
queryCommand.setName("persons");
queryCommand.setOutIdentifier("persons");
command.getCommands().add(queryCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <query out-identifier="persons" name="persons"/>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"query":{"out-identifier":"persons","name":"persons"}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <query name="persons" out-identifier="persons"/>
</batch-execution>

16.5.7.13. SetGlobalCommand

The SetGlobalCommand command allows you to set an object to global state. It has the following attributes:

Table 16.15. SetGlobalCommand Attributes

Name Description Required
identifier The identifier of the global defined in the knowledge base true
object The object to be set into the global false
out A boolean to add, or not, the set global result into the execution results false
outIdentifier The identifier of the global execution result false
Creating SetGlobalCommand

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
SetGlobalCommand setGlobalCommand = new SetGlobalCommand();
setGlobalCommand.setIdentifier("helper");
setGlobalCommand.setObject(new Person("kyle", 30));
setGlobalCommand.setOut(true);
setGlobalCommand.setOutIdentifier("output");
command.getCommands().add(setGlobalCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <set-global identifier="helper" out-identifier="output">
    <org.drools.compiler.test.Person>
      <name>kyle</name>
      <age>30</age>
    </org.drools.compiler.test.Person>
  </set-global>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"set-global":{"identifier":"helper","out-identifier":"output","object":{"org.drools.compiler.test.Person":{"name":"kyle","age":30}}}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <set-global out="true" out-identifier="output" identifier="helper">
        <object xsi:type="person" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <age>30</age>
            <name>kyle</name>
        </object>
    </set-global>
</batch-execution>

16.5.7.14. GetGlobalCommand

The GetGlobalCommand command allows you to get a previously defined global object. It has the following attributes:

Table 16.16. GetGlobalCommand Attributes

Name Description Required
identifier The identifier of the global defined in the knowledge base true
outIdentifier The identifier to be used in the execution results false
Creating GetGlobalCommand

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
GetGlobalCommand getGlobalCommand = new GetGlobalCommand();
getGlobalCommand.setIdentifier("helper");
getGlobalCommand.setOutIdentifier("helperOutput");
command.getCommands().add(getGlobalCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <get-global identifier="helper" out-identifier="helperOutput"/>
</batch-execution>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"get-global":{"identifier":"helper","out-identifier":"helperOutput"}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <get-global out-identifier="helperOutput" identifier="helper"/>
</batch-execution>

16.5.7.15. GetObjectsCommand

The GetObjectsCommand command returns all the objects from the current session as a Collection. It has the following attributes:

Table 16.17. GetObjectsCommand Attributes

Name Description Required
objectFilter An ObjectFilter to filter the objects returned from the current session false
outIdentifier The identifier to be used in the execution results false
Creating GetObjectsCommand

BatchExecutionCommand command = new BatchExecutionCommand();
command.setLookup("ksession1");
GetObjectsCommand getObjectsCommand = new GetObjectsCommand();
getObjectsCommand.setOutIdentifier("objects");
command.getCommands().add(getObjectsCommand);

XML output

XStream:

<batch-execution lookup="ksession1">
  <get-objects out-identifier="objects"/>
</batch-execution>
JSON:
{"lookup":"ksession1","commands":{"get-objects":{"out-identifier":"objects"}}}
JAXB:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batch-execution lookup="ksession1">
    <get-objects out-identifier="objects"/>
</batch-execution>