10.8. Realtime Decision Server Java Client API Overview

In Chapter 4 from the Red Hat BRMS Getting Started Guide, you used the Realtime Decision Server Java Client API (that is a Maven structure) to send requests using REST API. This section further explains:

10.8.1. Maven Dependencies

To import Maven dependencies, you can use the Bill of Materials (BOM). Alternatively, you can follow the Hello World example.

Example 10.25. Maven Dependency using BOM

<dependencyManagement>
  <dependencies>
   <dependency>
     <groupId>org.jboss.bom.brms</groupId>
     <artifactId>jboss-brms-bpmsuite-bom</artifactId>
     <version>${version.org.jboss.bom.brms}</version>
     <type>pom</type>
     <scope>import</scope>
   </dependency>
 </dependencies>
</dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.kie.server</groupId>
            <artifactId>kie-server-client</artifactId>
        </dependency>
    </dependencies>
Use 6.2.1.GA-redhat-2 in version.org.jboss.bom.brms for Red Hat JBoss BRMS 6.2.0. Follow Maven BOM page to see all the available versions.

Example 10.26. Hello World Maven Dependency

<dependency>
    <groupId>org.kie.server</groupId>
    <artifactId>kie-server-client</artifactId>
    <version>6.3.0.Final-redhat-7</version>
</dependency>

10.8.2. Client Configuration

You need to declare a configuration object and set server communication aspects, such as the protocol (REST or JMS), credentials and the payload format (XStream, JAXB or JSON). For additional example, follow the Hello World project.

Example 10.27. Client Configuration

import org.kie.server.api.marshalling.MarshallingFormat;
import org.kie.server.client.KieServicesClient;
import org.kie.server.client.KieServicesConfiguration;
import org.kie.server.client.KieServicesFactory;

public class DecisionServerTest {

    private static final String URL = "http://localhost:8080/kie-server/services/rest/server";
    private static final String USER = "kieserver";
    private static final String PASSWORD = "kieserver1!";

    private static final MarshallingFormat FORMAT = MarshallingFormat.JSON;

    private KieServicesConfiguration conf;
    private KieServicesClient kieServicesClient;

    @Before
    public void initialize() {
        conf = KieServicesFactory.newRestConfiguration(URL, USER, PASSWORD);
        conf.setMarshallingFormat(FORMAT);
        kieServicesClient = KieServicesFactory.newKieServicesClient(conf);
    }
}

Example 10.28. JMS Client Configuration

    import java.util.Properties;

    import javax.jms.ConnectionFactory;
    import javax.jms.Queue;
    import javax.naming.Context;
    import javax.naming.InitialContext;

    import org.junit.Test;
    import org.kie.server.client.KieServicesClient;
    import org.kie.server.client.KieServicesConfiguration;
    import org.kie.server.client.KieServicesFactory;

    public class DecisionServerTest {

        private static final String REMOTING_URL = new String("remote://localhost:4447");

        private static final String USER = "kieserver";
        private static final String PASSWORD = "kieserver1!";

        private static final String INITIAL_CONTEXT_FACTORY = new String("org.jboss.naming.remote.client.InitialContextFactory");
        private static final String CONNECTION_FACTORY = new String("jms/RemoteConnectionFactory");
        private static final String REQUEST_QUEUE_JNDI = new String("jms/queue/KIE.SERVER.REQUEST");
        private static final String RESPONSE_QUEUE_JNDI = new String("jms/queue/KIE.SERVER.RESPONSE");

        private KieServicesConfiguration conf;
        private KieServicesClient kieServicesClient;

        @Test
        public void testJms() throws Exception {
            final Properties env = new Properties();
            env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
            env.put(Context.PROVIDER_URL, REMOTING_URL);
            env.put(Context.SECURITY_PRINCIPAL, USER);
            env.put(Context.SECURITY_CREDENTIALS, PASSWORD);
            InitialContext context = new InitialContext(env);

            Queue requestQueue = (Queue) context.lookup(REQUEST_QUEUE_JNDI);
            Queue responseQueue = (Queue) context.lookup(RESPONSE_QUEUE_JNDI);
            ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY);

            conf = KieServicesFactory.newJMSConfiguration(connectionFactory, requestQueue, responseQueue, USER, PASSWORD);

            kieServicesClient = KieServicesFactory.newKieServicesClient(conf);

        }
    }
Note that you must assign the the guest role to the user kieserver. Additionally, you must declare JMS dependency:
    <dependency>
      <groupId>org.jboss.as</groupId>
      <artifactId>jboss-as-jms-client-bom</artifactId>
      <version>7.5.6.Final-redhat-2</version>
      <type>pom</type>
    </dependency>

10.8.3. Server Response

Service responses are represented by the org.kie.server.api.model.ServiceResponse<T> object, where T represents the payload type. It has following attributes:
  • String msg: returns the response message.
  • ResponseType type: returns SUCCESS or FAILURE.
  • T result: returns the requested object.

Example 10.29. Hello World Server Response

import org.kie.server.api.model.ServiceResponse;
import org.kie.server.client.RuleServicesClient;

RuleServicesClient ruleClient = client.getServicesClient(RuleServicesClient.class);
ServiceResponse<String> response = ruleClient.executeCommands(container, batchCommand);
System.out.println(response.getResult());

10.8.4. Inserting and Executing Commands

You must use the org.kie.api.command.KieCommands class to insert commands. Use org.kie.api.KieServices.get().getCommands() to instantiate the KieCommands class. If you want to add multiple commands, you must use the BatchExecutionCommand wrapper. For additional example, follow the Hello World project.

Example 10.30. Inserting and Executing Commands

public void executeCommands() {
 String containerId = "hello";
 System.out.println("== Sending commands to the server ==");
 RuleServicesClient rulesClient = kieServicesClient.getServicesClient(RuleServicesClient.class);
 KieCommands commandsFactory = KieServices.Factory.get().getCommands();
 Command<?> insert = commandsFactory.newInsert("Some String OBJ");
 Command<?> fireAllRules = commandsFactory.newFireAllRules();
 Command<?> batchCommand = commandsFactory.newBatchExecution(Arrays.asList(insert, fireAllRules));
 ServiceResponse<String> executeResponse = rulesClient.executeCommands(containerId, batchCommand);
 if(executeResponse.getType() == ResponseType.SUCCESS) {
	System.out.println("Commands executed with success! Response: ");
	System.out.println(executeResponse.getResult());
 }
 else {
	System.out.println("Error executing rules. Message: ");
	System.out.println(executeResponse.getMsg());
	}
 }
You must add the org.drools:drools-compiler Maven dependency:
<!-- Valid for version 6.2.0 -->
<dependency>
	<groupId>org.drools</groupId>
	<artifactId>drools-compiler</artifactId>
	<version>6.3.0.Final</version>
</dependency>

10.8.5. Server Capabilities

Note

Following sections expand topics not covered by the Hello World project.
From the version 6.2, Realtime Decision Server supports the business process execution. To know your server capabilities, use the org.kie.server.api.model.KieServerInfo object.

Example 10.31. Server Capabilities

public void listCapabilities() {
    KieServerInfo serverInfo = kieServicesClient.getServerInfo().getResult();
    System.out.print("Server capabilities:");
    for(String capability: serverInfo.getCapabilities()) {
        System.out.print(" " + capability);
    }
    System.out.println();
}

10.8.6. Containers

Containers are represented by the org.kie.server.api.model.KieContainerResource object. List of resources is represented by the org.kie.server.api.model.KieContainerResourceList object.

Example 10.32. Print a List of Containers

public void listContainers() {
  KieContainerResourceList containersList = kieServicesClient.listContainers().getResult();
  List<KieContainerResource> kieContainers = containersList.getContainers();
  System.out.println("Available containers: ");
  for (KieContainerResource container : kieContainers) {
      System.out.println("\t" + container.getContainerId() + " (" + container.getReleaseId() + ")");
  }
}

10.8.7. Handling Containers

You can use the Realtime Decision Server Java client to create and dispose containers. If you dispose a container, ServiceResponse will be returned with void payload. If you create a container, KieContainerResource object will be returned.

Example 10.33. Dispose and Create a Container

public void disposeAndCreateContainer() {
	System.out.println("== Disposing and creating containers ==");
	List<KieContainerResource> kieContainers = kieServicesClient.listContainers().getResult().getContainers();
	if (kieContainers.size() == 0) {
		System.out.println("No containers available...");
		return;
	}
	KieContainerResource container = kieContainers.get(0);
	String containerId = container.getContainerId();
	ServiceResponse<Void> responseDispose = kieServicesClient.disposeContainer(containerId);
	if (responseDispose.getType() == ResponseType.FAILURE) {
		System.out.println("Error disposing " + containerId + ". Message: ");
		System.out.println(responseDispose.getMsg());
		return;
	}
		System.out.println("Success Disposing container " + containerId);
		System.out.println("Trying to recreate the container...");
		ServiceResponse<KieContainerResource> createResponse = kieServicesClient.createContainer(containerId, container);
		if(createResponse.getType() == ResponseType.FAILURE) {
		System.out.println("Error creating " + containerId + ". Message: ");
		System.out.println(responseDispose.getMsg());
		return;
	}
	System.out.println("Container recreated with success!");
	}

10.8.8. Available Realtime Decision Server Clients

KieServicesClient serves also as an entry point for other clients with the ability to perform various operations, such as JBoss BRMS commands and manage processes. Following services are available in the org.kie.server.client package:
  • JobServicesClient is used to schedule, cancel, requeue, and get job requests.
  • ProcessServicesClient is used to start, signal, and abort processes or work items.
  • QueryServicesClient is used to query processes, process nodes, and process variables.
  • RuleServicesClient is used to send commands to the server to perform rule-related operations (for example insert objects into the working memory, fire rules, ...).
  • UserTaskServicesClient is used to perform all user-task operations (start, claim, cancel a task) and query tasks by specified field (process instances id, user, ...)
The getServicesClient method provides access to any of these clients:
RuleServicesClient rulesClient = kieServicesClient.getServicesClient(RuleServicesClient.class);

10.8.9. List of Available Business Processes

Use QueryClient to list available process definitions. QueryClient methods use pagination, therefore in addition to the query you make, you must provide the current page and the number of results per page. In the provided example, the query starts on page 0 and lists the first 1000 results.

Example 10.34. List Processes

public void listProcesses() {
	System.out.println("== Listing Business Processes ==");
	QueryServicesClient queryClient = kieServicesClient.getServicesClient(QueryServicesClient.class);
	List<ProcessDefinition> findProcessesByContainerId = queryClient.findProcessesByContainerId("rewards", 0, 1000);
	for (ProcessDefinition def : findProcessesByContainerId) {
		System.out.println(def.getName() + " - " + def.getId() + " v" + def.getVersion());
	}
}