Java rules engine and its API application detailed

Source: Internet
Author: User
Tags define object definition execution integer object model knowledge base access
Detailed

In this paper, the Java Rules Engine and its API (JSR-94) and related implementation are described in detail, the architecture and API application of the detailed description, and point out the Java Rules Engine, rule language, JSR-94 and the relationship between the JSR-94, as well as the shortcomings and prospects

In this paper, the Java Rules Engine and its API (JSR-94) and related implementation are described in detail, the architecture and API application of the detailed description, and point out the Java Rules Engine, rule language, JSR-94 and the relationship between the JSR-94, as well as the shortcomings and prospects

The development of complex enterprise-level projects, as well as the business rules with changing external conditions (business logic), are in urgent need of separating the business decision logic of business decision makers from the technical decisions of application developers, and placing these business decisions in central databases or other unified locations, They can be dynamically managed and modified at runtime (i.e. business time) to provide flexibility and adaptability to the software system. The rule engine is a solution that is applied to the dynamic environment described above.

The first part of this paper briefly introduces the background of rule engine and rule-based expert system, the second part introduces the rules engine and its architecture and algorithm, the third part introduces various Java rules engine, such as commercial product and open source project implementation, Part Four introduces the Java Rules Engine API (JSR-94) in detail, the architecture, management API and runtime APIs and related security issues are explained, and part fifth discusses the rules language and its standardization, and the sixth part gives a simple example of using the Java Rules Engine API. Part VII gives summary and Outlook.

   1. Introduction

1.1 Rule Engine generating background

Business managers have the following requirements for the development of enterprise-class IT systems: (1) To improve efficiency, management processes must be automated, even if modern business rules are unusually complex (2) the market requires frequent changes in business rules, IT systems must be based on the changes in business rules fast, low-cost updates (3) for fast, low-cost updates, Business people should be able to directly manage the rules in the IT system without requiring program developers to participate.

The project developers encountered the following problems: (1) program = algorithm + data structure, some complex business rules it is difficult to derive algorithm and abstract data Model (2) software engineering requirements from the requirements-> design-> coding, but the business rules often in the demand phase may not be clear, After the design and coding are still changing, business rules are often embedded in the system code (3) for programmers, the system has been maintained, updated difficult, and more unlikely to allow business personnel to manage.

The emergence of rule-based expert systems is an opportunity for developers to solve problems. The rule engine is developed by the inference engine in a rule-based expert system. The following is a brief introduction to rule-based expert systems.

1.2 rule-based Expert system (RBEs)

The expert system is a branch of artificial intelligence that imitates human reasoning, uses exploratory methods for reasoning, and interprets and proves its inference by using terms that humans can understand. Expert systems have many classifications: neural networks, case-based reasoning, and rule-based systems.

RBEs consists of three parts: rule base (Knowledge Base), Working Memory (fact base), and inference Engine (inference engine). Their structure is as follows:

Figure 1. The composition of rule-based expert system

As shown in the previous illustration, the inference engine consists of three parts: pattern Matcher, agenda, and execution Engine. The pattern Matcher when to execute which rule, agenda to manage the order of execution of the rules selected by Patternmatcher, and Execution engine is responsible for enforcing the rules and other actions. The

Inference engine is added to the agenda by deciding which rules meet the facts or objectives, and that the rules are given precedence, and that the rules that meet the facts or objectives. There are two ways of reasoning: deductive (forward-chaining forward chain) and inductive method (backward-chaining reverse chain). Deduction from an initial fact, constantly applying rules to draw conclusions (or perform specified actions). The inductive rule is to start from the hypothesis and constantly look for the facts that conform to the hypothesis.

  2. Rule Engine

2.1 Business Rules
 
A business rule contains a set of conditions and operations performed under this condition, which represent a business logic for a business rule application. Business rules should typically be developed and modified by business analysts and policy managers, but some complex business rules can also be customized by technicians using object-oriented technical language or scripts. The rationale for business rules is to set one or more conditions that trigger one or more actions when these conditions are met.

2.2 Rule Engine

What is a rule engine? How does the rule engine execute the rules? This can be called "what" and "how" the question. What is the rule engine or is the current industry a more controversial issue, in the JSR-94 species are almost no definition. It can be argued that the question of "how" is fully defined and solved, and that the "what" problem is essentially solved. Perhaps this is another "egg or chicken first" philosophy debate. In the future, the definition and introduction of standard rule language and the formulation of relevant standards should give a full stop to such problems and controversies. This article, for the moment, describes what a rule engine is: A rule engine developed by the inference engine, a component embedded in an application that separates business decisions from application code, and uses predefined semantic modules to write business decisions. Accept data entry, interpret business rules, and make business decisions based on rules.

2.3 How the rule engine is used

Because the rule engine is a software component, only developers can use and control it through the program interface, and the Rules Engine's program interface contains at least the following APIs: loading and unloading the rule set APIs, API for data manipulation, API for engine execution. Developers using the rules engine in their programs basically follow the following 5 typical steps: Creates a rule engine object, loads a rule set or a replacement rule set to the engine, submits to the engine a collection of data objects that need to be processed by the rule set, executes the command engine, exports the engine execution results, and withdraws the processed data from the engine. After using the rule engine, many of the program code involved in business logic are largely superseded by these five typical steps.

An open business rule engine should be "embedded" anywhere in the application, and the rules engine at different locations can use different sets of rules to handle different data objects. In addition, there is no limit to the number of engines used.

2.4 Rule Engine architecture and inference

The rules engine's schema is shown in the following illustration:

Figure 2. Business Rules Engine architecture

The reasoning steps of the rule engine are as follows: A. Enter the initial data (fact) into the working memory (Working Memory). B. Use pattern Matcher to compare rules (rule) and data (fact) in rule libraries (rules repository). C. If there is a conflict between the execution rules (conflict), multiple rules are activated at the same time, and the conflicting rules are put into the conflict collection. D. Resolve conflicts and put the activated rules into agenda in order. E. Implementation of the rules in Agenda. Repeat steps b through e until you have finished executing all the rules in agenda.

Any rule engine needs to solve the efficiency problem of rule inference mechanism and rule condition matching well.

When the engine executes, the rule execution instance is executed according to the precedence order in the rule execution queue. Because the execution part of the rule may alter the data object of the workspace, it causes some rule execution instances in the queue to expire because of a conditional change, to be revoked from the queue, or to activate a rule that originally did not meet the condition. Generates a new rule execution instance into the queue. Thus, a "dynamic" rule execution chain is created, which forms the inference mechanism of rules. The "chained" response to this rule is entirely driven by data in the workspace.

The efficiency of the rule condition matching determines the performance of the engine, the engine needs to quickly test the data objects in the workspace, find the eligible rules from the loaded rule set, and generate the rule execution instance. Charles L. Forgy of the University of Carnegie Mellon, USA, in 1982, invented a rete algorithm that solves this problem well. At present, the world's top commercial business rules engine products are basically using the rete algorithm.

2.5 Algorithms of the rule engine
 
Most rule engine product algorithms are basically from Dr. The Rete algorithm and its variants, proposed by Charles Forgy in 1979, Rete algorithm is one of the most efficient forward-chaining inference algorithms, Drools project is an object-oriented Java implementation of Rete algorithm, The core idea of the Rete algorithm is to construct the matching tree dynamically according to the content, so as to reduce the computational load significantly.

   3. Java Rule Engine
 
The current mainstream rule engine components are based on the Java and C + + program language environment, there are many Java Rules Engine commercial products and open source project implementation, some of which have already supported JSR94, and some are working in this direction, listed below:

3.1 Java Rules Engine commercial products

Java Rule Engine Commercial products are mainly (Jess is not open source project, it can be used for academic research, but for commercial use charge):

3.2 Java Rule Engine open source project

The implementation of open source project mainly includes:

The Drools-drools rule engine uses the improved form of the Rete algorithm rete-ii algorithm. Internally, it uses the same concepts and methods as the Forgy algorithm, but adds a node type that can be seamlessly connected to an object-oriented language.

Mandarax is based on reverse inference (inductive method). Enables easier integration of multiple data sources. For example, database records can be easily integrated into the fact set (facts sets), reflection to integrate the functionality in the object model. JSR 94 is not currently supported

OFBiz Rule Engine-Support induction (backward chaining). The original code is based on the "Metsker Building in Java" of Steven John parsers and does not support JSR 94

Jlisa-jlisa is a powerful framework for building business rules, and it has the advantage of expanding the outstanding features of Lisp, more powerful than clips. These features are essential for the development of multiple-sample software. Support JSR 94

Other open source projects are implemented such as Algernon, Tyruba, JTP, Jeops, Infosapient, Rdfexpert, Jena 2, Euler, Jlog, Pellet OWL reasoner, Prova, Openrul ES, Sweetrules, JSHOP2 and so on.

   4, Java Rules Engine API (JSR-94)

4.1 Introduction

In the past, most of the rule engine development was not standardized and had its own API, which made it less flexible to interact with external programs. Switching to another product often means rewriting the application logic and API calls with a high cost. The lack of standards in the rule engine industry has become an important aspect of concern. The JSR (Java Rules Engine API), which was finalized in November 2003 and eventually released in August 2004, standardizes the implementation of the Java rules engine.

The Java Rules Engine API, defined by the Javax.rules package, is the standard enterprise API for accessing the rules engine. The Java Rules Engine API allows clients to interact with the rules engine products of different vendors in a uniform way, just like using JDBC to write independent vendor access to different database products. The Java Rules Engine API includes mechanisms for creating and managing rule sets, adding, deleting and modifying the mechanisms of objects in working memory, and initializing, resetting, and executing rules engines.

4.2 Introduction to Java Rules Engine API architecture

The Java Rule Engine API is divided into two main sections: the Runtime Client API (the Runtime client API) and the Rules management API (the Code Administration API).

  4.2.1 Rule Management API

The rule management APIs are defined in Javax.rules.admin, including Mount rules and the actions that correspond to the rules (the execution set execution sets) and the instantiation Rule engine. Rules can be loaded from external sources, such as uri,input streams, XML streams and readers, and so on. The Administration API also provides a mechanism for registering and canceling the execution set and maintaining the execution set. Using the admin package Definition rule helps control management of client access running rules by defining permissions on the execution set so that unauthorized users cannot access the managed rules.

The management API uses class Ruleserviceprovider to obtain an instance of the rule management (Ruleadministrator) interface. The rule management interface provides methods to register and unregister the execution set. Rule Manager (Ruleadministrator) Provides local and remote Ruleexecutionsetprovider. As mentioned earlier, Ruleexecutionsetprovider is responsible for creating the rule execution set. The rule execution set can be from XML streams, input streams. These data sources and their contents are aggregated and serialized and then transferred to a remote server running the rule engine. In most applications, the remote rule engine or remote rule data source is rare. To avoid network overhead in these situations, The API provides a local ruleexecutionsetprovider that can read data from a rule library running in the same JVM.

The rule execution set interface has the ability to obtain methods for the execution set of rules, as well as to retrieve all rule objects defined in the rule execution set. This allows customers to know the rule objects in the rule set and use them as they want.

  4.2.2 Runtime API

The runtime API is defined in the Javax.rules package, providing a class and method for the rule engine user to run the rule to obtain results. At run time, clients can access only those rules that are registered with the Rule Management API, and the runtime API helps users get a rule dialog and execute the rules in this conversation.

The runtime API provides a JDBC-like access approach to the vendor Rule Engine API. The Rule engine vendor provides access to the Run-time and management APIs implemented by the specific rule engine through class Ruleserviceprovider (class Ruleserviceprovider) The implementation of its rule engine is provided to the customer and the URL that ruleserviceprovider uniquely identifies the rule engine is obtained.

The recommended standard usage for URLs is to use an Internet domain name space such as "Com.mycompany.myrulesengine.rules.RuleServiceProvider", This will help access the uniqueness of the URL. Class Ruleserviceprovider implements the interfaces required for rule management and Run-time access. All Ruleserviceprovider must be registered with Ruleserviceprovidermanager to be accessed by the customer. The registration method is similar to the JDBC API DriverManager and driver.

The Run-time interface is a critical part of the Run-time API. The Run-time interface provides a method for creating a rule session (Rulesession), which is used to run rules as described earlier. The runtime API also provides access to all rule execution sets that have been registered with service provider ( ruleexecutionsets). The rule session interface defines the type of session that the customer uses, and the customer can choose to use stateful or stateless sessions in the way they run the rules.

A stateless session works like a stateless session bean. A client can send a single input object or a list of objects to get the output object. Stateful sessions are useful when a client needs a dedicated session with the Rule engine. The object entered is passed through the AddObject () Method can be added to the conversation. Multiple objects can be added to the same session. Existing objects in the dialog can be updated by using the Updateobject () method. Objects in the session are not lost as long as the session between the customer and the rule engine persists.

The Ruleexecutionsetmetadata interface is provided to the customer to find the metadata (metadata) for the rule execution set. Metadata is provided to the user through the rule session interface (Rulesession Interface).

Code snippets that use the Run-time Runtime API are as follows:

  Ruleserviceprovider Ruleprovider = Ruleserviceprovidermanager.getruleserviceprovider
("Com.mycompany.myrulesengine.rules.") Ruleserviceprovider ");
Ruleruntime ruleruntime = Ruleprovider.getruleruntime ();

NULL, Ruleruntime.stteless_session_type);
List inputrules = new ArrayList ();
Inputrules.add (New String ("Rule 1"));
Inputrules.add (New Integer (1));
List resultrules = Rulesession.executerules (inputrules);

4.3 Java Rule Engine API security issues
  
The Rules Engine API separates the management APIs from the Run-time APIs, providing better granular security control for these packages. The Rules Engine API does not provide a clear security mechanism that can be used in conjunction with the standard security APIs defined in the Java EE specification. Security can be provided by the following mechanisms, such as Authentication and Authorization Service (JAAS), the Java Cryptography Extension (JCE), Java Secure Socket extension (JSSE), or other custom security Api.jaas can be used to define permission permissions for the rule execution set, so that only authorized users can access it.

4.4 Exceptions and logs

The Rules Engine API defines the javax.rules.RuleException as the root class for the exception hierarchy of the rule engine. All other exceptions are inherited from this root class. Exceptions defined in the rule engine are controlled exceptions (checked exceptions). So the task of catching the exception is given to the rules engine. The Rules Engine API does not provide a clear logging mechanism, but it recommends that the Java Logging API be used for the Rules Engine API.

Summary of 4.5 JSR 94

JSR 94 provides a common standard API for the rule engine, providing guidelines for implementing the Rule management APIs and Run-time APIs, providing no guidance on how rules and actions should be defined and what languages should be used to define rules, or providing technical guidance on how rules engines read and evaluate rules. The JSR 94 specification leaves the problem to the manufacturer of the rules engine. In the next section, I'll briefly introduce the rules language.

  5. Rules language

The language used to create rules and actions is not in JSR 94. The rule language is an important part of the Rules Engine application, and all business rules must be defined in some language and stored in the rule execution set, so that the rules engine can load and process them.

Because there is no public specification for how rules are defined, most popular rule engines on the market have their own rules language, and there are many rules languages that are currently being applied, so you might need to transform the rule definition when porting applications to other Java Rule engine implementations. such as the conversion of drools private DRL rule language into standard ruleml,jess rule language into ruleml. This work is typically done by the XSLT converter.

Details of the rules language are not detailed here, and the name and its web address are listed below:

Rule Markup language (RULEML)
http://www.ruleml.org/
http://xml.coverpages.org/srml.html Business Rules Markup Language (BRML)
http://xml.coverpages.org/brml.html swrl:a semantic Web rule Language combining OWL and RULEML
http://www.daml.org/2003/11/swrl/

The use of multiple rule languages makes the compatibility between different rule engine implementations a problem. The common rules Engine API may mitigate problems between different manufacturers ' APIs, However, the lack of common rule language will still hinder interoperability between different rule engine implementations. Although the industry has made some efforts in proposing common rule languages, such as the emergence of RULEML,SRML, it still has a long way to go before the common standards agreed by most of the rules engine manufacturers.

  6, Java Rules Engine API usage Example

6.1 Setting the Rule engine

The administrative activity phase of the Java Rule Engine begins by looking for an appropriate Javax.rules.RuleServiceProvider object, which is the portal to the application access rule engine. In the Java EE environment, you may be able to 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);

With the Ruleserviceprovider object, you can get a Javax.rules.admin.RuleAdministrator class. From the Ruleadministrator class, you can get a ruleexecutionsetprovider from the class name to know that it is used to create Javax.rules.RuleExecutionSets objects. Ruleexecutionset is basically a collection of rules that are loaded into memory and ready to execute.

The package javax.rules.admin includes two different ruleexecutionsetprovider classes. The Ruleexecutionsetprovider class itself includes methods for creating ruleexecutionsets from the serializable object, so in the case where the rule engine is located on a remote server, You can still use the Ruleexecutionsetprovider class, and the constructor parameters can be passed by RMI. Another class is Localruleexecutionsetprovider, which contains other methods for creating ruleexectionsets from serializable resources such as java.io.reader-local files. Assuming you have a Ruleserviceprovider object, you can create a Ruleexectionset object from a local file Rules.xml file. As shown in the following code:

  Ruleadministrator admin = serviceprovider.getruleadministrator ();
HashMap properties = new HashMap ();
Properties.put ("name", "My Rules");

FileReader reader = new FileReader ("Rules.xml");
Ruleexecutionset ruleSet = null;
try {

RuleSet = Lresp.createruleexecutionset (reader, properties);
finally {
Reader.close ();
}

Next, you can use the Ruleadministrator register to get the Ruleexecutionset and assign it a name. At run time, you can create a rulesession with the same name, and the rulesession uses this named Ruleexecutionset. See the following usage: Admin.registerruleexecutionset ("Rules", RuleSet, properties);

6.2 Executing the Rule engine

In the run-time phase, you can see a Rulesession object. The Rulesession object is essentially a rule engine instance loaded with a specific set of rules. You get a Ruleruntime object from Ruleserviceprovider, and then you get Rulesession object from Javax.rules.RuleRuntime.

Rulesession are divided into two categories: stateful and stateless. They have different functions. Statefulrulesession's working memory can save state during multiple method invocations. You can add multiple objects to the working memory during multiple method calls, then execute the engine, and then add more objects and execute the engine again. Instead, the Statelessrulesession class is not saved, and in order to perform its Executerules method, you must provide all the initial data for the working memory, execute the rule engine, and get a list of the 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, execute the rule, and then get all the content in the working Memory, Returned as a Java.util.List object. Finally, we call the release method to clean the rulesession:

  
Statefulrulesession session = (statefulrulesession) runtime.createrulesession ("rules",
Properties,ruleruntime.stateful_session_type);

Session.addobject ("A string");


Session.release ();

   7. Concluding remarks

The Java Rules Engine API (JSR-94) allows client programs to interact with the rules engine products of different vendors in a uniform way and to some extent provides standardized specifications to the rules engine manufacturer. But it has almost no definition of what the rule engine is, and of course it doesn't go deep into how the rules are built and manipulated, the utility of rule calls, and the binding of rules to the Java language. And JSR-94 in the support of the Java EE is also insufficient. The standardization of regular language, the further enrichment and deepening of JSR-94, is still to be studied.

Related Article

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.