Drools Rules Engine introduces a

Source: Internet
Author: User
Tags file system static class xmlns jboss knowledge base git clone maven central jbpm

Original address: http://docs.jboss.org/drools/release/6.2.0.Final/drools-docs/html_single/index.html

All the steps in front of the original text can be omitted, directly from the installation of the Eclipse plug-in, the installation address is: http://docs.jboss.org/drools/release/6.2.0.Final/drools-docs/html_single/index.html

In the country can now be directly update, so do not need to use a Zip installation method.

A menu drools appears in Eclipse's preferences, and a runtime is included in installed Drools (select the binaries directory that was unzipped after downloading the website).

Create a new drools Project

Src/main/java New class Droolstest:

Package com.sample;
Import org.kie.api.KieServices;
Import Org.kie.api.runtime.KieContainer;


Import org.kie.api.runtime.KieSession;
 /** * This was a sample class to launch a rule.  */public class Droolstest {public static final void main (string[] args) {try {//load up the
       Knowledge Base Kieservices KS = KieServices.Factory.get ();
        Kiecontainer Kcontainer = Ks.getkieclasspathcontainer ();


            Kiesession ksession = kcontainer.newkiesession ("Ksession-rules");
            Go!
            Message message = new Message ();
            Message.setmessage ("Hello World");
            Message.setstatus (Message.hello);
            Ksession.insert (message);
        Ksession.fireallrules ();
        } catch (Throwable t) {t.printstacktrace ();
        }} public static class Message {public static final int HELLO = 0;


        public static final int GOODBYE = 1;


        Private String message; private int status;
        Public String GetMessage () {return this.message;
        The public void Setmessage (String message) {this.message = message;
        } public int GetStatus () {return this.status;
        } public void SetStatus (int status) {this.status = status; }


    }


}



Src/main/resources/rules New Rule File

Package com.sample
 
import com.sample.DroolsTest.Message;
 
Rule "Hello World"
    when
        m:message (status = = Message.hello, mymessage:message) then
        System.out.print ln (mymessage);
        M.setmessage ("Goodbye Cruel World");
        M.setstatus (Message.goodbye);
        Update (m);
End


rule "GoodBye"
    when
        Message (status = = Message.goodbye, mymessage:message
    )
        Then System.out.println (mymessage);
End


Src/main/resources/meta-inf New configuration file Kmodule.xml:

<?xml version= "1.0" encoding= "UTF-8"?> <kmodule
xmlns= "Http://jboss.org/kie/6.0.0/kmodule" >
    <kbase name= "Rules" packages= "Rules" >
        <ksession name= "Ksession-rules"/>
    </kbase>
</kmodule>


Click Run to see the results:

slf4j:failed to load Class "Org.slf4j.impl.StaticLoggerBinder".
Slf4j:defaulting to No-operation (NOP) Logger implementation
Slf4j:see http://www.slf4j.org/codes.html# Staticloggerbinder for further details.
Hello World
Goodbye Cruel World

Explain the logic of this example: the first three lines of the main function are fixed notation, which loads "ksession-rules". This name is configured in the Kmodule.xml, it will be in the resources directory under the rules directory to find the rule.

The main function first writes a message of type Message.hello to the object, which specifies that if the type is Message.hello, the message is printed and the object type Message.goodbye is updated.

Because update (m) is then triggered again by the rule engine, because the type updates to Message.goodbye will trigger rule 2, printing out the new type of message.


How to use drools in maven:

Drools is available in the MAVEN central repository, so there is no need to configure additional Maven repositories, as follows:

    <dependencies>
      <dependency>
        <groupId>org.drools</groupId>
        <artifactid >drools-bom</artifactId>
        <type>pom</type>
        <version>...</version>
        <scope>import</scope>
      </dependency> ...
    </dependencies>
  </dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-api</artifactId>
    </ dependency>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId> drools-compiler</artifactid>
      <scope>runtime</scope>
    </dependency>
    ...
  <dependencies>



Run Time:

The runtime here is referring to: if you deploy a binary form of rules (Knowledgepackage objects or Knowledgebase objects), this will make your runtime very lightweight. You can use Drools-compiler to generate rule packages and then deploy them to the runtime environment. The run-time environment requires only Drool-core.jar and Knowledge-api.jar to run.

Rule Workbench (Regular workbench)

Requires more than Eclipse3.4 (GEF plug-ins above 3.4)

Otherwise, it's integrated with JBoss IDE.

Locate the corresponding Drools plug-in installation address via the http://www.jboss.org/drools/downloads.html link.

Drools Run Time:

The runtime here represents a collection of jar packages, which are actually the different versions of drools that are downloaded. Eclipse requires a default drools runtime.

Build Drools from Source code:

Drools and jbpm use git to do version control. Link to: https://github.com/droolsjbpm

For example, the Guvnor sub-project, build method is as follows:

$ git clone git@github.com:droolsjbpm/guvnor.git ...
$ CD guvnor
$ mvn clean install-dskiptests-dfull
...
Starting from 6.0 Kie,drools (including Workbench), JBPM (including designers and consoles), Optaplanner will share the same version number.

What is Kie.

Kie is a bottom-level library shared by Drools and JBPM, which provides a unified basic approach, a programming model to build, deploy, and provide a toolset.

Structure of the Kie:



Optaplanner is a local search and optimization tool that is now a top-level project with Drools and JBPM.

Dashboard Builder is a powerful reporting tool. It is independent of drools and JBPM.

Uberfire is the base component of the Workbench project, and he provides a work desk capability like the Eclipse style (such as a plugin). It is also independent of drools and JBPM.

Guvnor had too much responsibility in 5.0. Within 6.0 it will focus on encapsulating Uberfire plug-in users to build the Web IDE.

The release version of the Drools and JBPM Workbench uses uberfire as the basis and then adds some plugins guvnor as well as drools, jbpm own plugins like decision table,guided Editor,bpmn2 Designer, Human task.


The life cycle of Kie

Edit

Edit the Knowledge Base (knowledge) with visual tools such as DRL bpmn2,decision table, class models, etc.

Build

Build the repository of the previous edit into a deployment unit, which is the jar for Kie.

Test

Before deploying the jar to the application, test

Deployment

Deploy the jar to a location where an app can be used

Kie using a MAVEN-style warehouse

Use (utilize)

Load the jar and then provide a Kiesession object so that the application can interact with it.

Run

The system interacts with it via the Kiesession API

Job

User calls to it via UI or command line

Management

Manage some kiesession or Kiecontainer


Build, deploy, use, and run

6.0 introduces a new mate and method to build the knowledge base, and 5.0 is programmed, of course, in the way that this programming is available for backwards compatibility.

Kie project or module is actually a MAVEN project or module, just a kmodule.xml under the Meta-inf directory. This file is used to describe the session that selects those knowledge base and configures the knowledge base. It can provide XML support through spring or OSGi blueprints.


Although Maven can build and deploy the Kie project, there is a plug-in that generates many class files that can provide validation and run faster.

Example diagram:



Org.kie.api.core.builder Content


Kiecontainer


Example 4.2. Create a Kiecontainer

Kieservices kieservices = KieServices.Factory.get ();
Kiecontainer Kcontainer = Kieservices.getkieclasspathcontainer ();

Kieservice


Kmodule.xml is the place to declare kiebase and kiesession definitions.

Kiebase includes rules,processes,functions and type models.

Data not included in Kiebase

The kiesession created from Kiebase contains data, Kiebase is created as a heavyweight, and kiesession is a lightweight thing.

Kiecontainer has a mechanism to automatically cache the Kiebase, the end user does not have to worry about this problem


Kiebase


Kiesession can also be directly created directly from the Kiecontainer defined in the Kmodule.xml.



Example 4.3. Kmodule.xml in the configuration kiebase example

<kmodule xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://jboss.org/kie/6.0.0/kmodule" > <configuration> <property key= "drools.evaluator.supersetOf" value= " Org.mycompany.SupersetOfEvaluatorDefinition "/> </configuration> <kbase name=" KBase1 "default=" true "
    Eventprocessingmode= "Cloud" equalsbehavior= "equality" declarativeagenda= "Enabled" packages= "Org.domain.pkg1" > <ksession name= "Ksession2_1" type= "stateful" default= "true"/> <ksession name= "ksession2_2" type= "stateless" Default= "false" beliefsystem= "Jtms"/> </kbase> <kbase name= "KBase2" default= "false" eventprocessingmode= "Stream" equalsbehavior= "equality" declarativeagenda= "Enabled" packages= "Org.domain.pkg2, Org.domain.pkg3" includes = "KBase1" > <ksession name= "ksession3_1" type= "stateful" default= "false" Clocktype= "Realtime" > <filel Ogger file= "Drools.log" threaded= "true" interval= "ten"/> <workitemhandlers&Gt <workitemhandler name= "name" type= "Org.domain.WorkItemHandler"/> </workItemHandlers> <listeners > <ruleruntimeeventlistener type= "Org.domain.RuleRuntimeListener"/> <agendaeventlistener type=
        "Org.domain.FirstAgendaListener"/> <agendaeventlistener type= "Org.domain.SecondAgendaListener"/> <processeventlistener type= "Org.domain.ProcessListener"/> </listeners> </ksession> </kbas E> </kmodule>



Table 4.1. Kbase Properties

Attribute name Default Value admitted values meaning
Name None Any The name with which retrieve this kiebase from the Kiecontainer. The only mandatory attribute.
Includes None Any comma separated list A Comma separated list of other kiebases contained in this kmodule. The artifacts of all these kiebases would be a also included in this one.
Packages All Any comma separated list By default all the Drools artifacts under the Resources folder, at any level, is included into the kiebase. This attribute allows-to-limit the artifacts that would be a compiled in this kiebase to only the ones belonging to the list of packages.
Default False True, False Defines if this kiebase are the default one for this module, so it can be created from the Kiecontainer without passing any Name to it. There can is at the most one of the default kiebase in each module.
Equalsbehavior Identity Identity, equality Defines the behavior of Drools when a new fact was inserted into the working Memory. With identity it always create a new facthandle unless the same object isn ' t already present in the working Memory, while With equality only if the newly inserted object was not equal (according to it equal method) to an already existing fact.
Eventprocessingmode Cloud Cloud, Stream When compiled in cloud mode the Kiebase treats events as normal facts, while in stream mode allow temporal reasoning on th Em.
Declarativeagenda Disabled Disabled, Enabled Defines if the declarative Agenda is enabled or not.

Example 4.4. Parse out kiebases and kiesessions from Kiecontainer

Kieservices kieservices = KieServices.Factory.get ();
Kiecontainer Kcontainer = Kieservices.getkieclasspathcontainer ();

Kiebase kBase1 = kcontainer.getkiebase ("KBase1");
Kiesession KieSession1 = kcontainer.newkiesession ("Ksession2_1");
Statelesskiesession KieSession2 = kcontainer.newstatelesskiesession ("ksession2_2");



Because Ksession2_1 and ksession2_2 are different types, one is stateful and the other is stateless. So the method they use is different, if used wrong will throw runtimeexception.


Use Maven to build

The Kie plugin allows artifact to be verified and precompiled, so it is recommended to always use this plugin. Figure below

Example 4.7. Increase the Kie plugin in pom.xml

  <build>
    <plugins>
      <plugin>
        <groupId>org.kie</groupId>
        < artifactid>kie-maven-plugin</artifactid>
        <version>${project.version}</version>
        <extensions>true</extensions>
      </plugin>
    </plugins>
  </build>        
      

To define Kiemodule with a program

In fact, you can also use the program to define kiemodule inside the kiebase and kiesession. To do this you need to create a kiefilesystem first. It is a virtual file system and then adds all the resources in the project.


Like other core components, you can also get Kiefilesystem from Kieservices.



Example 4.8. Example of kmodule.xml the same effect by way of programming

Kieservices kieservices = KieServices.Factory.get ();
Kiemodulemodel Kiemodulemodel = Kieservices.newkiemodulemodel ();

Kiebasemodel KieBaseModel1 = Kiemodulemodel.newkiebasemodel ("KBase1")
        . SetDefault (True)
        . Setequalsbehavior (equalitybehavioroption.equality)
        . Seteventprocessingmode (eventprocessingoption.stream);

Kiesessionmodel KsessionModel1 = Kiebasemodel1.newkiesessionmodel ("KSession1")
        . SetDefault (True)
        . SetType (KieSessionModel.KieSessionType.STATEFUL)
        . Setclocktype (Clocktypeoption.get ("Realtime"));

Kiefilesystem KFS = Kieservices.newkiefilesystem ();


The following must also be given to Kiefilesystem plus other necessary artifacts:

Example 4.9. Adding Kie artifacts to a kiefilesystem

Kiefilesystem KFS = ...
Kfs.write ("Src/main/resources/kbase1/ruleset1.drl", STRINGCONTAININGAVALIDDRL)
        . Write ("src/main/resources/ Dtable.xls ",
                kieservices.getresources (). Newinputstreamresource (Dtablefilestream));
The example shows that adding kie artifact can be done through the regular string or through the resources.


Kieresources


The type of resources can be inferred by extension or specified by ResourceType, as follows:

Example 4.10. Creating and adding a Resource with an explicit type

Kiefilesystem KFS = ...
Kfs.write ("Src/main/resources/mydrl.txt",
           kieservices.getresources (). Newinputstreamresource (DrlStream)
                      . Setresourcetype (RESOURCETYPE.DRL));

Load all the resources into Kiefilesystem and then pass the Kiefilesystem to Kiebuilder to build.

Kiebuilder


When the content inside the Kiefilesystem is built, the run result kiemodule automatically be added Kierepository,kierepository is a singleton.


You can also use ReleaseID to get Kiecontainer through kieservices after this. For example:

Example 4.11. Building the contents of a kiefilesystem and creating a Kiecontainer

Kieservices kieservices = KieServices.Factory.get ();
Kiefilesystem KFS = ...
Kieservices.newkiebuilder (KFS). Buildall ();
Kiecontainer Kiecontainer = Kieservices.newkiecontainer (Kieservices.getrepository (). GetDefaultReleaseId ());

At this point, you can get kiebase and create kiesession, similar to the previous method.

Best practices show that it's best to check the compilation results of Kiebuilder.

Example 4.12. Checking a compilation didn ' t produce any error

Kiebuilder Kiebuilder = Kieservices.newkiebuilder (KFS). Buildall ();
Assertequals (0, Kiebuilder.getresults (). Getmessages (Message.Level.ERROR). Size ());
Modifying the default build behavior

By default, when a new rule with the same name is added, it replaces the old rule and prints the info log. Most of the situation is OK, but some users want to block this behavior and report the error log. Examples are as follows:

Example 4.13. Setting the severity using properties

Sets the severity of rule updates
Drools.kbuilder.severity.duplicateRule = <info| Warning| Error>
//sets the severity of function updates
drools.kbuilder.severity.duplicateFunction = <info| Warning| Error>

4.2.3 Deployment

4.2.3.1 Kiebase

Kiebase is a repository of knowledge-defined collections of applications. It contains rules,processes,functions and type models. The kiebase itself does not contain any data. The session created by Kiebase can be used to insert data and then use the session to start the process instance. The kiebase can be taken from the Kiecontainer (including the Kiemodule).


Sometimes, in an OSGi environment, Kiebase needs to resolve types that are not defined in the default class loader. This will require Kiebaseconfiguration, which has an additional class loader that can be passed to it when Kiecontainer creates the kiebase.

Example 4.14. Creating a new kiebase with a custom ClassLoader

Kieservices kieservices = KieServices.Factory.get ();
Kiebaseconfiguration kbaseconf = kieservices.newkiebaseconfiguration (null, MyType.class.getClassLoader ());

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.