8.7. Functions in a Rule

Functions are a way to put semantic code in a rule source file, as opposed to in normal Java classes. The main advantage of using functions in a rule is that you can keep the logic all in one place. You can change the functions as needed.
Functions are most useful for invoking actions on the consequence (then) part of a rule, especially if that particular action is used repeatedly.
A typical function declaration looks like the following:
function String hello(String name) {
    return "Hello "+name+"!";
}

Note

Note that the function keyword is used, even though it's not technically part of Java. Parameters to the function are defined as for a method. You don't have to have parameters if they are not needed. The return type is defined just like in a regular method.

8.7.1. Function Declaration with Static Method Example

This example of a function declaration shows the static method in a helper class (Foo.hello(). JBoss BRMS supports the use of function imports, so the following code is all you would need to enter the following:
import function my.package.Foo.hello

8.7.2. Calling a Function Declaration Example

Irrespective of the way the function is defined or imported, you use a function by calling it by its name, in the consequence or inside a semantic code block. This is shown below:
rule "using a static function"
when 
    eval( true )
then
    System.out.println( hello( "Bob" ) );
end

8.7.3. Type Declarations

Type declarations have two main goals in the rules engine: to allow the declaration of new types, and to allow the declaration of metadata for types.

Table 8.3. Type Declaration Roles

Role Description
Declaring new types
JBoss BRMS uses plain Java objects as facts out of the box. However, if you wish to define the model directly to the rules engine, you can do so by declaring a new type. You can also declare a new type when there is a domain model already built and you want to complement this model with additional entities that are used mainly during the reasoning process.
Declaring metadata
Facts may have meta information associated to them. Examples of meta information include any kind of data that is not represented by the fact attributes and is consistent among all instances of that fact type. This meta information may be queried at runtime by the engine and used in the reasoning process.

8.7.4. Declaring New Types

To declare a new type, the keyword declare is used, followed by the list of fields and the keyword end. A new fact must have a list of fields, otherwise the engine will look for an existing fact class in the classpath and raise an error if not found.

8.7.5. Declaring a New Fact Type Example

In this example, a new fact type called Address is used. This fact type will have three attributes: number, streetName and city. Each attribute has a type that can be any valid Java type, including any other class created by the user or other fact types previously declared:
declare Address
   number : int
   streetName : String
   city : String
end

8.7.6. Declaring a New Fact Type Additional Example

This fact type declaration uses a Person example. dateOfBirth is of the type java.util.Date (from the Java API) and address is of the fact type Address.
declare Person
    name : String
    dateOfBirth : java.util.Date
    address : Address
end

8.7.7. Using Import Example

This example illustrates how to use the import feature to avoid he need to use fully qualified class names:
import java.util.Date

declare Person
    name : String
    dateOfBirth : Date
    address : Address
end

8.7.8. Generated Java Classes

When you declare a new fact type, JBoss BRMS generates bytecode that implements a Java class representing the fact type. The generated Java class is a one-to-one Java Bean mapping of the type definition.

8.7.9. Generated Java Class Example

This is an example of a generated Java class using the Person fact type:
public class Person implements Serializable {
    private String name;
    private java.util.Date dateOfBirth;
    private Address address;

    // empty constructor
    public Person() {...}

    // constructor with all fields 
    public Person( String name, Date dateOfBirth, Address address ) {...}

    // if keys are defined, constructor with keys
    public Person( ...keys... ) {...}

    // getters and setters
    // equals/hashCode
    // toString
}

8.7.10. Using the Declared Types in Rules Example

Since the generated class is a simple Java class, it can be used transparently in the rules like any other fact:
rule "Using a declared Type"
when 
    $p : Person( name == "Bob" )
then
    // Insert Mark, who is Bob's manager.
    Person mark = new Person();
    mark.setName("Mark");
    insert( mark );
end

8.7.11. Declaring Metadata

Metadata may be assigned to several different constructions in JBoss BRMS, such as fact types, fact attributes and rules. JBoss BRMS uses the at sign ('@') to introduce metadata and it always uses the form:
@metadata_key( metadata_value )
The parenthesized metadata_value is optional.

8.7.12. Working with Metadata Attributes

JBoss BRMS allows the declaration of any arbitrary metadata attribute. Some have special meaning to the engine, while others are available for querying at runtime. JBoss BRMS allows the declaration of metadata both for fact types and for fact attributes. Any metadata that is declared before the attributes of a fact type are assigned to the fact type, while metadata declared after an attribute are assigned to that particular attribute.

8.7.13. Declaring a Metadata Attribute with Fact Types Example

This is an example of declaring metadata attributes for fact types and attributes. There are two metadata items declared for the fact type (@author and @dateOfCreation) and two more defined for the name attribute (@key and @maxLength). The @key metadata has no required value, and so the parentheses and the value were omitted:
import java.util.Date

declare Person
    @author( Bob )
    @dateOfCreation( 01-Feb-2009 )

    name : String @key @maxLength( 30 )
    dateOfBirth : Date 
    address : Address
end

8.7.14. The @position Attribute

The @position attribute can be used to declare the position of a field, overriding the default declared order. This is used for positional constraints in patterns.

8.7.15. @position Example

This is what the @position attribute looks like in use:
declare Cheese
    name : String @position(1)
    shop : String @position(2)
    price : int @position(0)
end

8.7.16. Predefined Class Level Annotations

Table 8.4. Predefined Class Level Annotations

Annotation Description
@role( <fact | event> )
This attribute can be used to assign roles to facts and events.
@typesafe( <boolean> )
By default, all type declarations are compiled with type safety enabled. @typesafe( false ) provides a means to override this behavior by permitting a fall-back, to type unsafe evaluation where all constraints are generated as MVEL constraints and executed dynamically. This is useful when dealing with collections that do not have any generics or mixed type collections.
@timestamp( <attribute name> )
Creates a timestamp.
@duration( <attribute name> )
Sets a duration for the implementation of an attribute.
@expires( <time interval> )
Allows you to define when the attribute should expire.
@propertyChangeSupport
Facts that implement support for property changes as defined in the Javabean spec can now be annotated so that the engine register itself to listen for changes on fact properties. .
@propertyReactive Makes the type property reactive.

8.7.17. @key Attribute Functions

Declaring an attribute as a key attribute has two major effects on generated types:
  1. The attribute is used as a key identifier for the type, and thus the generated class implements the equals() and hashCode() methods taking the attribute into account when comparing instances of this type.
  2. JBoss BRMS generates a constructor using all the key attributes as parameters.

8.7.18. @key Declaration Example

This is an example of @key declarations for a type. JBoss BRMS generates equals() and hashCode() methods that checks the firstName and lastName attributes to determine if two instances of Person are equal to each other. It does not check the age attribute. It also generates a constructor taking firstName and lastName as parameters:
declare Person
    firstName : String @key
    lastName : String @key
    age : int
end

8.7.19. Creating an Instance with the Key Constructor Example

This is what creating an instance using the key constructor looks like:
Person person = new Person( "John", "Doe" );

8.7.20. Positional Arguments

Patterns support positional arguments on type declarations and are defined by the @position attribute.
Positional arguments are when you don't need to specify the field name, as the position maps to a known named field. (That is, Person( name == "mark" ) can be rewritten as Person( "mark"; ).) The semicolon ';' is important so that the engine knows that everything before it is a positional argument. You can mix positional and named arguments on a pattern by using the semicolon ';' to separate them. Any variables used in a positional that have not yet been bound will be bound to the field that maps to that position.

8.7.21. Positional Argument Example

Observe the example below:
declare Cheese
    name : String
    shop : String
    price : int
end
The default order is the declared order, but this can be overridden using @position
declare Cheese
    name : String @position(1)
    shop : String @position(2)
    price : int @position(0)
end

8.7.22. The @Position Annotation

The @Position annotation can be used to annotate original pojos on the classpath. Currently only fields on classes can be annotated. Inheritance of classes is supported, but not interfaces of methods.

8.7.23. Example Patterns

These example patterns have two constraints and a binding. The semicolon ';' is used to differentiate the positional section from the named argument section. Variables and literals and expressions using just literals are supported in positional arguments, but not variables:
Cheese( "stilton", "Cheese Shop", p; )
Cheese( "stilton", "Cheese Shop"; p : price )
Cheese( "stilton"; shop == "Cheese Shop", p : price )
Cheese( name == "stilton"; shop == "Cheese Shop", p : price )