Java rules engine integration

xiaoxiao2021-03-06  41

Transfer from: http://starrynight.blogdriver.com/starrynight/237938.html

Introduction to the rules engine

The Java Rules Engine is a kind of reasoning engine that originated from rule-based expert systems.

The Java Rules Engine separates business decisions from the application code and writes business decisions using a predefined semantic module. The Java Rules Engine accepts data input, explains business rules, and makes business decisions based on rules. In this sense, it is an important progress in software methodology in "concerns separation".

The JSR-94 specification defines independent of the manufacturer's standard API, and developers can use this standard API to use the Different Products of Java Rules Engine Specification. However, it is worth noting that this specification does not force a syntax defined by a unified rule, so it may be necessary to transform rule definitions when it is necessary to transplant the application to another Java rule engine.

Rules-based expert system (RBES) expert system is a branch of artificial intelligence, which imitates human reasoning methods, reasoning using testive methods, and uses human understanding of terms to explain and prove its reasoning conclusions. Expert system has a lot of categories: neural network, based on case reasoning and rule system, etc.

The rule engine is part of a rule-based expert system. In order to understand the Java rule engine, the rules-based expert system (RBES) is briefly introduced below.

The technical architecture of RBES includes three parts: Rule Base (Knowledge Base), Working Memory (Fact Base), and Rule Engine. Their structure is as follows:

As shown above, the rule engine includes three parts: Pattern Matcher, Agenda, and Execution Engine. Pattern Matcher decides which rule to do, when to perform a rule; Agenda manages the execution of the rules selected by PatternMatcher; Execution Engine is responsible for rules and other actions.

RBES's reasoning (rules) engine and human thinking correspond, there are both of the rules engine: Forward-chaining and induction (Backward-chaining). Deductive method From an initial fact, the interpretation is constantly applying the rules to draw conclusions (or execute the specified action). The summary method is from hypotheses and constantly looking for facts that meet the hypothesis.

The REE algorithm is the most efficient forward-chaining reasoning algorithm, and the DROOLS project is an object-oriented Java implementation of the RETE algorithm.

The reasoning steps of the rules engine are as follows:

1. Enter the initial data (FACT) to Working Memory.

2. Use the Pattern Matcher Compare Rules (Rule) and Data (FACT).

3. If there is a conflict (Conflict), multiple rules are activated, and the rules of the conflict are placed in the conflict collection.

4. Resolve conflicts and put the activated rules in order in the order of Agenda.

5. Use the rule engine to perform the rules in Agenda. Repeat steps 2 through 5 until the rules in all Agenda are executed.

JSR 94: Java Rules Engine API

Based on rule programming is a declarative programming technology that allows you to solve the problem using the testistic rules instead of procedural instructions. The rule engine is a software module that determines how to make rules to reasoning data. Rule engine technology is particularly useful when using rule-based programming techniques in the insurance industry and financial services industry. The Java Rules Engine API is defined by Javax.Rules package is a standard enterprise API for accessing the rules engine. Java Rules Engine API allows client programs to use unified ways and different manufacturers' rules engine products, just like using JDBC to write different database products that are different from vendors. Java Rules Engine API includes a mechanism for creating and administering rule sets, adding, deleting, and modifying objects in Working Memory, and the mechanism of initialization, reset, and executing rule engines.

Use Java Rules Engine API

The Java Rules Engine API divides the interaction between and the rules engine into two categories: management activities and runtime activities. Management activities include instantiation rules engine and load rules. Running activities include operating Working Memory and execution rules. If you use the Java rule engine in the J2SE environment, you may need to implement all the above activities in your code. Instead, in the J2EE environment, the management activity of the Java Rules Engine is part of the application server. The reference implementation of JSR 94 includes a JCA connector for obtaining a RuleServiceProvider through JNDI.

Set the rule engine

The management activity phase of the Java rules engine begins to find a suitable javax.rules.ruleServiceProvider object, which is the entry of the application access rule engine. In the J2EE environment, you might get RuleServiceProvider through JNDI. Otherwise, you can use the Javax.Rules.RuleServiceProviderManager class:

Javax.Rules.ruleServiceProviderManager Class:

String Implname = "org.jcp.jsr94.ri.ruleServiceProvider";

Class.Forname (Implname);

RuleServiceProvider ServiceProvider = ruleServiceProviderManager.GetruleserviceProvider (IMPLNAME);

Once you have a RuleServiceProvider object, you can get a javax.rules.admin.ruleAdministrator class. From the RuleAdministrator class, you can get a RuleExecutionSetProvider, you can know from the class name, which is used to create a javax.rules.ruleExecutionSets object. RuleExecutionSet is basically a set of rules that are loaded, ready to execute.

Package javax.rules.Admin includes two different RuleExecutionSetProvider classes. The RuleExecutionSetProvider class itself includes a method of creating RuleExecutionSets from the Serializable object, so where the rule engine is located in the remote server, you can still use the RuleExecutionSetProvider class, and the parameters of the constructor can be passed through RMI. Another class is LOCALRULEXECUTIONSETPROVIDER, which contains other methods to create ruleexectionsets from non-Serializable resources (such as Java.io.Reader - local files). Assume that you have a RuleServiceProvider object, you can create a RuleExectionSet object from the local file rules.xml file. As shown in the following code: ruleadministrator admin = serviceProvider.getruleAdministrator ();

Hashmap property = new hashmap ();

Properties.Put ("Name", "My Rules");

Properties.Put ("Description", "a trivial rulebase);

FileReader Reader = New FileReader ("Rules.xml");

RuleExecutionSet ruleset = null;

Try {

LocalruleexecutionSetProvider Lresp =

Admin.getlocalruleexecutionSetProvider (Properties);

RuleSet = lresp.createruleexecutionSet (Reader, Properties);

} finally {

Reader.Close ();

}

Next, you can use the ruleexecutionset obtained by RuleAdministrator and assign it a name. At runtime, you can create a rulesession with the same name; this rulession uses this named RuleExecutionSet. See the example below:

Admin.RegisterruleexecutionSet ("Rules", Ruleset, Properties;

Execute rule engine

At runtime phase, you can see a rulesession object. The rulesession object is basically a rule engine instance that loads a specific rule set. You get a Ruleruntime object from RuleServiceProvider, follow Javax.Rules.ruleruntime gets the rulesession object.

The rulesession is divided into two categories: stateful and stateless. They have different functions. StatefulRulesession Working Memory can save status during multiple method calls. You can add multiple objects in Working Memory during multiple method calls, then execute the engine, and then add more objects and perform the engine again. In contrast, the StatelessRulesession class is not saved. In order to perform its Executerules method, you must provide all initial data for Working Memory, execute the rule engine, get a list of contents as the return value.

In the following example, we create a statefulrulesession instance, add two objects (an Integer and a string) to Working Memory, perform rules, then get all the content in Working Memory, returning as a java.util.list object. Finally, we call Release methods to clean up rulesession: ruleruntime runtime = rsp.getruleruntime ();

StatefulRulesession session = (statefulrulesession)

Runtime.createrulesession ("Rules", Properties,

Ruleruntime.Stateful_Session_Type);

Session.addObject (New Integer (1));

Session.adDObject ("a string");

session.executerules ();

List results = session.getObjects ();

session.release ();

Integrated JSR 94 Products Support JSR 94-specific products to achieve both commercial products, also have free open source projects. The most mature, most powerful commercial products are Ilog's JRules, which is also one of the active promoters of JSR 94 norms. Open source projects support JSR 94 specification are currently very few, only Drools and JLISA projects. It is worth noting that Jess is not an open source project, which can be used for academic research, but it is charged for commercial purposes.

JSR 94 product implementation

Java Rules Engine commercial products are:

L. Ilog's JRules

2. Blazesoft's Blaze

3. Rules4j

4. Java EXPERT SYSTEM Shell (JESS)

The implementation of open source projects includes:

l. drools project

2. JLISA project

3. OFBIZ RULE ENGINE (does not support JSR 94)

4. Mandarax (JSR 94 is not supported)

Integrate using Spring

The goal of integrating the Java rules engine is to encapsulate different implementations using standard Java rules engine APIs, and mask different product implementation details. The advantage of this is that when the different rule engine products are replaced, the application code can not be modified.

Package JSR94 implementation

The RuleEngineFacade class package Java rule engine, using RuleserviceProviderURL and RuleServiceProviderImpl, blocking the configuration of different products. code show as below:

Public class ruleenginefacade {

Private ruleadministrator ruleadministrator;

Private ruleServiceProvider ruleServiceProvider;

Private LocalruleexecutionSetProvider RuleSetProvider;

Private ruleruntime ruleruntime;

// Configuration Parameters

Private string ruleServiceProviderURL;

Private Class RuleserviceProviderImpl;

Public void setRviceProviderURL (String URL) {

This.RuleServiceProviderURL = URL;}

Public void setRuleserviceProviderImpl (Class Impl) {

this.RuleServiceProviderImpl = IMPL;

}

Public void init () throws exception {

RuleServiceProviderManager.RegisterruleServiceProvider (

RuleServiceProviderURL, RuleServiceProviderImpl;

RuleServiceProvider = RuleServiceProviderManager.GeeServiceProviderURL;

RuleAdministrator = ruleServiceProvider.GetruleAdministrator ();

RuleSetProvider = ruleadministrator.getlocalruleexecutionSetProvider (NULL);

}

Public void addruleexecutionSet (String Binduri, InputStream ResourceAsteam)

Throws exception {

Reader RuleReader = New InputStreamReader (ResourceAsStream);

RuleExecutionSet ruleexecutionSet =

RuleSetProvider.createruleExecutionSet (RuleReader, NULL);

Ruleadministrator.registerruleexecutionSet (Binduri, RuleExecutionSet, NULL)

}

Public StatelessRulesession GetStateLessRulessis (String Key)

Throws exception {

Ruleruntime = ruleServiceProvider.GetruLeruntime ();

Return (StatelessRulesession) ruleruntime.createrulesession (key, null, ruleruntime.stateless_ssion_type);

}

Public StatefulRulesession GetStatefulRulesession (String Key)

Throws exception {

Ruleruntime = ruleServiceProvider.GetruLeruntime ();

Return (StatefulRulesession) Ruleruntime.createrulesession

Key, NULL, Ruleruntime.Stateful_Session_Type);

}

Public ruleServiceProvider getRviceProvider () {

Return this.ruleServiceProvider;

}

}

The package rules Rule class encapsulates the specific business rules, and its input parameter Rulename is the configuration file name that defines the rule and rely on the RuleEngineFacade component. code show as below:

PUBLIC CLASS RULE {

Private string rulename;

Private ruleenginefacade enginefacade;

Public void init () throws exception {

InputStream IS = rule.class.getResourceceasstream (Rulename); EngineFacade.AddruleExecutionSet (Rulename, IS);

Is.close ();

}

Public void setRulename (String name) {

this.Rulename = name;

}

Public void setEngineFacade (ruleenginefacade engine) {

THIS.ENGINEFACADE = ENGINE

}

Public statelessRulesession GetStateLessRulesession ()

Throws exception {

Return EngineFacade.getStateLessRules (RuleName);

}

Public StatefulRulesession GetStateFulerulesession ()

Throws exception {

Return EngineFacade.getStateFulRules (Rulename);

}

}

Assembly rule component

The configuration files for assembly rules are as follows:

http://drools.org/

Org.drools.jsr94.rules.ruleServiceProviderImpl

/TEST / FIBONACCI.DRL

Test case

Finally, we write test cases, the code is as follows:

Public Class Jsrtest Extends Testcase {

ApplicationContext CTX = NULL;

Protected void setup () throws exception {

Super.setup ();

CTX = New FileSystemXmlapplicationContext ("Testrule.xml");

}

Public void testgetRulesession () throws exception {

Rule rule = (rule) CTX.getBean ("Fibonacci");

AssertNotnull (rule.getStateFulerueSession ());

AssertNotnull (rule.getStateLessRulesession);

}

Public void testStateLessrule () throws exception {

Rule rule = (rule) CTX.getBean ("Fibonacci");

Fibonacci Fibonacci = New Fibonacci (50);

List list = new arraylist ();

List.add (Fibonacci);

STATELESSRULESSESSION session = rule.getStateLessRulesession ();

Session.executerules (List);

session.release ();

}

Public void testStatefulrule () throws exception {

Rule rule = (rule) CTX.getBean ("Fibonacci");

Fibonacci Fibonacci = New Fibonacci (50);

StatefulRulesession session = rule.getStateFulerulesession ();

Session.addObject (Fibonacci);

session.executerules ();

session.release ();

}

}

Run the test case, a green strip appears, and the test is passed.

Rule definition language transformation

Because the JSR 94 specification does not force a syntax defined by the unified rule, it is necessary to transform the application to other Java rule engines, it may be necessary to define the transformation rules, such as converting the DROOLS private DRL rule language to a standard Ruleml, JESS Rule language is converted into ruleml et al. This work is generally completed by the XSLT converter.

转载请注明原文地址:https://www.9cbs.com/read-61652.html

New Post(0)