Guided Rules with the Guvnor

August 24, 2009

Uncategorized

«»

Guided Rules with the Guvnor

In the last chapter we took a tour with the Guvnor and used it to write our first
business rule, and printed out a traditional ‘Hello World’ message. Although this
rule is a major step forward for us, we’re not really using the full power of the Drools
rule engine. In this chapter, we’re going to stay with the Guvnor rule editor, and use
it to write some more sophisticated rules. In particular, we’re going to:

  • Show how to put information into and out of our rules
  • Build a fact model to hold this information
  • Import our newly built model into Guvnor
  • Create guided rules using this fact model
  • Run and test our new fact-based rules

Passing information in and out

The main reason for the simplicity of our Hello World example was that it neither
took in any information, nor passed any information out—the rule always fired, and
said the same thing. In real life, we need to pass information between our rules and
the rest of the system. You may remember that in our tour of the Guvnor, we came
across models that solved this problem of ‘How do we get information into and out
of the rules?’.


	If you're familiar with Java, models are just normal JavaBeans deployed
	into Guvnor/JBoss rules in a JAR (ZIP-like) file; nothing more, nothing
	less. In fact, a lot of the time you can use the JavaBeans that already exist
	in your system.

Here’s a quick reminder of the spreadsheet that we used as an example in the
last chapter:

If we want to duplicate this in our model/JavaBean, we would need places to hold
four key bits of sales-related information.

  • Customer Name: String (that is, a bit of text)
  • Sales: Number
  • Date of Sale: Date
  • Chocolate Only Customer: Boolean (that is, a Y/N type field)

W e also need a description for this group of information that is useful when we have
many spreadsheets/models in our system (similar to the way this spreadsheet tab is
called Sales)


	Note that one JavaBean (model) is equal to one line in the spreadsheet.
	Because we can have multiple copies of JavaBeans in memory, we are able
	to represent the many lines of information that we have in a spreadsheet.
	Later, we'll loop and add 10, 100, or 1000 lines (that is, JavaBeans) of
	information into Drools (for as many lines as we need). As we loop,
	adding them one at a time, the various rules will fire as a match is made.

Building the fact model

W e will now build this model in Java using the Eclipse editor we installed in Chapter
2. Don’t worry if this is your first bit of Java; we’re going to do it step-by-step.

  1. Open the Eclipse/JBoss IDE editor that you installed earlier. If prompted, use
    the default workspace. (Unless you’ve a good reason to put it somewhere else.)
  2. From the menu bar at the top the screen, select File |New Project. Then
    choose Java Project from the dialog box that appears. You can either select
    this by starting to type “Java Project” into the wizard, or by finding it by
    expanding the various menus.
  3. In the Create a new Java Project dialog that appears, give the project a name in
    the upper box. For our example, we’ll call it SalesModel (one word, no spaces).
  4. Accept the other defaults (unless you have any other reason to change them).
    Our screen will now look something like this:

When you’ve finished entering the details, click on Finish. You will be redirected to
the main screen, with a new project (SalesModel) created. If you can’t see the project,
try opening either the Package or the Navigator tab.

When you can see the project name, right-click on it. From the menu, choose
New | Package. The New Java Package dialog will be displayed, as shown below.
Enter the details as per the screenshot to create a new package called org.sample,
and then click on Finish

.

If you are doing this via the navigator (or you can take a peek via Win dows
Explorer), you’ll see that this creates a new folder org, and within it a subfolder
called sample. Now that we’ve created a set of folders to organize our JavaBeans,
let’s create the JavaBean itself by creating a class.


	Did you play with Lego blocks as a kid—multicolored plastic blocks that
	you could pull apart and stick together again and again? JavaBeans are
	like those Lego blocks—instead of building toy houses, we can build
	entire computer systems with them.

	Often, while playing Lego, you'd run out of blocks (often red roof tiles)
	just when you were about to finish. Luckily, in Java, we can create as
	many blocks as we want. The class that we're about to put together is our
	mould to let us do this.

To create a new Java class, expand/select the org.sample package (folder) that we
created in the previous step. Right-click on it and select New Class. Fill in the dialog
as shown in the following screenshot, and then click on Finish:

We will now be back in the main editor, with a newly created class called Sales.java
(below). For the moment, there isn’t much there—it’s akin to two nested folders (a
sample folder within one called org) and a new (but almost empty) file / spreadsheet
called Sales.


	pac kage org.sample;
	public class Sales {
	}

By itself, this is not of much use. We need to tell Java about the information that we
want our class (and hence the beans that it creates) to hold. This is similar to adding
new columns to a spreadsheet.

Edit the Java class until it looks something like the code that follows (and take a
quick look of the notes information box further down the page if you want to save a
bit of typing). If you do it correctly, you should have no red marks on the editor (the
red marks look a little like the spell checking in Microsoft Word).


	package org.sample;
	import java.util.Date;
	public class Sales {
		private String name;
		private long sales;
		private Date dateOfSale;
		private boolean chocolateOnlyCustomer;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public long getSales() {
			return sales;
		}
		public void setSales(long sales) {
			this.sales = sales;
		}
		public Date getDateOfSale() {
			return dateOfSale;
		}
		public void setDateOfSale(Date dateOfSale) {
			this.dateOfSale = dateOfSale;
		}
		public boolean isChocolateOnlyCustomer() {
			return chocolateOnlyCustomer;
		}
		public void setChocolateOnlyCustomer(boolean choclateOnlyCustomer) {
			this.chocolateOnlyCustomer = chocolateOnlyCustomer;
		}
	}

Believe it or not, this piece of Java code is almost the same as the Excel Spreadsheet
we saw at the beginning of the chapter. If you want the exact details, let’s go through
what it means line by line.

  • The braces ({ and }) are a bit like tabs. We use them to organize our code.
    package—This data holder will live in the subdirectory sample within the
    directory org.
  • import—List of any other data formats that we need (for example, dates).
    Text and number data formats are automatically imported.
  • Public class Sales—This is the mould that we’ll use to create a JavaBean.
    It’s equivalent to a spreadsheet with a Sales tab.
  • Private String name—create a text (string) field and give it a column
    heading of ‘name’. The private bit means ‘keep it hidden for the moment’.
  • The next three lines do the same thing, but for sales (as a number/long),
    dateOfSale (as a date) and chocolateOnlyCustomer (a Boolean or
    Y/N field).
  • The rest of the lines (for example, getName and setName) are how we control
    access to our private hidden fields. If you look closely, they follow a similar
    naming pattern.


	The get and set lines ( in the previous code) are known as accessor
	methods. They control access to hidden or private fields. They're more
	complicated than may seem necessary for our simple example, as Java has
	a lot more power than we're using at the moment.

	Luckily, Eclipse can auto-generate these for us. (Right-click on the word
	Sales in the editor, then select Source | Generate Getters and Setters
	from the context menu. You should be prompted for the Accessor
	methods that you wish to create.)

Once you have the text edited like the sample above, check again that there are no
spelling mistakes. A quick way to do this is to check the Problems tab in Eclipse
(which is normally at the bottom of the screen).


	If you do have any problems, you may be able to use the Eclipse quick-fix
	feature (highlight the problem, then press Ctrl+1). If that doesn't work,
	check again and ensure that the spelling is exactly the same as shown
	earlier. If that doesn't work, follow the steps in the How to ask for help
	section near the beginning of this book.

Now that we’ve created our model in Java, we need to export it so that we can use in
the Guvnor.

  1. In Ec lipse, right-click on the project name (SalesModel) and select Export.
  2. From the pop-up menu, select jar (this may be under Java; you might
    need to type jar to bring it up). Click on Next. The screen shown above will
    be displayed.
  3. Fill out this screen. Accept the defaults, but give the JAR file a name
    (SalesModel.jar) and a location (in our case C:\temp\SalesModel.jar).
    Remember these settings as we’ll need them shortly.
  4. All being well, you should get an ‘export successful’ message when you click
    on the Finish button, and you will be able to use Windows Explorer to find
    the JAR file that you just created.


	What is a JAR file? JAR stands for Java Archive and is just another name
	for a ZIP compressed file (you may be familiar with the WinZip utility).
	Although our model is pretty small (only one file), compressing the files
	and putting them in one place (the JAR) saves a huge amount of time
	when deploying larger systems.

Congr atulations! You have not only built your first Java file (possibly), but also
successfully exported it elsewhere for use. But now that we’ve built this, how do we
use it in the Guvnor?

email

«»

Comments

comments