Java rules Engine drools7.0.0.final rules Engine tutorial 4th 4.4 constraints (part of pattern)

Source: Internet
Author: User

4.4.3 constraints (part of pattern)

We have already introduced the conditional constraint in the pattern position, then what is the conditional constraint? In simple terms, an expression that returns TRUE or false, such as the following 5 less than 6, is a constraint.

Person (5 < 6)
View Code

Essentially, it is an enhanced version of a Java expression (such as property access), and it has some small differences, such as the language difference between the Equals method and = =. Let's take a closer look.

Accessing the properties in JavaBean

Any property in a JavaBean can be accessed, but the corresponding property is provided with a getter method or Isproperty method. Like what:

Person (age = = )//  has the same effect as above person (getage () = = 50)
View Code

Drools uses Java standard class checking, so it follows the Java standard. Also, nested properties are supported, such as:

Person (Address.housenumber = = )//  same person as above (GetAddress (). Gethousenumber () = = 50)
View Code

Using nested properties in the case of stateful sessions requires that the value of the property may be modified elsewhere. Either think of them as immutable when any one parent reference is inserted into the working memory. Or, if you want to modify a nested property value, you should update all external fact tags. In the above example, when the Housenumber property value changes, any person with address will need to be tagged for updates.

Java expressions

In the constraint of pattern, any Java expression that returns the result as a Boolean type can be returned. Of course, Java expressions can also be used in conjunction with enhanced expressions, such as property access. You can change the calculation priority by using parentheses, such as in any logical or mathematical expression.

Person (age > + && (age% 10 = = 0))
View Code

You can also perform operations calculations directly using the tool methods provided by Java:

Person (math.round (weight/height * height)) < 25.0)
View Code

In the process of use, it is important to note that the method executed in LHS can only be read-only and cannot change the value of the fact object during the execution of the method, otherwise it will affect the correct execution of the rule.

// do not update the fact object like this in the process of comparison
View Code

In addition, the status of the fact object should not be changed every time it is called, in addition to being updated in working memory.

// don't do this .
View Code

Standard Java operator Precedence is also applicable, see the following list of operator precedence levels. All operators have standard java semantics, except = = and! = Their null security is equivalent to the effect of placing a constant string before calling the Equals method when comparing two strings in Java.

Constraint-type conversions are performed during the comparison of constraints, such as when the string "10" is passed into the data calculation, and can be successfully converted to the Number 10 for calculation. However, if the value passed in at this time cannot be converted, such as "Ten", then an exception will be thrown.

Comma delimiter

Commas can group constraints, which function as "and".

// Person is older than 50 and weighs more than Person (age > Weight > 80)
View Code

Although "&&" and "," have the same functionality, they have different priorities. "&&" takes precedence over "| |", "&&" and "| |" Also takes precedence over ",". However, it is recommended that the "," delimiter be preferred, as it is more conducive to reading comprehension and engine optimization operations. At the same time, the comma delimiter cannot be mixed with other operators, such as:

// Compile Error // Use this method instead of Person ((Age > && weight >) | | height > 2)
View CodeBinding variables

A property can be bound to a variable:

// 2 person has the same age property value // binding // Constraint Expression
View Code

The prefix $ is a general convention that allows you to differentiate variables and attributes in complex rules. For backwards compatibility, it is possible (but not recommended) to mix constraint bindings and constraint expressions.

// It is not recommended to write Person ($age: Age * 2 < )//  recommended (detach binding and constraint expression)person (age * 2 <, $age: Age)
View Code

Using the operator "= =" to bind variables, Drools uses a hash index to improve execution performance.

Inner class group Access

Generally, when we access multiple properties of an inner class, we have the following wording:

Person (name = = "Mark", address.city = = "London", address.country = = "UK")
View Code

The group access provided by Drools is more convenient to use:

Person (name = = "Mark", address. (City = = "London", country = = "UK")1
View Code

Note the prefix '. ' is required to differentiate between nested object constraints and method calls.

Internal casts

When using an inner class, it is often necessary to convert it to a parent class, which can be cast by "#" in the rule:

Person (name = = "Mark", Address#longaddress.country = = "UK")
View Code

The above example casts the address to longaddress, which makes the getter method available. If the conversion cannot be cast, the result of the expression evaluation is false. The cast also supports full path notation:

Person (name = = "Mark", Address#org.domain.longaddress.country = = "UK")
View Code

Multiple internal conversion Syntax:

Person (name = = "Mark", Address#longaddress.country#detailedcountry.population > 10000000 )1
View Code

It can also be judged using the instanceof operator, which is then further used to compare the property.

instanceof longaddress, Address.country = = "UK")
View CodeDate characters

In addition to supporting Java standard characters, the rule syntax also supports date characters. Drools default supported date format is "dd-mmm-yyyy", you can change the default date format by setting the value of the system variable "Drools.dateformat".

Cheese (Bestbefore < "27-oct-2009")
View CodeAccess to list and map

Access list:

// and Childlist (0). Getage () = = 18 effect is the same Person (childlist[0].age = = 18)
View Code

Access Map by Key:

// Same as Credentialmap.get ("JSmith"). IsValid () Person (credentialmap["JSmith"].valid)
View Code&& | |

Constraint expressions can be obtained by && and | | For comparison, the usage here is similar to standard Java, and when combined, it can be prioritized by parentheses.

Person (at age > 40 && < max ) person ((> && <) The person (the Age of the () | | (> && < (>) && < | | | location = = "London")
View CodeDRL Special Operators

"<? The > >= "operator is used for property comparisons by default sorting, such as date attributes using less than sign can be sorted by date, and sorted alphabetically when using a comparison of string strings. This operator applies only to comparable properties.

Person (FirstName << $otherBirthDate)
View Code

“!.” Provides an operation for a default null check. When this operator is used, the current object is checked for null, if it is not NULL, its method is called, or its properties are determined. Once the current operand is null, the result is equivalent to false.

Person ($streetName: address!. Street)//  above is equivalent to null, $streetName: Address.street)
View Code

The matches operator can use Java regular expressions to match strings, usually by matching strings, but also supporting the way that variable values are the correct expression. This operator applies only to string properties. If the property value is null, the result of the match is always false.

Cheese (Type matches "(Buffalo)? \\s*mozzarella")
View Code

The not matches method is the same as matches, except that the returned result is the opposite.

Cheese (Type not matches "(Buffalo)? \\s*mozzarella")
View Code

The contains operator determines whether a collection property or element contains the specified string or variable value. Applies only to collection properties. It can also be used to override String.contains () to check for constraints. The use of not contains is the same, and the result is reversed.

// contain string // include variable  "Tilto""Jr" This contains "foo")
View Code

MemberOf is used to check whether a property value is a collection, and the representation of this collection must be a variable. Not memberof use the same method, the result is reversed.

Cheesecounter (cheese memberOf $matureCheeses)
View Code

The effect of Soundslike is similar to matches, but it is used to check whether a string is pronounced similar to a specified character (in English).

// Match "Fubar" or "Foobar" Cheese (name Soundslike ' Foobar ')
View Code

The STR action is used to compare whether a string begins or ends with a specified string, and there is a length that can be used to compare strings.

Message (Routingvalue str[startswith] "R1""R2"17)
View Code

In and Notin are used to match whether a set of data contains one or more matching strings, using a method similar to that used in the database. The data to be matched can be a string, a variable.

"Stilton", "Cheddar", $cheese))
View CodeOperator Precedence

type of Operation operator Notes
(Nested/NULL security) property access .!. Non-standard Java semantics
List/map Access [ ] Non-standard Java semantics
Constraint binding : Non-standard Java semantics
Multiplication */%
Add and Subtract +-
Shift <<>>>>>
Relationship <>?>=instanceof
such as ==!= Standard Java semantics are not used, and some semantics are equivalent to equals.
Non-short-circuit and &
Non-short-circuit XOR ^
Non-shorted contains or |
Logic and &&
Logical OR ||
Ternary operators ? :
Comma-delimited, equivalent to and , Non-standard Java semantics

Java rules Engine drools7.0.0.final rules Engine tutorial 4th 4.4 constraints (part of pattern)

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.