Chapter 4. Hello World Rule Example

This chapter demonstrates basic features of Red Hat JBoss BRMS by setting up a Hello World project with a simple business rule.

In this chapter, you will:

  • Create a repository.
  • Create a project.
  • Create a rule.
  • Create a knowledge base.
  • Build and deploy the project.

4.1. Create Your First Rule Using Business Central

Prerequisite

Ensure that you have successfully installed Red Hat JBoss BRMS and Maven before you run this rule example. Red Hat JBoss BRMS should be started and you should be logged in the Business Central.

Procedure: Create and Execute Your First Rule Using Business Central

  1. On the main menu of Business Central, click AuthoringAdministration and then Organizational UnitManage Organizational Units.
  2. Click Add.
  3. In the displayed Add New Organizational Unit dialog box, define the unit properties. For example:

    • Name: Hello World
    • Owner: finance-dept@company.org

    Click OK.

  4. On the perspective menu, click RepositoriesNew repository.
  5. In the displayed New Repository dialog box, define the repository properties. For example:

    • Repository Name: EmployeeRepo
    • In the In Organizational Unit drop-down menu, select Hello World.

    Click Finish.

  6. Go to AuthoringProject Authoring.
  7. In the Project Explorer, under the organizational unit drop-down box, select Hello World, and in the repository drop-down box select EmployeeRepo.
  8. On the perspective menu, go to New ItemProject.
  9. In the displayed New Project wizard, provide a name (for example MyProject) for your project. In the Group Artifact Version part of the wizard, define the Maven properties of the project. For example:

    • Group ID: org.brms
    • Artifact ID: MyProject
    • Version ID: 1.0.0

    Click Finish.

  10. On the perspective menu, go to New ItemData Object.
  11. In the displayed Create new Data Object dialog box, provide the values for object name and package. For example:

    • Data Object: Person
    • Package: org.brms.myproject

    Click Ok.

  12. In the displayed Person window of the newly created Person data object, click add field to open the New field dialogue. Add a variable name in the Id field, select data type for the variable in the Type field, and click Create and continue until you have defined all the necessary variables. For example:

    • Id: firstName

      Type: String

    • Id: lastName

      Type: String

    • Id: hourlyRate

      Type: Integer

    • Id: wage

      Type: Integer

    Click Create for the last variable and then Save.

  13. On the perspective menu, click New ItemDRL File.
  14. In the Create new dialog box, provide the name and package name of your rule file. For example:

    • DRL file name: MyRule
    • Package: org.brms.myproject

    Click Ok.

  15. In the displayed DRL editor with MyRule.drl, create the rule:

    package org.brms.myproject;
    rule "MyRule"
    when
    
      Person(hourlyRate*wage > 100)
      Person(name : firstName, surname : lastName)
    
    then
      System.out.println( "Hello" + " " + name + " " + surname + "!" );
      System.out.println( "You are rich!" );
    
    end

    Click Save.

    For more information about rules, see chapter All About Rules of the Red Hat JBoss BPM Suite Development Guide.

  16. Following steps demonstrate how to create your own knowledge base. For more information about knowledge session, see the KIE Sessions chapter from the Red Hat JBoss BPM Suite Development Guide.

    1. Click Open Project Editor.
    2. Click Project Settings: Project General SettingsKnowledge Base Settings: Knowledge bases and sessions.
    3. Click Add and enter the name of your knowledge base.

      Enter myBase for this example.

    4. Click Make Default
    5. Click Add under Knowledge Sessions.
    6. Enter the name of your session. For example mySession. Check Default and select the stateless state.
    7. Click Save in the top right corner.
  17. Click Open Project Editor and then Build & Deploy.

    A green notification appears in the upper part of the screen informing you that the project has been built and deployed successfully to the Execution Server.

    Note

    In case a red notification appears, informing you that the build has failed, you will be presented with information about the build failure in the Red Hat JBoss BRMS console. This is crucial information in case of troubleshooting your application. Make sure you have saved all assets before attempting to build your project.

4.2. Configuring Realtime Decision Server

Register a Realtime Decision Server instance to fire your rules through the REST API. This section illustrates:

  • How to register the Realtime Decision Server.
  • How to add a new container to the Realtime Decision Server.

Procedure: Registering Realtime Decision Server

  1. Create a new user with the role kie-server:

    On the command line, change into EAP_HOME/bin/ and execute the following command:

    ~]$ ./add-user.sh -a --user kieserver --password kieserver1! --role kie-server,rest-all
  2. Open EAP_HOME/standalone/configuration/standalone.xml and add the following properties into the system-properties tag:

    <property name="org.kie.server.user"
              value="kieserver"></property>
    <property name="org.kie.server.pwd"
              value="kieserver1!"></property>
    <property name="org.kie.server.location"
              value="http://localhost:8080/kie-server/services/rest/server"></property>
    <property name="org.kie.server.controller"
              value="http://localhost:8080/business-central/rest/controller"></property>
    <property name="org.kie.server.controller.user"
              value="kieserver"></property>
    <property name="org.kie.server.controller.pwd"
              value="kieserver1!"></property>
    <property name="org.kie.server.id"
              value="local-server-123"></property>
  3. Change into EAP_HOME/bin/ and execute the following command:

    ~]$ ./standalone.sh
  4. In the Business Central, click DeployExecution Servers.

    In the displayed window, you will see local-server-123. Click Add Container under KIE CONTAINERS.

  5. The New Container dialog opens. Enter the following:

    • Name: myContainer
    • Click Search and click Select next to MyProject-1.0.0.jar.
    • Click Finish to create the container.
  6. Select myContainer and click Start to start the container.

4.3. Firing Rules Using KIE Server Java Client API

To fire the rules, you need to send a request to the Realtime Decision Server. This section demonstrates how to use the KIE Server Java Client API to send requests using REST API. You can use any client to send requests to the server.

Note

Make sure you have configured your Maven installation to use Red Hat JBoss BRMS online repositories. For more information about Maven configuration, see the Configuring Maven to Use Online Repositories section from the Red Hat JBoss BPM Suite Installation Guide.

  1. Change into a directory of your choice and execute the following command:

    ~]$ mvn archetype:generate -DgroupId=com.MyProject.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

    This creates a directory called my-app with the following structure:

    my-app
    |-- pom.xml
    `-- src
        |-- main
        |   `-- java
        |       `-- com
        |           `-- MyProject
        |               `-- app
        |                   `-- App.java
        `-- test
            `-- java
                `-- com
                    `-- MyProject
                        `-- app
                            `-- AppTest.java
  2. Declare libraries your Maven project will use. Edit my-app/pom.xml to set the Red Hat JBoss BRMS dependencies. For more information about Bill of Material (BOM) and dependency management, see chapter Dependency Management of the Red Hat JBoss BPM Suite Development Guide.

    <!-- Declaration of BOM -->
    <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.jboss.bom.brms</groupId>
        <artifactId>jboss-brms-bpmsuite-platform-bom</artifactId>
        <version>6.4.0.GA-redhat-2</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
    </dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
      </dependency>
    <!-- Realtime Decision Server dependencies -->
      <dependency>
        <groupId>org.kie.server</groupId>
        <artifactId>kie-server-client</artifactId>
      </dependency>
      <dependency>
        <groupId>org.kie.server</groupId>
        <artifactId>kie-server-api</artifactId>
      </dependency>
    <!-- Red Hat JBoss BRMS dependency. -->
      <dependency>
        <groupId>org.drools</groupId>
        <artifactId>drools-core</artifactId>
      </dependency>
    
      <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
      </dependency>
    <!-- Your project -->
      <dependency>
        <groupId>org.brms</groupId>
        <artifactId>MyProject</artifactId>
        <version>1.0.0</version>
      </dependency>
    </dependencies>
    Note

    The last dependency is the project you have built in Red Hat JBoss BRMS. The model class (org.brms.myproject.Person in this example) in the client code, that is your Maven application, needs to match your server side, that is the Red Hat JBoss BRMS. Otherwise, the rules will not match when sending a request. The easiest way to achieve this is to share the model class between both sides. You achieve this by adding it as a Maven dependency.

    Therefore, make sure that the following attributes match what you had entered while creating a new project in the Business Central:

    • groupId
    • artifactId
    • version
  3. Locate the my-app/src/test/java/com/MyProject/app/AppTest.java Java class. Maven creates this class by default.
  4. Edit AppTest.java. Add the following imports:

    import org.kie.api.command.BatchExecutionCommand;
    import org.kie.server.api.model.ServiceResponse;
    import org.kie.server.client.KieServicesClient;
    import org.kie.server.client.KieServicesConfiguration;
    import org.kie.server.client.KieServicesFactory;
    import org.kie.server.client.RuleServicesClient;
    import org.kie.api.KieServices;
    import org.kie.api.command.Command;
    
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    import org.brms.myproject.Person;
    import org.drools.core.command.impl.GenericCommand;

    Locate the testApp() method, load the knowledge base and fire your rule by adding the following code:

    Person p1 = new Person();
    p1.setFirstName("Anton");
    p1.setLastName("RedHat");
    p1.setHourlyRate(11);
    p1.setWage(20);
    
    String url = "http://localhost:8080/kie-server/services/rest/server";
    String username = "kieserver";
    String password = "kieserver1!";
    String container = "myContainer";
    String session = "mySession";
    
    KieServicesConfiguration config = KieServicesFactory
      .newRestConfiguration(url, username, password);
    Set<Class<?>> allClasses = new HashSet<Class<?>>();
    allClasses.add(Person.class);
    config.addExtraClasses(allClasses);
    
    KieServicesClient client  = KieServicesFactory.newKieServicesClient(config);
    RuleServicesClient ruleClient = client.getServicesClient(RuleServicesClient.class);
    List<GenericCommand<?>> commands = new ArrayList<GenericCommand<?>>();
    
    commands.add((GenericCommand<?>) KieServices.Factory
      .get().getCommands().newInsert(p1,"Person Insert ID"));
    commands.add((GenericCommand<?>) KieServices.Factory
      .get().getCommands().newFireAllRules("fire-identifier"));
    
    BatchExecutionCommand batchCommand = KieServices.Factory
      .get().getCommands().newBatchExecution(commands,session);
    ServiceResponse<String> response = ruleClient.executeCommands(container, batchCommand);
    System.out.println(response.getResult());

    Note that the default marshaller is JAXB, unless set differently. That means you must set its context with any custom classes you plan to use. In this example, that is Person.class. Since the example uses a stateless session, the kie session is disposed of once a single command is executed. That is why you need to wrap multiple commands in the BatchCommand object.

    To change the marshaller type, enter one of the following commands:

    config.setMarshallingFormat(MarshallingFormat.JSON);
    config.setMarshallingFormat(MarshallingFormat.XSTREAM);

    And add the following import:

    import org.kie.server.api.marshalling.MarshallingFormat;
  5. Navigate to my-app and execute the following command from the command line:

    ~]$ mvn clean install

    Note that there is the Maven output and the Red Hat JBoss BRMS output. The expected output in the Red Hat JBoss BRMS console is:

    16:26:56,119 INFO  [stdout] (http-/127.0.0.1:8080-5) Hello Anton RedHat!
    16:26:56,119 INFO  [stdout] (http-/127.0.0.1:8080-5) You are rich!