Develop your Addons

We will see here how to develop your own Addon, through a simple but realistic example. The case is: an e-commerce website wants, under some conditions, to generate a discount code for a client. This code can be a fixed amount or a percentage reduction.

To generate the code during the rule engine execution, the best solution is to develop a specific Addon, which is a fast and simple operation as all the tools are provided to ease the implementation.

In this example, the Addon will be a reading Accessor (IReadAccessor), meaning a component allowing to retrieve data.

It will be configured with 4 parameters:

  • The client ID to which the code is attached
  • A type (percentage or amount)
  • A value
  • An optional validity period

Let’s start by creating the implementation class. To achieve this, it’s possible to directly implement the interface or to extend the abstract class AbstractReadAccessor, providing some code components allowing to simplify the final code.

The code below shows the class skeleton, with configuration fields, associated getters / setters and the simpliest methods code.

This first step completed, it’s now time to write the 4 last methods code (commented as TODO):

  • Two compilation methods. The one handling Collections is not relevant in this case, it will throw an Exception. The compilation for unitary Objects will validate the configuration data.
  • The execution method. It will call a Helper allowing to generate the code, potentially reuseable by other application modules.
  • The method evaluating execution cost, internally used to opitmize coll ordering.

It’s worth mentionning the presence of error message dedicated to the Addon in the compilation method. These messages must be declared in a Java class and implement the MessageCode interface.

Then also the internationalization file, named here

Also, the test Helper for the example called in the “get” method:

Finally, don’t forget to declare this Addon so that it will be loaded at launch time. To achieve this, it’s necessary to create a file named “mrules-addons.xml”, directly accessible in the CLASSPATH and declaring the Addon. The priority attribute allows to order these files loading, to be able to override declarations (especially concerning data conversion formats).

A simple main launcher allows to test this example:

As a conclusion, we have seen here the steps necessary for creating a specific Addon, in order to adapt the MRules library to the business needs of the application it integrates. Using this Addon system, simple to set up, all possibilities are opened to developers for easily and quickly integrate all kings of behaviors.

The full source code of the example can be downloaded here.