Velocity A template engine or a rule engine or Both

Source: Internet
Author: User
Tags date integer key modify resource



March 2005
Discussion


Velocity:a template engine or A rule engine or Both?

Most of the developers must is familiar with Velocity as a great open source template engine and I don ' t do I need to s Ay much about its uses and features as a template engine. This paper compiles it features as a rule engine.

I have been working with Java for the past 6 years and recently, I got a opportunity to design and develop a entitlement Application.

An entitlement was the result of the execution of a formula, or rule this specifies what must be considered when deciding W Hether a given user has rights to manipulate or use a given resource (or object). This is composed of one or more conditions that might is evaluated with application the context specific data. In addition, a rule of evaluation may, the than simple yes/no answers and contain additional information that would be required by a application to now perform the requested access to the resource. These are called obligations. Therefore an entitlement service can is used both as a rule evaluator and a privilege data service.

In the simplest form an entitlement Service performs standard authorization calls. For example, can a user perform a simple action against a named resource? In it more complicated form a entitlement may is a rule on how an object such as a financial transaction may be Manipula Ted. In this rule the specific parameters of the transaction is compared against set limits or current financial data. The business logic of May is a representation.

There are four types of entitlement:

coarse-grained entitlement-the control of access to broad categories of, for example, a entire application, a N entire subsystem, or access to specific Web pages.

Fine-grained entitlement-the granting or withholding of individual resources like buttons, links, menu choices on a page or screens, or functions within a program.

Transactional Entitlement-an entitlement that checks privilege to manipulate a resource by examining very specific param Eters about a ' transaction ' upon that resource. The characteristics of or relationships between these parameters could are expressed numerically (",", =, ...), using Date and time information, or even as part of a formula (*,%,/,-, +).

Dynamic Entitlement-where A parameter of a ' transaction ' represents information that must is calculated or retrieved fro M an external source. This information may is retrieved by a call to a application specific service.

So according to the requirements, this application has to have:
Some logic to return the stored data (Users, User Groups, resources, Resource Groups, Permissions etc.) based on Some Filte Rs. For example return me all the users who have a access on this resource. Logic to check the permission. Permissions are Boolean in nature and don ' t require any complex logic to process. Although, permission are very simple they are quiet powerful for building a entitlement application and cater to most of The cases of coarse-grained and fine-grained entitlements. A rule based engine to handle transactional and Dynamic entitlements.
Now we'll directly focus on the uses of Velocity as a rule engine as this article are not about developing a entitlemen T application.

So, instead of developing me own rule engine I started looking the to find out a around rule decent this can engine my Requirements. And I began to explore the rule engines like:
JEL (Http://galaxy.fzu.cz/JEL), Bean Shell (http://www.beanshell.org/home.html), EL (http://java.sun.com/j2ee/1.4/ docs/tutorial/doc/jspintro7.html)
And many more, especially of the ones with open sources because I management did not want to spend too very much for this AP Plication.

What I is looking for is a engine with the following features:
Ease of use in development. Should reduce my development time. Easy and flexible in terms of configuration. It should have very easy and familiar language to write rules especially for a non-technical admin to maintain. Easily extendable. Clear separation between admin (rule author) and developer. Tested and reliable. Great community support. Nobody is perfect and everybody needs help:)
But I couldn ' t find anything good enough out there. Suddenly, Velocity got my attention. I have already used Velocity to generate the My GUI. However, this time, I is looking at it and a different point of view. I am compiling its features in terms's a rule engine and it seemed to me a considerable fit for the new framework. Then it became a perfect fit when I realized its uses of toolbox as. The Toolbox concept provides the "power" to "rule a author to access any EIS or application (almost anything) at runtime and With a complete transparency to the author.

Now lets down a real life example and use Velocity as Rule engine. Before we go ahead, lets configure Velocity.

Velocity can be used as a servlet in a Web application or as a utility in a standalone application. In our case, we'll use it as a standalone application. Now, as a standalone application, your can use it in two ways. One is singleton another is separate runtime instance. I used it as Singleton. Following is the code sample:

public class Ruleenginevelocityimpl implements Ruleengine{public ruleenginevelocityimpl{try {//Initialize Velocity.Velocity.init (); }catch (Exception e) {//do something.}} public string Execute (String RuleId, Map params) {//Get the velocity template from some storage. String template = Getfromsomewhere (RuleId);//Create a context object. Velocitycontext context = new Velocitycontext (params);//Get a template as stream. StringWriter writer = new StringWriter (); StringReader reader = new StringReader (template);/ask Velocity to evaluate it.boolean result = Velocity.evaluate (cont Ext, writer, RuleId, reader); String strresult = null; if (result) {strresult = Writer.getbuffer (). toString ();} return strresult;} public static void Main (string[] args) {//Add the variable and their values which are being referred in// AP params = new HashMap ();p arams.put ("AnyKey", anyobject);//Initialize rule Engine and execute. RuleEngine engine= new Ruleenginevelocityimpl (); STring result = Engine.execute ("Myrule", params); SYSTEM.OUT.PRINTLN ("Result:" + result);}

Now, we'll write a rule to check a-limit for some user. A VTL Template/rule For this may look like this:

#if ($creditLimit > 1000) over limit. You can ' t complete this transaction.# #OR just a Boolean value like false## #else #set ($creditLimit = 1000-$creditLimit Now, your balance are ${creditlimit}.# #OR just a Boolean value like true## #end

You can store the "rules in a" or "a" database or in any another data storage. In our case, I stored the rules/templates in a RDBMS and I provided the Admin GUI to maintain them. Lets assume database table, "rule" with two columns, RuleId and Template. I insert a rule with RuleId "Chk_credit_limit".

Now, lets modify the "Ruleenginevelocityimpl" class in the Main method.

public static void Main (string[] args) {Map params = new HashMap ();p arams.put ("Creditlimit", new Integer);//Initial Ize rule Engine and execute the rule. RuleEngine engine= new Ruleenginevelocityimpl (); String result = Engine.execute ("Chk_credit_limit", params); SYSTEM.OUT.PRINTLN ("Result:" + result);}

The output would be:

Now, your balance is 800.

doesn ' t it sounds very familiar and easy? It has to be. It is velocity, dude!!!

Now, lets to the power of toolbox concept.

Naturally, velocity only supports integer but Velocity tools project adds "to" to "do" any kind of Math, Da Te processing and formatting which you-need to use for the rule engine.

Since a toolbox is extendable and it's very easy to write a tool (almost any class with public method can be used as tool) You are have unlimited opportunities to write N numbers of tools corresponding to your application/requirements context and a ll'll be available to rule author for writing the Smart rules. For example, lets say of airline company has the up with a come the rule for year and that business:

If booking date is in a special day list then get the discounted rate, otherwise use the normal fare.

Lets assume this discounted rate and special day list are stored in some database and both are being to maintained by some ER application. This special rate are valid only for year, and it may or can, completely eliminated in year 2006. In such case it'll is wise to build the application to cater to the above business requirements and change it later.

So lets to the problem with the rules. Before we write a rule we need two values available at a runtime. One is a special day list and the other is the discount rate. Lets write a Tool class (COM. Ratehelper) Similar to what we have already in Velocity Tools:math, Date etc. The signature of this class would is as follows:

Public Double getrate ();p ublic boolean isinspecialdaylist (String day);

The any class has the can behave like a tool in Velocity. That ' s the magic of introspection:)

After writing this class lets add it as a tool in Velocity engine. We already have a beauty called "Xmltoolboxmanager" to add N number of the tools in Velocity automatically. We just need to specify our tools in an XML file called Toolbox.xml.

<toolbox><tool> <key> ratehelper </key> <scope>application</scope> <class >com. Ratehelper</class></tool></toolbox

Now, lets modify we Ruleenginevelocityimpl class to load this toolbox by adding the below line in the constructor after I Nitializing Velocity.

Xmltoolboxmanager Toolboxmanager = new Xmltoolboxmanager (); Toolboxmanager.load (This.getclass (). GetClassLoader (). getResourceAsStream ("Toolbox.xml")); toolboxcontext = Toolboxmanager.gettoolboxcontext (null);

And now replace the below-in-Execute method:

Velocitycontext context = new Velocitycontext (params);

With the This line:

Velocitycontext context = new Velocitycontext (toolboxcontext, params);

This is the context chaining. Please refer the Apache documentation for more information on it.

Okay, we are all set. Lets write the business rule (using our custom tool) and store it in our we database with RuleId "Get_price"

#if ($rateHelper. Isinspecialdaylist ($day)) $rateHelper. Getrate () #else 2500 # #Regular price## #end

Now, lets modify's main method is again to execute our new rule.

public static void Main (string[] args) {Map params = new HashMap ();p arams.put ("Day", "02/28/05");/Initialize rule Engine and execute the rule. RuleEngine engine= new Ruleenginevelocityimpl (); String result = Engine.execute ("Get_price", params); SYSTEM.OUT.PRINTLN ("Result:" + result);}

The output would be (if 02/28/05 isn't in special day list): 2500

ISN ' t it easy and powerful?

In addition to toolbox, I associated properties (Key-value pair) to objects like user, user Group, Resource, Resource Grou P which I made available to the rule author. This gives the author more flexibility to write smarts rules. For example, there are a user group in a where some of the users can only ' buy ' the product and some of them can on Ly "sell" the product and the rest of them can do both. We can associate a property called "Actiondirection" with every user of the group and the possible values for the Would be like "buy", "SELL" and "BOTH". A rule author can use it freely the user actions that are in the he rules to distinguish among.

Velocity was intensely written as a template engine and it ' s one of the pioneers in this area but you can-you-it is also A great rule engine. Combination of properties, toolbox and parameters makes it more powerful and perfectly as this task. And most importantly, somebody has used it successfully as rule engine.
Reference:
1) http://jakarta.apache.org/velocity/index.html
To:
-marc and Norm who brought me to this project.

-margaret for her editing. :)

origional link:velocity:a template engine or A rule engine or Both?


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.