Using a Process in Your Application

There are two things you need to do to be able to execute processes from within your application: (1) you need to create a Knowledge Base that contains the definition of the process, and (2) you need to start the process by creating a session to communicate with the process engine and start the process.

  1. Creating a Knowledge Base: Once you have a valid process, you can add the process to the Knowledge Base. Note that this is almost identical to adding rules to the Knowledge Base, except for the type of knowledge added:

    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add( ResourceFactory.newClassPathResource("MyProcess.rf"),
                  ResourceType.DRF );

    After adding all your knowledge to the builder (you can add more than one process, and even rules), you should probably check whether the process (and rules) have been parsed correctly and write out any errors like this:

    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    if (errors.size() > 0) {
        for (KnowledgeBuilderError error: errors) {
            System.err.println(error);
        }
        throw new IllegalArgumentException("Could not parse knowledge.");
    }

    Next, you need to create the Knowledge Base that contains all the necessary processes (and rules) like this:

    KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
  2. Starting a process: Processes are only executed if you explicitly state that they should be executed. This is because you could potentially define a lot of processes in your Knowledge Base and the engine has no way to know when you would like to start each of these. To activate a particular process, you will need to start it by calling the startProcess method on your session. For example:

    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
    ksession.startProcess("com.sample.MyProcess");

    The parameter of the startProcess method represents the id of the process that needs to be started. This process id needs to be specified as a property of the process, shown in the Properties View when you click the background canvas of your process. If your process also requires the execution of rules during the execution of the process, you also need to call the ksession.fireAllRules() method to make sure the rules are executed as well. That's it!

    You may specify additional parameters that are used to pass on input data to the process, using the startProcess(String processId, Map parameters) method, which takes an additional set of parameters as name-value pairs. These parameters are then copied to the newly created process instance as top-level variables of the process.

    You can also start a process from within a rule consequence, using

    kcontext.getKnowledgeRuntime().startProcess("com.sample.MyProcess");