[jboss-svn-commits] JBL Code SVN: r20482 - in labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples: ConwaysGameOfLifeExample and 5 other directories.

jboss-svn-commits at lists.jboss.org jboss-svn-commits at lists.jboss.org
Sat Jun 14 12:26:55 EDT 2008


Author: mark.proctor at jboss.com
Date: 2008-06-14 12:26:55 -0400 (Sat, 14 Jun 2008)
New Revision: 20482

Added:
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Chapter-Examples.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/ConwaysGameOfLifeExample/
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/ConwaysGameOfLifeExample/conway1.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/ConwaysGameOfLifeExample/conway2.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/ConwaysGameOfLifeExample/conway_ruleflow_generation.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci1.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci2.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci3.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci4.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci5.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/InsuranceExample/
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/InsuranceExample/BRMS_DSL.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/InsuranceExample/BRMS_Guided.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/InsuranceExample/insurance-ruleflow.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/InsuranceExample/insurance-website.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PetStoreExample/
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PetStoreExample/1-PetStore-Start-Screen.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PetStoreExample/2-stock-added-to-order-list.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PetStoreExample/3-purchase-suggestion.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PetStoreExample/4-Petstore-final-screen.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PricingExample/
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PricingExample/DT_Config.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PricingExample/DT_Table1.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PricingExample/DT_Table2.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-ConwaysGameOfLifeExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-InsuranceExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-MannersExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-PetStoreExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-PricingExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-ShoppingExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/ShoppingExample/
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExample/
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExample/state_example_agenda1.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExample/state_example_audit1.png
Removed:
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/1-PetStore-Start-Screen.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/2-stock-added-to-order-list.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/3-purchase-suggestion.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/4-Petstore-final-screen.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/BRMS_DSL.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/BRMS_Guided.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/DT_Config.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/DT_Table1.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/DT_Table2.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci1.jpg
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci2.jpg
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci3.jpg
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci4.jpg
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci5.jpg
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-Examples.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExample/state_example_agenda1.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExample/state_example_audit1.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExampleExample/
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/conway1.jpg
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/conway2.jpg
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/conway_ruleflow_generation.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/insurance-ruleflow.png
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/insurance-website.png
Log:
JBRULES-1643
-trying to move example images to section folders for better grouping
-better layout for chapters

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/1-PetStore-Start-Screen.png
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/2-stock-added-to-order-list.png
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/3-purchase-suggestion.png
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/4-Petstore-final-screen.png
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/BRMS_DSL.png
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/BRMS_Guided.png
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Chapter-Examples.xml (from rev 20481, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-Examples.xml)
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Chapter-Examples.xml	                        (rev 0)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Chapter-Examples.xml	2008-06-14 16:26:55 UTC (rev 20482)
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<section xmlns:xi="http://www.w3.org/2001/XInclude">
+	<title></title>
+	<section>
+
+		<title>Getting the examples</title>
+
+		<para>Make sure the Drools Eclipse plugin is installed, which needs GEF dependency installed first. Then download and extract the drools-examples zip file, which includes an already created Eclipse project. Import that project into a new Eclipse workspace. The rules all have example classes that execute the rules. If you want to try the examples in another project (or another IDE) then you will need to setup the dependencies by hand of course. Many, but not all of the examples are documented below, enjoy :)</para>
+	</section>	
+
+    <xi:include href="Section-HelloWorldExample.xml" />
+    
+    <xi:include href="Section-StateExample.xml" />
+    
+    <xi:include href="Section-FibonacciExample.xml" />
+    
+    <xi:include href="Section-BankingExample.xml" />
+
+    <xi:include href="Section-PricingExample.xml" />
+
+    <xi:include href="Section-PetStoreExample.xml" />
+
+    <xi:include href="Section-HonestPoliticianExample.xml" />
+    
+    <xi:include href="Section-SodukiExample.xml" />
+    
+    <xi:include href="Section-NumberGuessExample.xml" />
+
+    <xi:include href="Section-MannersExample.xml" />
+
+    <xi:include href="Section-ConwaysGameOfLifeExample.xml" />
+
+
+</section>


Property changes on: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/ConwaysGameOfLifeExample
___________________________________________________________________
Name: svn:ignore
   + *.db


Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/ConwaysGameOfLifeExample/conway1.png
===================================================================
(Binary files differ)


Property changes on: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/ConwaysGameOfLifeExample/conway1.png
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream

Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/ConwaysGameOfLifeExample/conway2.png
===================================================================
(Binary files differ)


Property changes on: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/ConwaysGameOfLifeExample/conway2.png
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/ConwaysGameOfLifeExample/conway_ruleflow_generation.png (from rev 20476, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/conway_ruleflow_generation.png)
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/DT_Config.png
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/DT_Table1.png
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/DT_Table2.png
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci1.jpg
===================================================================
(Binary files differ)

Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci1.png
===================================================================
(Binary files differ)


Property changes on: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci1.png
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci2.jpg
===================================================================
(Binary files differ)

Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci2.png
===================================================================
(Binary files differ)


Property changes on: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci2.png
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci3.jpg
===================================================================
(Binary files differ)

Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci3.png
===================================================================
(Binary files differ)


Property changes on: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci3.png
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci4.jpg
===================================================================
(Binary files differ)

Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci4.png
===================================================================
(Binary files differ)


Property changes on: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci4.png
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci5.jpg
===================================================================
(Binary files differ)

Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci5.png
===================================================================
(Binary files differ)


Property changes on: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/FibonacciExample/fibonacci5.png
___________________________________________________________________
Name: svn:mime-type
   + application/octet-stream

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/InsuranceExample/BRMS_DSL.png (from rev 20476, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/BRMS_DSL.png)
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/InsuranceExample/BRMS_Guided.png (from rev 20476, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/BRMS_Guided.png)
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/InsuranceExample/insurance-ruleflow.png (from rev 20476, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/insurance-ruleflow.png)
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/InsuranceExample/insurance-website.png (from rev 20476, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/insurance-website.png)
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PetStoreExample/1-PetStore-Start-Screen.png (from rev 20476, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/1-PetStore-Start-Screen.png)
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PetStoreExample/2-stock-added-to-order-list.png (from rev 20476, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/2-stock-added-to-order-list.png)
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PetStoreExample/3-purchase-suggestion.png (from rev 20476, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/3-purchase-suggestion.png)
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PetStoreExample/4-Petstore-final-screen.png (from rev 20476, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/4-Petstore-final-screen.png)
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PricingExample/DT_Config.png (from rev 20476, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/DT_Config.png)
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PricingExample/DT_Table1.png (from rev 20476, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/DT_Table1.png)
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/PricingExample/DT_Table2.png (from rev 20476, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/DT_Table2.png)
===================================================================
(Binary files differ)

Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-ConwaysGameOfLifeExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-ConwaysGameOfLifeExample.xml	                        (rev 0)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-ConwaysGameOfLifeExample.xml	2008-06-14 16:26:55 UTC (rev 20482)
@@ -0,0 +1,315 @@
+<?xml version="1.0" encoding="UTF-8"?>
+	<section xml:base="../" >
+    <title>Conways Game Of Life Example</title>
+
+    <programlisting><emphasis role="bold">Name:</emphasis> Conways Game Of Life
+<emphasis role="bold">Main class:</emphasis> org.drools.examples.conway.ConwayAgendaGroupRun org.drools.examples.conway.ConwayRuleFlowGroupRun
+<emphasis role="bold">Type:</emphasis> java application
+<emphasis role="bold">Rules file:</emphasis> conway-ruleflow.drl conway-agendagroup.drl
+<emphasis role="bold">Objective:</emphasis> Demonstrates 'accumulate', 'collect' and 'from'</programlisting>
+
+    <para>Conway's Game Of Life, <ulink
+    url="http://en.wikipedia.org/wiki/Conway's_Game_of_Life">http://en.wikipedia.org/wiki/Conway's_Game_of_Life</ulink>
+    <ulink
+    url="http://www.math.com/students/wonders/life/life.html">http://www.math.com/students/wonders/life/life.html</ulink>,
+    is a famous cellular automaton conceived in the early 1970's by
+    mathematician John Conway. While the system is well known as "Conway's
+    Game Of Life", it really isn't a game at all. Conway's system is more like
+    a life simulation. Don't be intimidated. The system is terribly simple and
+    terribly interesting. Math and Computer Science students alike have
+    marvelled over Conway's system for more than 30 years now. The application
+    represented here is a Swing based implementation of Conway's Game of Life.
+    The rules that govern the system are implemented as business rules using
+    Drools. This document will explain the rules that drive the simulation and
+    discuss the Drools specific parts of the implementation.</para>
+
+    <para>We'll first introduce the grid view, shown below, to help
+    visualisation of the problem; this is where the life simuation takes
+    place. Initially the grid is empty, meaning that there are no live cells
+    in the system; ech cell can be considered "LIVE" or "DEAD", live cells
+    have a green ball in them. Pre-selected patterns of live cells can be
+    selected from the "Pattern" drop down or cells can be doubled-clicked to
+    toggle them between LIVE and DEAD. It's important to understand that each
+    cell is related to it's neighbour cells, which is a core part of the
+    game's rules and will be explained in a moment. Neighbors include not only
+    cells to the left, right, top and bottom but also cells that are connected
+    diagonally. Each cell has a total of 8 neighbors except the 4 corner cells
+    and all of the other cells along the 4 edges. Corner cells have 3
+    neighbors and other edge cells have 5 neighbors.</para>
+
+    <figure>
+      <title>Conways Example : Starting a new game</title>
+
+      <mediaobject>
+        <imageobject>
+		<imagedata fileref="ConwaysGameOfLifeExample/conway1.png" />
+        </imageobject>
+      </mediaobject>
+    </figure>
+
+    <para>So what are the basic rules that govern this game? Each generation,
+    i.e. completion iteration and evalution of all cells, the system evolves
+    and cells may be born or killed, there are a very simple set of rules that
+    govern what the next generation will look like.</para>
+
+    <itemizedlist>
+      <listitem>
+        <para>If a live cell has fewer than 2 live neighbors, it dies of
+        loneliness</para>
+      </listitem>
+
+      <listitem>
+        <para>If a live cell has more than 3 live neighbors, it dies from
+        overcrowding</para>
+      </listitem>
+
+      <listitem>
+        <para>If a dead cell has exactly 3 live neighbors, it comes to
+        life</para>
+      </listitem>
+    </itemizedlist>
+
+    <para>That is all there is to it. Any cell that doesn't meet any of those
+    criteria is left as is for the next generation. With those simple rules in
+    mind, go back and play with the system a little bit more and step through
+    some generations one at a time and notice these rules taking their
+    effect.</para>
+
+    <para>The screnshot below shows an example generation, with a number of
+    live cells. Don't worry about matching the exact patterns represented in
+    the screen shot. Just get some groups of cells added to the grid. Once you
+    have groups of live cells in the grid, or select a pre-designed pattern,
+    click the "Next Generation" button and notice what happens. Some of the
+    live cells are killed (the green ball disappears) and some dead cells come
+    to life (a green ball appears). Cycle through several generations and see
+    if you notice any patterns. If you click on the "Start" button, the system
+    will evolve itself so you don't need to click the "Next Generation" button
+    over and over. Play with the system a little and then come back here for
+    more details of how the application works.</para>
+
+    <figure>
+      <title>Conways Example : A running game</title>
+
+      <mediaobject>
+        <imageobject>
+		<imagedata fileref="ConwaysGameOfLifeExample/conway2.png" />
+        </imageobject>
+      </mediaobject>
+    </figure>
+
+    <para>Now lets delve into the code, as this is an advanced example we'll
+    assume that by now you know your way around the Drools framework and able
+    to connect many of the dots, so we'll just focus at a hgh level
+    overview.The example has two ways to execute, one way uses AgendaGroups to
+    manage execution flow the other uses RuleFlowGroups to manage execution
+    flow - so it's a great way to see the differences. - that's
+    ConwayAgendaGroupRun and ConwayRuleFlowGroupRun respectively. For this
+    example I'll cover the ruleflow version, as its what most people will
+    use.</para>
+
+    <para>All the Cells are inserted into the session and the rules in the
+    ruleflow-group "register neighbor" are allowed to execute by the ruleflow
+    process. What this group of rules does is for each cell it registers the
+    north east, north, north west and west cells using a Neighbor relation
+    class, notice this relation is bi-drectional which is why we don't have to
+    do any rules for southern facing cells. Note that the constraints make
+    sure we stay one column back from the end and 1 row back from the top. By
+    the time all activations have fired for these rules all cells are related
+    to all their neighboring cells.</para>
+
+    <example>
+      <title>Conways Example : Register all Cell Neighbour relations</title>
+
+      <programlisting>rule "register north east"
+    ruleflow-group "register neighbor"
+when
+    CellGrid( $numberOfColumns : numberOfColumns )
+    $cell: Cell( $row : row &gt; 0, $col : col &lt; ( $numberOfColumns - 1 ) )            
+    $northEast : Cell( row  == ($row - 1), col == ( $col + 1 ) )    
+then                    
+    insert( new Neighbor( $cell, $northEast ) );
+    insert( new Neighbor( $northEast, $cell ) );        
+end
+
+rule "register north"
+    ruleflow-group "register neighbor"  
+when
+    $cell: Cell( $row : row &gt; 0, $col : col )   
+    $north : Cell( row  == ($row - 1), col == $col )    
+then        
+    insert( new Neighbor( $cell, $north ) );
+    insert( new Neighbor( $north, $cell ) );        
+end
+
+rule "register north west"
+    ruleflow-group "register neighbor"
+when
+    $cell: Cell( $row : row &gt; 0, $col : col &gt; 0 )           
+    $northWest : Cell( row  == ($row - 1), col == ( $col - 1 ) )                        
+then        
+    insert( new Neighbor( $cell, $northWest ) );
+    insert( new Neighbor( $northWest, $cell ) );        
+end
+
+rule "register west"
+    ruleflow-group "register neighbor"
+when
+    $cell: Cell( $row : row &gt;= 0, $col : col &gt; 0 )          
+    $west : Cell( row  == $row, col == ( $col - 1 ) )                       
+then        
+    insert( new Neighbor( $cell, $west ) );
+    insert( new Neighbor( $west, $cell ) );         
+end</programlisting>
+    </example>
+
+    <para>Once all the cells are inserted some java code applies the pattern
+    to the grid setting certain cells to Live. Then when the user clicks
+    "start" or "next generation" it executes the "Generation" ruleflow. This
+    ruleflow is responsible for the management of all changes of cells in each
+    generation cycle.</para>
+
+    <figure>
+      <title>Conways Example : ruleflow "Generation"</title>
+
+      <mediaobject>
+        <imageobject>
+		<imagedata fileref="ConwaysGameOfLifeExample/conway_ruleflow_generation.png" />
+        </imageobject>
+      </mediaobject>
+    </figure>
+
+    <para>The ruleflow process first enters the "evaluate" group, this means
+    any active rule in that group can fire. The rules in this group apply the
+    main game of life rules discussed in the beginning of the example, where
+    it determines what cells will be killed and which ones given life. We use
+    the "phase" attribute to drives the reasoning of the Cell by specific
+    groups of rules; typical the phase is tied to a RuleFlowGroup. in the
+    ruleflow process definition. Notice that it doesn't actually change the
+    state of any Cells at this point; this is because it's evaluating the Grid
+    in turn and it must complete the full evaluation until those changes can
+    be applied. To achieve this it sets the cell to a "phase" which is either
+    Phase.KILL or Phase.BIRTH, which is used later to control actions applied
+    to the Cell and when.</para>
+
+    <example>
+      <title>Conways Example : Evaluate Cells with state changes</title>
+
+      <programlisting>rule "Kill The Lonely"
+    ruleflow-group "evaluate"
+    no-loop
+when
+#   A live cell has fewer than 2 live neighbors
+    theCell: Cell(liveNeighbors &lt; 2, cellState == CellState.LIVE, phase == Phase.EVALUATE)
+then
+    theCell.setPhase(Phase.KILL);
+    update( theCell );
+end
+
+rule "Kill The Overcrowded"
+    ruleflow-group "evaluate"
+    no-loop
+when
+#   A live cell has more than 3 live neighbors
+    theCell: Cell(liveNeighbors &gt; 3, cellState == CellState.LIVE, phase == Phase.EVALUATE)
+then
+    theCell.setPhase(Phase.KILL);
+    update( theCell );
+end
+
+rule "Give Birth"
+    ruleflow-group "evaluate"
+    no-loop
+when
+#   A dead cell has 3 live neighbors
+    theCell: Cell(liveNeighbors == 3, cellState == CellState.DEAD, phase == Phase.EVALUATE)
+then
+    theCell.setPhase(Phase.BIRTH);
+    update( theCell );
+end
+</programlisting>
+    </example>
+
+    <para>Once all Cells in the grid have been evaluated we first clear any
+    calculation activations, that occured from any previous data changes, via
+    the "reset calculate" rule, which clears any activations in the
+    "calculate" group. We then enter a split which allows any activations in
+    the "kill" groups and "birth" groups to fire, these rules are responsible
+    for applying the state change.</para>
+
+    <example>
+      <title>Conways Example : Apply the state changes</title>
+
+      <programlisting>rule "reset calculate"
+    ruleflow-group "reset calculate"
+when
+then
+    WorkingMemory wm = drools.getWorkingMemory();
+    wm.clearRuleFlowGroup( "calculate" );
+end
+
+rule "kill"
+    ruleflow-group "kill"
+    no-loop
+when
+    theCell: Cell(phase == Phase.KILL)
+then
+    theCell.setCellState(CellState.DEAD);
+    theCell.setPhase(Phase.DONE);   
+    update( theCell );
+end 
+ 
+rule "birth"
+    ruleflow-group "birth"
+    no-loop
+when
+    theCell: Cell(phase == Phase.BIRTH)
+then
+    theCell.setCellState(CellState.LIVE);
+    theCell.setPhase(Phase.DONE);
+    update( theCell );  
+end </programlisting>
+    </example>
+
+    <para>At this stage a number of Cells have been modified with the state
+    changed to either LIVE or DEAD, this is where we get to see the power of
+    the Neighbour cell and relational programming. When a cell becomes LIVE or
+    DEAD we use the Neigbor relation drive the iteration over all surrounding
+    Cells increasing or decreasing the LIVE neighbour count, any cell who has
+    their count changed is also set to to the EVALUATE phase, to make sure
+    they are reasoned over duing the evaluate stage of the ruleflow process.
+    Notice that we don't have to do any iteration ourselves, by simpy applying
+    the relations in the rules we can get the rule engine to do all the hard
+    work for us in a minimal amount of code - very nice :) Once the live count
+    for all Cells has been determiend and set the ruleflow process comes to
+    and end; the user can either tell it to evaluate another generation, of if
+    "start" was clicked the engine will start the ruleflow process
+    again.</para>
+
+    <example>
+      <title>Conways Example : Evaluate Cells with state changes</title>
+
+      <programlisting>rule "Calculate Live"
+    ruleflow-group "calculate"
+    lock-on-active  
+when
+    theCell: Cell(cellState == CellState.LIVE)
+    Neighbor(cell == theCell, $neighbor : neighbor) 
+then
+    $neighbor.setLiveNeighbors( $neighbor.getLiveNeighbors() + 1 );
+    $neighbor.setPhase( Phase.EVALUATE );   
+    update( $neighbor );
+end 
+
+rule "Calculate Dead"
+    ruleflow-group "calculate"
+    lock-on-active  
+when
+    theCell: Cell(cellState == CellState.DEAD)
+    Neighbor(cell == theCell, $neighbor : neighbor )
+then
+    $neighbor.setLiveNeighbors( $neighbor.getLiveNeighbors() - 1 );
+    $neighbor.setPhase( Phase.EVALUATE );
+    update( $neighbor );    
+end </programlisting>
+    </example>
+  </section>
\ No newline at end of file

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-Examples.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-Examples.xml	2008-06-14 16:17:03 UTC (rev 20481)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-Examples.xml	2008-06-14 16:26:55 UTC (rev 20482)
@@ -1,1857 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<section xmlns:xi="http://www.w3.org/2001/XInclude">
-	<title></title>
-	<section>
-
-		<title>Getting the examples</title>
-
-		<para>Make sure the Drools Eclipse plugin is installed, which needs GEF dependency installed first. Then download and extract the drools-examples zip file, which includes an already created Eclipse project. Import that project into a new Eclipse workspace. The rules all have example classes that execute the rules. If you want to try the examples in another project (or another IDE) then you will need to setup the dependencies by hand of course. Many, but not all of the examples are documented below, enjoy :)</para>
-	</section>	
-
-    <xi:include href="Section-HelloWorldExample.xml" />
-    <xi:include href="Section-StateExample.xml" />
-    <xi:include href="Section-FibonacciExample.xml" />
-    <xi:include href="Section-BankingExample.xml" />
-
-
-	<section >
-
-		<title>Pricing Rule Decision Table Example</title>
-
-		<para>The Pricing Rule decision table demonstrates the use of a decision table in a spreadsheet (XLS format) in calculating the retail cost of an insurance policy. The purpose of the set of rules provided is to calculate a base price, and an additional discount for a car driver applying for a specific policy. The drivers age, history and the policy type all contribute to what the basic premium is, and an additional chunk of rules deals with refining this with a subtractive percentage discount.</para>
-
-		<programlisting><emphasis role="bold">Name:</emphasis> Example Policy Pricing
-<emphasis role="bold">Main class:</emphasis> org.drools.examples.PricingRuleDTExample
-<emphasis role="bold">Type:</emphasis> java application
-<emphasis role="bold">Rules file:</emphasis> ExamplePolicyPricing.xls
-<emphasis role="bold">Objective:</emphasis> demonstrate spreadsheet based decision tables.    </programlisting>
-
-		<section>
-			<title>Executing the example</title>
-
-			<para>Open the PricingRuleDTExample.java and execute it as a Java application. It should produce the following console output:</para>
-
-			<programlisting>Cheapest possible
-BASE PRICE IS: 120
-DISCOUNT IS: 20     </programlisting>
-
-			<para>The code to the execute the example is very similar to the other examples. The rules are loaded, the facts inserted and a stateless session is used. What is different is how the rules are obtained:</para>
-
-			<programlisting>SpreadsheetCompiler compiler = new SpreadsheetCompiler();
-String drl = compiler.compile(getSpreadsheetStream(), InputType.XLS);
-</programlisting>
-
-			<para>Note the use of the SpreadsheetCompiler class. It is what takes the XLS (as a binary InputStream to the XLS file), and outputs ordinary DRL (which is then dealt with in the usual way). You can (if you like) also print out the DRL. If you use the BRMS, all this is of course taken care of for you.</para>
-
-			<para>There are 2 facts used in this example, Driver, and Policy. Both are used with their default values. The Driver is 30 years old, has had no prior claims and currently has a risk profile of LOW. The Policy being applied for is COMPREHENSIVE, and the policy has not yet been approved.</para>
-		</section>
-		
-		<section>
-			<title>The decision table</title>
-
-			<para>In this decision table, each row is a rule, and each column is a condition or an action.</para>
-
-			<figure>
-				<title>Decision table configuration</title>
-
-				<mediaobject>
-					<imageobject>
-						<imagedata fileref="TroubleTicket/DT_Config.png" />
-					</imageobject>
-				</mediaobject>
-			</figure>
-
-			<para>Referring to the above, we have the RuleSet declaration, which provides the package name. There are also other optional items you can have here, such as Variables for global variables, and Imports for importing classes. In this case, the namespace of the rules is the same as the fact classes we are using, so we can omit it.</para>
-
-			<para>Moving further down, we can see the RuleTable declaration. The name after this (Pricing bracket) is used as the prefix for all the generated rules. Below that, we have CONDITION or ACTION - this indicates the purpose of the column (ie does it form part of the condition, or an action of a rule that will be generated).</para>
-
-			<para>You can see there is a Driver which is spanned across 3 cells, this means the template expressions below it apply to that fact. So we look at the drivers age range (which uses $1 and $2 with comma separated values), locationRiskProfile, and priorClaims in the respective columns. In the action columns, we are setting the policy base price, and then logging a message.</para>
-
-			<figure>
-				<title>Base price calculation</title>
-
-				<mediaobject>
-					<imageobject>
-						<imagedata fileref="TroubleTicket/DT_Table1.png" />
-					</imageobject>
-				</mediaobject>
-			</figure>
-
-			<para>Referring to the above, we can see there are broad category brackets (indicated by the comment in the left most column). As we know the details of our driver and their policy, we can tell (with a bit of thought) that they should match row number 18, as they have no prior accidents, and are 30 years old. This gives us a base price of 120.</para>
-
-			<figure>
-				<title>Discount calculation</title>
-
-				<mediaobject>
-					<imageobject>
-						<imagedata fileref="TroubleTicket/DT_Table2.png" />
-					</imageobject>
-				</mediaobject>
-			</figure>
-
-			<para>Referring to the above, we are seeing if there is any discount we can give our driver. Based on the Age bracket, number of priot claims, and the policy type, a discount is provided. In our case, the drive is 3, with no priors, and they are applying for COMPREHENSIVE, this means we can give a discount of 20%. Note that this is actually a separate table, but in the same worksheet. This different templates apply.</para>
-
-			<para>It is important to note that decision tables generate rules, this means they aren't simply top down logic, but more a means to capture data that generate rules (this is a subtle difference that confuses some people). The evaluation of the rules is not "top down" necessarily, all the normal indexing and mechanics of the rule engine still apply.</para>
-		</section>
-	</section>	
-
-
-	
-	<section>
-		<title>Shopping Example</title>
-
-		<programlisting><emphasis role="bold">Name:</emphasis>Shopping Example
-<emphasis role="bold">Main class:</emphasis> org.drools.examples.ShoppingExample
-<emphasis role="bold">Type:</emphasis> java application
-<emphasis role="bold">Rules file:</emphasis> Shopping.drl
-<emphasis role="bold">Objective:</emphasis> demonstrate truth maintenance, accumulate
-</programlisting>
-
-		<para>The shopping example simulates a very simple shopping cart type application, where the idea is to track a users purchases in a stateful session, and apply discounts as appropriate.</para>
-		
-		<section>
-			<title>Running the example</title>
-
-			<para>The following is a listing of the interesting parts that are used to launch the example:</para>
-
-			<programlisting>Customer mark = new Customer( "mark",
-                              0 );
-session.insert( mark );
-Product shoes = new Product( "shoes",
-                             60 );
-session.insert( shoes );
-Product hat = new Product( "hat",
-                           60 );
-session.insert( hat );
-session.insert( new Purchase( mark,
-                              shoes ) );
-FactHandle hatPurchaseHandle = session.insert( new Purchase( mark,
-                                                             hat ) );
-session.fireAllRules();
-session.retract( hatPurchaseHandle );
-System.out.println( "Customer mark has returned the hat" );
-session.fireAllRules();      </programlisting>
-
-			<para>Refering the the above listing, we can see there is a Customer ("mark"), and there are 2 Products ("shoes" and "hat") which are available for Purchase. In this case, a Purchase combines a customer with a product (and a product has a price attribute).</para>
-
-			<para>Note that after we fireAllRules(), we then retract the purchase of a hat (but leave the purchase of shoes in). Running the example as a java application should see the following output:</para>
-
-			<programlisting>Customer mark just purchased hat
-Customer mark just purchased shoes
-Customer mark now has a shopping total of 120.0
-Customer mark now has a discount of 10
-Customer mark has returned the hat
-Customer mark now has a discount of 0      </programlisting>
-
-		</section>
-
-		<section>
-			<title>Discounts and purchases</title>
-
-			<para>We want to give discounts to customers who purchase stuff of enough value. This discount could also be removed should the customer decide not to purchase enough to fall within the threshold.</para>
-
-			<programlisting>rule "Purchase notification"
-    salience 10
-
- when
-  $c : Customer()
-  $p : Purchase( customer == $c)	    
- then
-     System.out.println( "Customer " + $c.name + " just purchased " + $p.product.name );
-end 
-
-rule "Discount removed notification"
- when
-     $c : Customer()
-  not Discount( customer == $c )
- then
-  $c.discount = 0 ;
-  System.out.println( "Customer " + $c.name + " now has a discount of " + $c.discount );
-end
-
-rule "Discount awarded notification"
- when
-     $c : Customer()
-     $d : Discount( customer == $c )
- then
-  System.out.println( "Customer " + $c.name + " now has a discount of " + $d.amount );
-end      </programlisting>
-
-			<para>The "Purchase notification" rule simply makes note of the purchase event for a given customer. The "Discount removed notification" rule removes the customer discount (by checking for the non existence of a discount for that customer). The "Discount awarded notification" simply makes not of the fact that the discount was applied.</para>
-		</section>
-		
-		<section>
-			<title>Calculating the discount</title>
-
-			<para>Calculating the discount is done with a single rule, using the higher order logic of "accumulate".</para>
-
-			<programlisting>rule "Apply 10% discount if total purcahses is over 100"
- no-loop true
- dialect "java"
-    when
-      $c : Customer()
-      $i : Double(doubleValue  &gt; 100) from accumulate ( Purchase( customer == $c, $price : product.price ), 
-                                                            sum( $price ) )
-    then
-      $c.setDiscount( 10 );
-      insertLogical( new Discount($c, 10) );
-      System.out.println( "Customer " + $c.getName() + " now has a shopping total of " + $i );
-end      </programlisting>
-
-			<para>An interesting part of this rule is the "accumulate": this is saying to accumulate a total (sum) of the $price of a product (product.price) for all Purchase facts that belong to the customer ($c). The result of this is a Double. The rule then checks to see if this total is greater then 100. If it is, it applies the discount (of 10), and then inserts a logical fact of the Discount object.</para>
-
-			<para>The purpose of the logical insertion of the Discount, is to automatically retract the Discount object should the total of the purchases not add up to &gt; 100 (when the LHS is no longer satisified, restract the resulting logical assertions - this is what is meant by "truth maintenance"). The act of inserting the Discount, causes the "Discount awarded notification" rule to activate. However, should the discount fact be retracted, the "Discount removed notification" will activate, resulting in the customers discount being wiped out. In the example you can see this happen, as after the first fireAllRules(), a purchase is retracted, causing the total to fall below 100, which means the conditions that satisfied the "Apply 10% discount..." rule no longer apply, hence the logical fact of "Discount" is automatically retracted.</para>
-		</section>
-	</section>
-
-		<section>
-			<title>Pet Store Example</title>
-
-			<programlisting><emphasis role="bold">Name:</emphasis> Pet Store 
-<emphasis role="bold">Main class:</emphasis> org.drools.examples.PetStore
-<emphasis role="bold">Type:</emphasis> Java application
-<emphasis role="bold">Rules file:</emphasis> PetStore.drl
-<emphasis role="bold">Objective:</emphasis> Demonstrate use of Agenda Groups, Global Variables and integration with a GUI (including callbacks from within the Rules)
-</programlisting>
-
-			<para>The Pet Store example shows how to integrate Rules with a GUI (in this case a Swing based Desktop application). Within the rules file, it shows how to use agenda groups and auto-focus to control which of a set of rules is allowed to fire at any given time. It also shows mixing of Java and MVEL dialects within the rules, the use of accumulate functions and calling of Java functions from within the ruleset.</para>
-
-			<para>Like the rest of the the samples, all the Java Code is contained in one file. The PetStore.java contains the following principal classes (in addition to several minor classes to handle Swing Events)</para>
-
-			<itemizedlist>
-				<listitem>
-					<para><emphasis role="italic"> Petstore</emphasis> - containing the main() method that we will look at shortly.</para>
-				</listitem>
-
-				<listitem>
-					<para><emphasis role="italic">PetStoreUI</emphasis> - responsible for creating and displaying the Swing based GUI. It contains several smaller classes , mainly for responding to various GUI events such as mouse and button clicks.</para>
-				</listitem>
-
-				<listitem>
-					<para><emphasis role="italic">TabelModel</emphasis> - for holding the table data. Think of it as a JavaBean that extends the Swing AbstractTableModel class.</para>
-				</listitem>
-
-				<listitem>
-					<para><emphasis role="italic">CheckoutCallback</emphasis> - Allows the GUI to interact with the Rules.</para>
-				</listitem>
-
-				<listitem>
-					<para><emphasis role="italic">Ordershow </emphasis> - the items that we wish to buy.</para>
-				</listitem>
-
-				<listitem>
-					<para><emphasis role="italic">Purchase</emphasis> - Details of the order and the products we are buying.</para>
-				</listitem>
-
-				<listitem>
-					<para><emphasis role="italic">Product</emphasis> - JavaBean holding details of the product available for purchase, and it's price.</para>
-				</listitem>
-			</itemizedlist>
-
-			<para>Much of the Java code is either JavaBeans (simple enough to understand) or Swing based. We will touch on some Swing related points in the this tutorial , but a good place to get more Swing component information is <ulink url="???"><uri>http://java.sun.com/docs/books/tutorial/uiswing/</uri> available at the Sun Swing website.<citebiblioid /></ulink></para>
-
-			<para>There are two important Rules related pieces of Java code in <emphasis role="italic">Petstore.java</emphasis>.</para>
-
-			<example>
-				<title>Creating the PetStore RuleBase - extract from PetStore.java main() method</title>
-
-				<programlisting>PackageBuilder builder = new PackageBuilder();
-builder.addPackageFromDrl( new InputStreamReader( 
-PetStore.class.getResourceAsStream( "PetStore.drl" ) ) );
-RuleBase ruleBase = RuleBaseFactory.newRuleBase();
-ruleBase.addPackage( builder.getPackage() );
-
-//RuleB
-Vector stock = new Vector();
-stock.add( new Product( "Gold Fish",5 ) );
-stock.add( new Product( "Fish Tank", 25 ) );
-stock.add( new Product( "Fish Food", 2 ) );
-
-//The callback is responsible for populating working memory and
-// fireing all rules
-PetStoreUI ui = new PetStoreUI( stock, new CheckoutCallback( ruleBase ) );
-ui.createAndShowGUI();
-</programlisting>
-			</example>
-
-			<para>This code above loads the rules (drl) file from the classpath. Unlike other examples where the facts are asserted and fired straight away, this example defers this step to later. The way it does this is via the second last line where the PetStoreUI is created using a constructor the passes in the Vector called stock containing products, and an instance of the CheckoutCallback class containing the RuleBase that we have just loaded.</para>
-
-			<para>The actual Javacode that fires the rules is within the <emphasis role="italic">CheckoutCallBack.checkout()</emphasis> method. This is triggered (eventually) when the 'Checkout' button is pressed by the user.</para>
-
-			<example>
-				<title>Firing the Rules - extract from the CheckOutCallBack.checkout() method</title>
-
-				<programlisting>public String checkout(JFrame frame, List items) throws FactException {           
-    Order order = new Order();
-
-    //Iterate through list and add to cart
-    for ( int i = 0; i &lt; items.size(); i++ ) {
-        order.addItem( new Purchase( order, (Product) items.get( i ) ) );
-    }
-
-    //add the JFrame to the ApplicationData to allow for user interaction
-    WorkingMemory workingMemory = ruleBase.newStatefulSession();
-    workingMemory.setGlobal( "frame", frame );
-    workingMemory.setGlobal( "textArea",  this.output );
-
-    workingMemory.insert( new Product( "Gold Fish", 5 ) );
-    workingMemory.insert( new Product( "Fish Tank", 25 ) );
-    workingMemory.insert( new Product( "Fish Food",  2 ) );
-    workingMemory.insert( new Product( "Fish Food Sample", 0 ) );            
-           
-    workingMemory.insert( order );
-    workingMemory.fireAllRules();
-
-    //returns the state of the cart
-    return order.toString();
-}
-</programlisting>
-			</example>
-
-			<para>Two items get passed into this method; A handle to the JFrame Swing Component surrounding the output text frame (bottom of the GUI if / when you run the component). The second item is a list of order items; this comes from the TableModel the stores the information from the 'Table' area at the top right section of the GUI.</para>
-
-			<para>The <emphasis role="italic">for()</emphasis> loop transforms the list of order items coming from the GUI into the Order JavaBean (also contained in the PetStore.java file). Note that it would be possible to refer to the Swing dataset directly within the rules, but it is better coding practice to do it this way (using Simple Java Objects). It means that we are not tied to Swing if we wanted to transform the sample into a Web application.</para>
-
-			<para>It is important to note that <emphasis role="bold">all state in this example is stored in the Swing components, and that the rules are effectively stateless. </emphasis>Each time the 'Checkout' button is pressed, this code copies the contents of the Swing <emphasis>TableModel</emphasis> into the Session / Working Memory.</para>
-
-			<para>Within this code, there are nine calls to the working memory. The first of these creates a new workingMemory (statefulSession) from the Rulebase - remember that we passed in this Rulebase when we created the CheckoutCallBack class in the <emphasis role="italic">main()</emphasis> method. The next two calls pass in two objects that we will hold as Global variables in the rules - the Swing text area and Swing frame that we will use for writing messages later.</para>
-
-			<para>More inserts put information on products into the working memory, as well as the order list. The final call is the standard <emphasis role="italic">fireAllRules()</emphasis>. Next, we look at what this method causes to happen within the Rules file.</para>
-			
-			<example>
-				<title>Package, Imports , Globals and Dialect - extract (1) from PetStore.drl</title>
-
-				<programlisting>package org.drools.examples
-
-import org.drools.WorkingMemory
-import org.drools.examples.PetStore.Order
-import org.drools.examples.PetStore.Purchase
-import org.drools.examples.PetStore.Product
-import java.util.ArrayList
-import javax.swing.JOptionPane;
-
-import javax.swing.JFrame 
-        
-global JFrame frame 
-global javax.swing.JTextArea textArea
- 
-dialect "mvel"
-</programlisting>
-			</example>
-    
-			<para>The first part of the <emphasis role="italic">PetStore.drl</emphasis> file contains the standard package and import statement to make various Java classes available to the rules. We've seen the dialect been defaulted to "mvel" before in other examples. What is new are the two globals <emphasis>frame and textArea. </emphasis>These hold references to the Swing JFrame and Textarea components that were previous passed by the Java code calling the <emphasis>setGlobal() </emphasis>method. Unlike normal variables in Rules , which expire as soon as the rule has fired, Global variables retain their value for the lifetime of the (Stateful in this case) Session.</para>
-
-			<para>The next extract (below) is from the <emphasis role="bold">end</emphasis> of the PetStore.drl file. It contains two functions that are referenced by the rules that we will look at shortly.</para>
-			
-			<example>
-				<title>Java Functions in the Rules - extract (2) from PetStore.drl</title>
-
-				<programlisting>function void doCheckout(JFrame frame, WorkingMemory workingMemory) {
-    Object[] options = {"Yes",
-                        "No"};
-                            
-    int n = JOptionPane.showOptionDialog(frame,
-                                         "Would you like to checkout?",
-                                         "",
-                                         JOptionPane.YES_NO_OPTION,
-                                         JOptionPane.QUESTION_MESSAGE,
-                                         null,
-                                         options,
-                                         options[0]);
-
-    if (n == 0) {
-        workingMemory.setFocus( "checkout" );
-    }   
-}
-
-function boolean requireTank(JFrame frame, WorkingMemory workingMemory, Order order, Product fishTank, int total) {
-    Object[] options = {"Yes",
-                        "No"};
-                            
-    int n = JOptionPane.showOptionDialog(frame,
-                                         "Would you like to buy a tank for your " + total + " fish?",
-                                         "Purchase Suggestion",
-                                         JOptionPane.YES_NO_OPTION,
-                                         JOptionPane.QUESTION_MESSAGE,
-                                         null,
-                                         options,
-                                         options[0]);
-                                             
-    System.out.print( "SUGGESTION: Would you like to buy a tank for your "
-                      + total + " fish? - " );
-
-    if (n == 0) {
-        Purchase purchase = new Purchase( order, fishTank );
-        workingMemory.insert( purchase );
-        order.addItem( purchase );
-        System.out.println( "Yes" );
-    } else {
-        System.out.println( "No" );
-    }      
-    return true;
-}
-</programlisting>
-			</example>
-  
-
-			<para>Having these functions in the rules file makes the PetStore sample more compact - in real life you probably have the functions in a file of their own (within the same rules package), or as a static method on a standard Java class (and import them using the <emphasis role="bold">import function my.package.Foo.hello </emphasis>syntax).</para>
-
-			<para>The above functions are</para>
-
-			<itemizedlist>
-				<listitem>
-					<para><emphasis role="italic">doCheckout()</emphasis> - Displays a dialog asking the user if they wish to checkout. If they do, focus is set to the <emphasis role="italic">checkOut</emphasis> agenda-group, allowing rules in that group to (potentially) fire.</para>
-				</listitem>
-
-				<listitem>
-					<para><emphasis role="italic">requireTank()</emphasis> - Displays a dialog asking the user if they wish to buy a tank. If so, a new FishTank <emphasis role="italic">Product</emphasis> added to the orderlist in working memory.</para>
-				</listitem>
-			</itemizedlist>
-			
-			<para>We'll see later the rules that call these functions.The next set of examples are from the PetStore rules themselves. The first extract is the one that happens to fire first (partly because it has the <emphasis role="italic">auto-focus</emphasis> attibute set to true).</para>
-				
-			<example>
-				<title>Putting each (individual) item into working memory - extract (3) from PetStore.drl</title>
-
-				<programlisting>// insert each item in the shopping cart into the Working Memory 
-rule "Explode Cart"
-    agenda-group "init"
-    auto-focus true    
-    salience 10
-    dialect "java"
-when
-    $order : Order( grossTotal == -1 )
-    $item : Purchase() from $order.items
-then
-   insert( $item );
-   drools.setFocus( "show items" );
-   drools.setFocus( "evaluate" );
-end
-
-</programlisting>
-			</example>
-
-			<para>This rule matches against all orders that do not yet have an Order.grossTotal calculated . It loops for each purchase item in that order. Some of the <emphasis role="italic">Explode Cart</emphasis> Rule should be familiar ; the rule name, the salience (suggesting of the order that the rules should be fired in) and the dialect set to <emphasis role="italic">java</emphasis>. There are three new items:</para>
-
-			<itemizedlist>
-				<listitem>
-					<para role="bold"><emphasis role="bold">agenda-group "init" </emphasis>- the name of the agenda group. In this case, there is only one rule in the group. However, nothing in Java code / nor a rule sets the focus to this group , so it relies on the next attibute for it's chance to fire.</para>
-				</listitem>
-
-				<listitem>
-					<para><emphasis role="bold">auto-focus true - </emphasis>This is the only rule in the sample, so when <emphasis role="italic">fireAllRules()</emphasis> is called from within the Java code, this rule is the first to get a chance to fire.</para>
-				</listitem>
-
-				<listitem>
-					<para><emphasis role="bold">drools.setFocus() </emphasis>This sets the focus to the <emphasis role="italic">show items </emphasis>and <emphasis role="italic">evaluate</emphasis> agenda groups in turn , giving their rules a chance to fire. In practice , we loop through all items on the order, inserting them into memory, then firing the other rules after each insert.</para>
-				</listitem>
-			</itemizedlist>
-
-			<para>The next two listings shows the rules within the <emphasis role="italic">show items </emphasis>and <emphasis role="italic">evaluate</emphasis> agenda groups. We look at them in the order that they are called.</para>
-				
-			<example>
-				<title>Show Items in the GUI extract (4) from PetStore.drl</title>
-
-				<programlisting>rule "Show Items"
-    agenda-group "show items"
-    dialect "mvel"
-when
-    $order : Order( )
-    $p : Purchase( order == $order )
-then
-   textArea.append( $p.product + "\n");
-end
-</programlisting>
-			</example>
-
-			<para>The <emphasis role="italic">show items</emphasis> agenda-group has only one rule, also called <emphasis role="italic">Show Items</emphasis> (note the difference in case). For each purchase on the order currently in the working memory (session) it logs details to the text area (at the bottom of the GUI). The <emphasis role="italic">textArea</emphasis> variable used to do this is one of the Global Variables we looked at earlier.</para>
-
-			<para>The <emphasis role="italic">evaluate</emphasis> Agenda group also gains focus from the <emphasis role="italic">explode cart </emphasis>rule above. This Agenda group has two rules (below) <emphasis role="italic">Free Fish Food Sample </emphasis> and <emphasis role="italic">Suggest Tank</emphasis>.</para>
-
-			<example>
-				<title>Evaluate Agenda Group extract (5) from PetStore.drl</title>
-
-				<programlisting>// Free Fish Food sample when we buy a Gold Fish if we haven't already  bought 
-// Fish Food and dont already have a Fish Food Sample
-rule "Free Fish Food Sample"
-    agenda-group "evaluate"
-    dialect "mvel"
-when
-    $order : Order()
-    not ( $p : Product( name == "Fish Food") &amp;&amp; Purchase( product == $p ) )
-    not ( $p : Product( name == "Fish Food Sample") &amp;&amp; Purchase( product == $p ) )
-    exists ( $p : Product( name == "Gold Fish") &amp;&amp; Purchase( product == $p ) )
-    $fishFoodSample : Product( name == "Fish Food Sample" );
-then
-    System.out.println( "Adding free Fish Food Sample to cart" );
-    purchase = new Purchase($order, $fishFoodSample);
-    insert( purchase );
-    $order.addItem( purchase ); 
-end
-
-// Suggest a tank if we have bought more than 5 gold fish and dont already have one
-rule "Suggest Tank"
-    agenda-group "evaluate"
-    dialect "java"
-when
-    $order : Order()
-    not ( $p : Product( name == "Fish Tank") &amp;&amp; Purchase( product == $p ) )
-    ArrayList( $total : size &gt; 5 ) from collect( Purchase( product.name == "Gold Fish" ) )
-    $fishTank : Product( name == "Fish Tank" )
-then
-    requireTank(frame, drools.getWorkingMemory(), $order, $fishTank, $total); 
-end
-</programlisting>
-			</example>
-      
-
-			<para>The <emphasis role="italic">Free Fish Food Sample</emphasis> rule will only fire if</para>
-
-			<itemizedlist>
-				<listitem>
-					<para>We <emphasis role="italic">don't </emphasis>already have any fish food.</para>
-				</listitem>
-
-				<listitem>
-					<para>We <emphasis role="italic">don't</emphasis> already have a free fish food sample.</para>
-				</listitem>
-
-				<listitem>
-					<para>We <emphasis role="italic">do</emphasis> have a Gold Fish in our order.</para>
-				</listitem>
-			</itemizedlist>
-
-			<para>If the rule does fire, it creates a new product (Fish Food Sample), and adds it to the Order in working memory.</para>
-
-			<para>The <emphasis role="italic">Suggest Tank</emphasis> rule will only fire if</para>
-
-			<itemizedlist>
-				<listitem>
-					<para>We <emphasis role="italic">don't </emphasis>already have a Fish Tank in our order</para>
-				</listitem>
-
-				<listitem>
-					<para>If we <emphasis role="italic">can</emphasis> find more than 5 Gold Fish Products in our order.</para>
-				</listitem>
-			</itemizedlist>
-
-			<para>If the rule does fire, it calls the <emphasis role="italic">requireTank</emphasis>() function that we looked at earlier (showing a Dialog to the user, and adding a Tank to the order / working memory if confirmed). When calling the <emphasis role="italic">requireTank</emphasis>() function the rule passes the global <emphasis role="italic">frame</emphasis> variable so that the function has a handle to the Swing GUI.</para>
-
-			<para>The next rule we look at is <emphasis role="italic">do checkout.</emphasis></para>
-				
-			<example>
-				<title>Doing the Checkout - extract (6) from PetStore.drl</title>
-
-				<programlisting>rule "do checkout"
-    dialect "java"
-    when
-    then
-        doCheckout(frame, drools.getWorkingMemory());
-end</programlisting>
-			</example>
-
-			<para>The <emphasis role="italic">do checkout</emphasis> rule has <emphasis role="bold">no agenda-group set and no auto-focus attribute</emphasis>. As such, is is deemed part of the default (MAIN) agenda-group - the same as the other non PetStore examples where agenda groups are not used. This group gets focus by default when all the rules/agenda-groups that explicity had focus set to them have run their course.</para>
-
-			<para>There is no LHS to the rule, so the RHS will always call the <emphasis role="italic">doCheckout</emphasis>() function. When calling the <emphasis role="italic">doCheckout</emphasis>() function the rule passes the global <emphasis role="italic">frame</emphasis> variable so the function has a handle to the Swing GUI. As we saw earlier, the <emphasis role="italic">doCheckout</emphasis>() function shows a confirmation dialog to the user. If confirmed, the function sets the focus to the <emphasis role="italic">checkout</emphasis> agenda-group, allowing the next lot of rules to fire.</para>
-
-			<example>
-				<title>Checkout Rules- extract (7) from PetStore.drl</title>
-
-				<programlisting>rule "Gross Total"
-    agenda-group "checkout"
-    dialect "mvel"
-when
-   $order : Order( grossTotal == -1)
-   Number( total : doubleValue ) from accumulate( Purchase( $price : product.price ),
-                 sum( $price ) )
-then
-    modify( $order ) { grossTotal = total };
-    textArea.append( "\ngross total=" + total + "\n" );
-end
-
-rule "Apply 5% Discount"
-    agenda-group "checkout"
-dialect "mvel"
-when
-   $order : Order( grossTotal &gt;= 10 &amp;&amp; &lt; 20 )
-then
-   $order.discountedTotal = $order.grossTotal * 0.95;
-   textArea.append( "discountedTotal total=" + $order.discountedTotal + "\n" );
-end
-
-
-rule "Apply 10% Discount"
-    agenda-group "checkout"
-dialect "mvel"
-when
-   $order : Order( grossTotal &gt;= 20 )
-then
-   $order.discountedTotal = $order.grossTotal * 0.90;
-   textArea.append( "discountedTotal total=" + $order.discountedTotal + "\n" );
-end
-</programlisting>
-			</example>
-
-			<para>There are three rules in the <emphasis role="italic">checkout</emphasis> agenda-group</para>
-
-			<itemizedlist>
-				<listitem>
-					<para><emphasis role="bold">Gross Total </emphasis> - if we haven't already calculated the gross total, accumulates the product prices into a total, puts this total into working memory, and displays it via the Swing TextArea (using the <emphasis role="italic">textArea </emphasis>global variable yet again).</para>
-				</listitem>
-
-				<listitem>
-					<para><emphasis role="bold">Apply 5% Discount</emphasis> - if our gross total is between 10 and 20, then calculate the discounted total and add it to working memory / display in the text area.</para>
-				</listitem>
-
-				<listitem>
-					<para><emphasis role="bold">Apply 10% Discount</emphasis> - if our gross total is equal to or greater than 20, calculate the discounted total and add it to working memory / display in the text area.</para>
-				</listitem>
-			</itemizedlist>
-			
-			<para>Now we've run through what happens in the code, lets have a look at what happens when we run the code for real. The <emphasis role="italic">PetStore.java </emphasis>example contains a <emphasis role="italic">main()</emphasis> method, so it can be run as a standard Java application (either from the command line or via the IDE). This assumes you have your classpath set correctly (see the start of the examples section for more information).</para>
-
-			<para>The first screen that we see is the Pet Store Demo. It has a List of available products (top left) , an empty list of selected products (top right), checkout and reset buttons (middle) and an empty system messages area (bottom).</para>
-
-			<figure>
-				<title>Figure 1 - PetStore Demo just after Launch</title>
-
-				<mediaobject>
-					<imageobject>
-						<imagedata fileref="1-PetStore-Start-Screen.png" />
-					</imageobject>
-				</mediaobject>
-			</figure>
-			
-			<para>To get to this point, the following things have happened:</para>
-
-			<orderedlist>
-				<listitem>
-					<para>The <emphasis role="italic">main()</emphasis> method has run and loaded the RuleBase <emphasis role="bold">but not yet fired the rules</emphasis>. This is the only rules related code to run so far.</para>
-				</listitem>
-
-				<listitem>
-					<para>A new <emphasis role="italic">PetStoreUI</emphasis> class is created and given a handle to the RuleBase (for later use).</para>
-				</listitem>
-
-				<listitem>
-					<para>Various Swing Components do their stuff, and the above screen is shown and <emphasis role="bold">waits for user input</emphasis>.</para>
-				</listitem>
-			</orderedlist>
-			
-			<para>Clicking on various products from the list might give you a screen similar to the one below.</para>
-
-			<figure>
-				<title>Figure 2 - PetStore Demo with Products Selected</title>
-
-				<mediaobject>
-					<imageobject>
-						<imagedata fileref="2-stock-added-to-order-list.png" />
-					</imageobject>
-				</mediaobject>
-			</figure>
-			
-			<para>Note that <emphasis role="bold">no rules code has been fired here</emphasis>. This is only swing code, listening for the mouse click event, and added the clicked product to the <emphasis>TableModel</emphasis> object for display in the top right hand section (as an aside , this is a classic use of the Model View Controller - MVC - design pattern).</para>
-
-			<para>It is only when we press the <emphasis role="bold">Checkout</emphasis> that we fire our business rules, in roughly the same order that we walked through the code earlier.</para>
-
-			<orderedlist>
-				<listitem>
-					<para>The <emphasis role="italic">CheckOutCallBack.checkout()</emphasis> method is called (eventually) by the Swing class waiting for the click on the checkout button. This inserts the data from the <emphasis>TableModel</emphasis> object (top right hand side of the GUI), and handles from the GUI into the session / working memory. It then fires the rules.</para>
-				</listitem>
-
-				<listitem>
-					<para>The <emphasis role="italic">Explode Cart</emphasis> rule is the first to fire, given that has <emphasis role="italic">auto-focus </emphasis>set to true. It loops through all the products in the cart, makes sure the products are in the working memory, then gives the <emphasis role="italic">Show Items</emphasis> and <emphasis role="italic">Evaluation</emphasis> agenda groups a chance to fire. The rules in these groups, add the contents of the cart to the text area (bottom), decide whether or not to give us free fish food and whether to ask if we want to buy a fish tank (Figure 3 below).</para>
-				</listitem>
-			</orderedlist>
-
-			<figure>
-				<title>Figure 3 - Do we want to buy a fish tank?</title>
-
-				<mediaobject>
-					<imageobject>
-						<imagedata fileref="3-purchase-suggestion.png" />
-					</imageobject>
-				</mediaobject>
-			</figure>
-
-			<orderedlist>
-				<listitem>
-					<para>The <emphasis role="italic">Do Checkout</emphasis> rule is the next to fire as it (a) No other agenda group currently has focus and (b) it is part of the default (MAIN) agenda group. It always calls the<emphasis role="italic"> doCheckout() function </emphasis>which displays a 'Would you like to Checkout?' Dialog Box.</para>
-				</listitem>
-
-				<listitem>
-					<para>The <emphasis role="italic">doCheckout() function</emphasis> sets the focus to the <emphasis role="italic">checkout </emphasis>agenda-group, giving the rules in that group the option to fire.</para>
-				</listitem>
-
-				<listitem>
-					<para>The rules in the the <emphasis role="italic">checkout</emphasis> agenda-group, display the contents of the cart and apply the appropriate discount.</para>
-				</listitem>
-
-				<listitem>
-					<para><emphasis role="bold">Swing then waits for user input</emphasis> to either checkout more products (and to cause the rules to fire again) or to close the GUI - Figure 4 below.</para>
-				</listitem>
-			</orderedlist>
-
-			<figure>
-				<title>Figure 4 - Petstore Demo after all rules have fired.</title>
-
-				<mediaobject>
-					<imageobject>
-						<imagedata fileref="4-Petstore-final-screen.png" />
-					</imageobject>
-				</mediaobject>
-			</figure>
-
-			<para>Should we choose, we could add more System.out calls to demonstrate this flow of events. The current output of the console of the above sample is as per the listing below.</para>
-	
-			<example>
-				<title>Console (System.out) from running the PetStore GUI</title>
-
-				<programlisting>Adding free Fish Food Sample to cart 
-SUGGESTION: Would you like to buy a tank for your 6 fish? - Yes</programlisting>
-			</example>
-     
-
-			<!---<para>Todo : Add Audit and Agenda Views for this sample.</para>-->
-		</section>
-
-    <xi:include href="Section-HonestPoliticianExample.xml" />
-    
-    <xi:include href="Section-SodukiExample.xml" />
-    
-    <xi:include href="Section-NumberGuessExample.xml" />
-
-
-  <section>
-    <title>Miss Manners and Benchmarking</title>
-
-    <programlisting><emphasis role="bold">Name:</emphasis> Miss Manners
-<emphasis role="bold">Main class:</emphasis> org.drools.benchmark.manners.MannersBenchmark
-<emphasis role="bold">Type:</emphasis> java application
-<emphasis role="bold">Rules file:</emphasis> manners.drl
-<emphasis role="bold">Objective:</emphasis> Advanced walkthrough on the Manners benchmark, covers Depth conflict resolution in depth.</programlisting>
-
-    <section>
-      <title>Introduction</title>
-
-      <para>Miss Manners is throwing a party and being the good host she wants
-      to arrange good seating. Her initial design arranges everyone in male
-      female pairs, but then she worries about people have things to talk
-      about; what is a good host to do? So she decides to note the hobby of
-      each guest so she can then arrange guests in not only male and female
-      pairs but also ensure that a guest has someone to talk about a common
-      hobby, from either their left or right side.</para>
-
-      <figure>
-        <title>Miss Manners' Guests</title>
-
-        <mediaobject>
-
-          <imageobject>
-            <imagedata align="center" fileref="guests_at_table.png"
-                       format="PNG" scalefit="1" />
-          </imageobject>
-        </mediaobject>
-      </figure>
-
-      <section>
-        <title>BenchMarking</title>
-
-        <para>5 benchmarks were established in the 1991 paper "Effects of
-        Database Size on Rule System Performance: Five Case Studies" by Brant,
-        Timothy Grose, Bernie Lofaso, &amp; Daniel P. Miranker.</para>
-
-        <itemizedlist>
-          <listitem>
-            <para>Manners</para>
-
-            <itemizedlist>
-              <listitem>
-                <para>Uses a depth-first search approach to determine the
-                seating arrangements of boy/girl and one common hobby for
-                dinner guests</para>
-              </listitem>
-            </itemizedlist>
-          </listitem>
-
-          <listitem>
-            <para>Waltz</para>
-
-            <itemizedlist>
-              <listitem>
-                <para>line labeling for simple scenes by constraint
-                propagation</para>
-              </listitem>
-            </itemizedlist>
-          </listitem>
-
-          <listitem>
-            <para>WaltzDB</para>
-
-            <itemizedlist>
-              <listitem>
-                <para>More general version of Walts to be able to adapt to a
-                database of facts</para>
-              </listitem>
-            </itemizedlist>
-          </listitem>
-
-          <listitem>
-            <para>ARP</para>
-
-            <itemizedlist>
-              <listitem>
-                <para>Route planner for a robotic air vehicle using the A*
-                search algorithm</para>
-              </listitem>
-            </itemizedlist>
-          </listitem>
-
-          <listitem>
-            <para>Weavera</para>
-
-            <itemizedlist>
-              <listitem>
-                <para>VLSI router for channels and boxes using a black-board
-                technique</para>
-              </listitem>
-            </itemizedlist>
-          </listitem>
-        </itemizedlist>
-
-        <para>Manners has become the de facto rule engine benchmark; however
-        it's behavior is now well known and many engines optimize for this
-        thus negating its usefulness as a benchmark which is why Waltz is
-        becoming more favorable. These 5 benchmarks are also published at the
-        University of Texas <ulink
-        url="http://www.cs.utexas.edu/ftp/pub/ops5-benchmark-suite/">http://www.cs.utexas.edu/ftp/pub/ops5-benchmark-suite/</ulink>.</para>
-      </section>
-
-      <section>
-        <title>Miss Manners Execution Flow</title>
-
-        <para>After the first Seating arrangement has been assigned a
-        depth-first recursion occurs which repeatedly assigns correct Seating
-        arrangements until the last seat is assigned. Manners uses a Context
-        instance to control execution flow; the activity diagram is
-        partitioned to show the relation of the rule execution to the current
-        Context state.</para>
-
-        <figure>
-          <title>Manners Activity Diagram</title>
-
-          <mediaobject>
-
-            <imageobject>
-		    <imagedata align="center" fileref="manners_activity_diagram.png"
-                         format="PNG" scalefit="1" />
-            </imageobject>
-          </mediaobject>
-        </figure>
-      </section>
-
-      <section>
-        <title>The Data and Results</title>
-
-        <para>Before going deeper into the rules lets first take a look at the
-        asserted data and the resulting Seating arrangement. The data is a
-        simple set of 5 guests who should be arranged in male/female pairs
-        with common hobbies.</para>
-
-        <para><emphasis role="bold">The Data</emphasis></para>
-
-        <para>Each line of the results list is printed per execution of the
-        “Assign Seat” rule. They key bit to notice is that each line has pid
-        one greater than the last, the significance of this will be explained
-        in t he “Assign Seating” rule description. The 'l' and the 'r' refer
-        to the left and right, 's' is sean and 'n' is the guest name. In my
-        actual implementation I used longer notation, 'leftGuestName', but
-        this is not practice in a printed article. I found the notation of
-        left and right preferable to the original OPS5 '1' and '2</para>
-
-        <literallayout>(guest (name n1) (sex m) (hobby  h1)  )
-(guest (name n2) (sex f) (hobby  h1)  )
-(guest (name n2) (sex f) (hobby  h3)  )
-(guest (name n3) (sex m) (hobby  h3)  )
-(guest (name n4) (sex m) (hobby  h1)  )
-(guest (name n4) (sex f) (hobby  h2)  )
-(guest (name n4) (sex f) (hobby  h3)  )
-(guest (name n5) (sex f) (hobby  h2)  )
-(guest (name n5) (sex f) (hobby  h1)  )
-(last_seat (seat 5)  )</literallayout>
-
-        <para><emphasis role="bold">The Results</emphasis></para>
-
-        <literallayout>[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5] 
-[Seating id=2, pid=1, done=false, ls=1, ln=n5, rs=2, rn=n4] 
-[Seating id=3, pid=2, done=false, ls=2, ln=n4, rs=3, rn=n3] 
-[Seating id=4, pid=3, done=false, ls=3, rn=n3, rs=4, rn=n2] 
-[Seating id=5, pid=4, done=false, ls=4, ln=n2, rs=5, rn=n1]</literallayout>
-      </section>
-    </section>
-
-    <section>
-      <title>Indepth look</title>
-
-      <section>
-        <title>Cheating</title>
-
-        <para>Manners has been around a long time and is a contrived benchmark
-        meant to exercise the cross product joins and agenda, many people not
-        understanding this tweak the example to achieve better performance,
-        making their use of the Manners benchmark pointless. Known cheats to
-        Miss Manners are:</para>
-
-        <itemizedlist>
-          <listitem>
-            <para>Using arrays for a guests hobbies, instead of asserting each
-            one as a single fact. This massively reduces the cross
-            products.</para>
-          </listitem>
-
-          <listitem>
-            <para>The altering of the sequence of data can also reducing the
-            amount of matching increase execution speed</para>
-          </listitem>
-
-          <listitem>
-            <para>Changing NOT CE (conditional element) such that the test
-            algorithm only uses the "first-best-match". Basically, changing
-            the test algorithm to backward chaining. the results are only
-            comparable to other backward chaining rule engines or ports of
-            Manners.</para>
-          </listitem>
-
-          <listitem>
-            <para>Removing the context so the rule engine matches the guests
-            and seats pre-maturely. A proper port will prevent facts from
-            matching using the context start.</para>
-          </listitem>
-
-          <listitem>
-            <para>Any change which prevents the rule engine from performing
-            combinatorial pattern matching</para>
-          </listitem>
-
-          <listitem>
-            <para>If no facts are retracted in the reasoning cycle, as a
-            result of NOT CE, the port is incorrect.</para>
-          </listitem>
-        </itemizedlist>
-      </section>
-
-      <section>
-        <title>Conflict Resolution</title>
-
-        <para>Manners benchmark was written for OPS5 which has two conflict
-        resolution strategies, LEX and MEA; LEX is a chain of several
-        strategies including Salience, Recency, Complexity. The Recency part
-        of the strategy drives the depth first (LIFO) firing order. The Clips
-        manual documents the recency strategy as:</para>
-
-        <blockquote>
-          <attribution>Clips Reference Manual</attribution>
-
-          <para>Every fact and instance is marked internally with a “time tag”
-          to indicate its relative recency with respect to every other fact
-          and instance in the system. The pattern entities associated with
-          each rule activation are sorted in descending order for determining
-          placement. An activation with a more recent pattern entities is
-          placed before activations with less recent pattern entities. To
-          determine the placement order of two activations, compare the sorted
-          time tags of the two activations one by one starting with the
-          largest time tags. The comparison should continue until one
-          activation’s time tag is greater than the other activation’s
-          corresponding time tag. The activation with the greater time tag is
-          placed before the other activation on the agenda. If one activation
-          has more pattern entities than the other activation and the compared
-          time tags are all identical, then the activation with more time tags
-          is placed before the other activation on the agenda.</para>
-        </blockquote>
-
-        <para>However Jess and Clips both use the Depth strategy, which is
-        simpler and lighter, which Drools also adopted. The Clips manual
-        documents the Depth strategy as:</para>
-
-        <blockquote>
-          <attribution>Clips Reference Manual</attribution>
-
-          <para>Newly activated rules are placed above all rules of the same
-          salience. For example, given that fact-a activates rule-1 and rule-2
-          and fact-b activates rule-3 and rule-4, then if fact-a is asserted
-          before fact-b, rule-3 and rule-4 will be above rule-1 and rule-2 on
-          the agenda. However, the position of rule-1 relative to rule-2 and
-          rule-3 relative to rule-4 will be arbitrary.</para>
-        </blockquote>
-
-        <para>The initial Drools implementation for the Depth strategy would
-        not work for manners without the use of salience on the "make_path"
-        rule, the Clips support team had this to say:</para>
-
-        <blockquote>
-          <attribution>Clips Support Forum</attribution>
-
-          <para>The default conflict resolution strategy for CLIPS, depth, is
-          different than the default conflict resolution strategy used by
-          OPS5. Therefore if you directly translate an OPS5 program to CLIPS,
-          but use the default depth conflict resolution strategy, you're only
-          likely to get the correct behavior by coincidence. The lex and mea
-          conflict resolution strategies are provided in CLIPS to allow you to
-          quickly convert and correctly run an OPS5 program in CLIPS</para>
-        </blockquote>
-
-        <para>Investigation into the Clips code reveals there is undocumented
-        functionality in the Depth strategy. There is an accumulated time tag
-        used in this strategy; it's not an extensively fact by fact comparison
-        as in the recency strategy, it simply adds the total of all the time
-        tags for each activation and compares.</para>
-      </section>
-
-      <section>
-        <title>Assign First Seat</title>
-
-        <para>Once the context is changed to START_UP Activations are created
-        for all asserted Guests; because all Activations are created as the
-        result of a single Working Memory action, they all have the same
-        Activation time tag. The last asserted Guest would have a higher fact
-        time tag and its Activation would fire, becuase it has the highest
-        accumulated fact time tag. The execution order in this rule has little
-        importance, but has a big impact in the rule "Assign Seat". The
-        Activation fires and asserts the first Seating arrangement, a Path and
-        then sets the Context's state to create Activation for "Assign
-        Seat".</para>
-
-        <programlisting>rule assignFirstSeat
-    when
-        context : Context( state == Context.START_UP )
-        guest : Guest()
-        count : Count()
-    then
-        String guestName = guest.getName();        
-
-        insert( new Seating( count.getValue(), 1, true, 1, guestName, 1, guestName) );        
-        insert( new Path( count.getValue(), 1, guestName ) );        
-
-        count.setValue(  count.getValue() + 1 );        
-        update( count );
-        context.setState( Context.ASSIGN_SEATS );       
-        update( context );
-end</programlisting>
-      </section>
-
-      <section>
-        <title>Assign Seat</title>
-
-        <para>This rule determines each of the Seating arrangements. The Rule
-        creates cross product solutions for ALL asserted Seating arrangements
-        against ALL the asserted guests; accept against itself or any already
-        assigned Chosen solutions.</para>
-
-        <programlisting>rule findSeating
-   when 
-       context : Context( state == Context.ASSIGN_SEATS )
-       $s      : Seating( pathDone == true )
-       $g1     : Guest( name == $s.rightGuestName )
-       $g2     : Guest( sex != $g1.sex, hobby == $g1.hobby )
-       count   : Count()
-       not ( Path( id == $s.id, guestName == $g2.name) )
-       not ( Chosen( id == $s.id, guestName == $g2.name, hobby == $g1.hobby) )
-   then
-       int rightSeat = $s.getRightSeat();
-       int seatId = $s.getId();
-       int countValue = count.getValue();
-       
-       insert( new Seating( countValue, seatId, false, rightSeat, $s.getRightGuestName(), rightSeat + 1, $g2.getName() ) );                                
-       insert( new Path( countValue, rightSeat + 1, $g2.getName() ) );       
-       insert( new Chosen( seatId, $g2.getName(), $g1.getHobby() ) );
-
-       count.setValue(  countValue + 1 );
-       update( count );       
-       context.setState( Context.MAKE_PATH );
-       update( context );
-end</programlisting>
-
-        <para>However, as can be seen from the printed results shown earlier,
-        it is essential that only the Seating with the highest pid cross
-        product be chosen – yet how can this be possible if we have
-        Activations, of the same time tag, for nearly all existing Seating and
-        Guests. For example on the third iteration of "Assing Seat" these are
-        the produced Activations, remember this is from a very small data set
-        and with larger data sets there would be many more possible Activated
-        Seating solutions, with multiple solutions per pid:</para>
-
-        <literallayout>=&gt;[ActivationCreated(35): rule=findSeating 
-[fid:19:33]:[Seating id=3, pid=2, done=true, ls=2, ln=n4, rs=3, rn=n3] 
-[fid:4:4]:[Guest name=n3, sex=m, hobbies=h3] 
-[fid:3:3]:[Guest name=n2, sex=f, hobbies=h3]
-
-=&gt;[ActivationCreated(35): rule=findSeating 
-[fid:15:23]:[Seating id=2, pid=1, done=true, ls=1, ln=n5, rs=2, rn=n4] 
-[fid:5:5]:[Guest name=n4, sex=m, hobbies=h1] 
-[fid:2:2]:[Guest name=n2, sex=f, hobbies=h1] 
-
-=&gt;[ActivationCreated(35): rule=findSeating 
-[fid:13:13]:[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5] 
-[fid:9:9]:[Guest name=n5, sex=f, hobbies=h1] 
-[fid:1:1]:[Guest name=n1, sex=m, hobbies=h1]</literallayout>
-
-        <para>The creation of all these redundant Activations might seem
-        pointless, but it must be remembered that Manners is not about good
-        rule design; it's purposefully designed as a bad ruleset to fully
-        stress test the cross product matching process and the agenda, which
-        this clearly does. Notice that each Activation has the same time tag
-        of 35, as they were all activated by the change in Context to
-        ASSIGN_SEATS. With OPS5 and LEX it would correctly fire the Activation
-        with the last asserted Seating. With Depth the accumulated fact time
-        tag ensures the Activation with the last asserted Seating
-        fires.</para>
-      </section>
-
-      <section>
-        <title>Make Path and Path Done</title>
-
-        <para>"Make Path" must always fires before "Path Done". A Path is
-        asserted for each Seating arrangement up to the last asserted Seating.
-        Notice that "Path Done" is a subset of "Make Path", so how do we
-        ensure that "Make Path" fires first?</para>
-
-        <programlisting>rule makePath
-    when 
-        Context( state == Context.MAKE_PATH )
-        Seating( seatingId:id, seatingPid:pid, pathDone == false )
-        Path( id == seatingPid, pathGuestName:guestName, pathSeat:seat )
-        not Path( id == seatingId, guestName == pathGuestName )
-    then
-        insert( new Path( seatingId, pathSeat, pathGuestName ) );
-end</programlisting>
-
-        <programlisting>rule pathDone
-    when
-        context : Context( state == Context.MAKE_PATH ) 
-        seating : Seating( pathDone == false ) 
-    then
-        seating.setPathDone( true ); 
-        update( seating );
-        
-        context.setState( Context.CHECK_DONE ); 
-        update( context );
-end</programlisting>
-
-        <figure>
-          <title>Rete Diagram</title>
-
-          <mediaobject>
-
-            <imageobject>
-		    <imagedata align="center" fileref="make_path.png" format="PNG"
-                         scalefit="1" />
-            </imageobject>
-          </mediaobject>
-        </figure>
-
-        <para>Both rules end up on the Agenda in conflict and with identical
-        activation time tags, however the accumulate fact time tag is greater
-        for "Make Path" so it gets priority.</para>
-      </section>
-
-      <section>
-        <title>Continue and Are We Done</title>
-
-        <para>"Are We Done" only activates when the last seat is assigned, at
-        which point both rules will be activated. For the same reason that
-        "Make Path" always wins over "Path Done" "Are We Done" will take
-        priority over "Continue".</para>
-
-        <programlisting>rule areWeDone
-    when
-        context : Context( state == Context.CHECK_DONE ) 
-        LastSeat( lastSeat: seat )
-        Seating( rightSeat == lastSeat ) 
-    then
-        context.setState(Context.PRINT_RESULTS ); 
-        update( context );
-end
-</programlisting>
-
-        <programlisting>rule continue
-    when
-        context : Context( state == Context.CHECK_DONE ) 
-    then
-        context.setState( Context.ASSIGN_SEATS ); 
-        update( context );
-end
-</programlisting>
-      </section>
-    </section>
-
-    <section>
-      <title>Output Summary</title>
-
-      <literallayout><emphasis role="bold">Assign First seat</emphasis>
-=&gt;[fid:13:13]:[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5]
-=&gt;[fid:14:14]:[Path id=1, seat=1, guest=n5]
-
-==&gt;[ActivationCreated(16): rule=findSeating
-[fid:13:13]:[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5]
-[fid:9:9]:[Guest name=n5, sex=f, hobbies=h1]
-[fid:1:1]:[Guest name=n1, sex=m, hobbies=h1]
-
-==&gt;[ActivationCreated(16): rule=findSeating
-[fid:13:13]:[Seating id=1 , pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5]
-[fid:9:9]:[Guest name=n5, sex=f, hobbies=h1]
-[fid:5:5]:[Guest name=n4, sex=m, hobbies=h1]*
-
-<emphasis role="bold">Assign Seating</emphasis>
-=&gt;[fid:15:17] :[Seating id=2 , pid=1 , done=false, ls=1, lg=n5, rs=2, rn=n4]
-=&gt;[fid:16:18]:[Path id=2, seat=2, guest=n4]
-=&gt;[fid:17:19]:[Chosen id=1, name=n4, hobbies=h1]
-
-=&gt;[ActivationCreated(21): rule=makePath 
-[fid:15:17] : [Seating id=2, pid=1, done=false, ls=1, ln=n5, rs=2, rn=n4]
-[fid:14:14] : [Path id=1, seat=1, guest=n5]*
-
-==&gt;[ActivationCreated(21): rule=pathDone
-[Seating id=2, pid=1, done=false, ls=1, ln=n5, rs=2, rn=n4]*
-
-<emphasis role="bold">Make Path</emphasis>
-=&gt;[fid:18:22:[Path id=2, seat=1, guest=n5]]
-
-<emphasis role="bold">Path Done</emphasis>
-
-<emphasis role="bold">Continue Process</emphasis>
-=&gt;[ActivationCreated(25): rule=findSeating
-[fid:15:23]:[Seating id=2, pid=1, done=true, ls=1, ln=n5, rs=2, rn=n4]
-[fid:7:7]:[Guest name=n4, sex=f, hobbies=h3]
-[fid:4:4] : [Guest name=n3, sex=m, hobbies=h3]*
-
-=&gt;[ActivationCreated(25): rule=findSeating
-[fid:15:23]:[Seating id=2, pid=1, done=true, ls=1, ln=n5, rs=2, rn=n4]
-[fid:5:5]:[Guest name=n4, sex=m, hobbies=h1]
-[fid:2:2]:[Guest name=n2, sex=f, hobbies=h1], [fid:12:20] : [Count value=3]
-
-=&gt;[ActivationCreated(25): rule=findSeating
-[fid:13:13]:[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5]
-[fid:9:9]:[Guest name=n5, sex=f, hobbies=h1]
-[fid:1:1]:[Guest name=n1, sex=m, hobbies=h1]
-
-<emphasis role="bold">Assign Seating</emphasis>
-=&gt;[fid:19:26]:[Seating id=3, pid=2, done=false, ls=2, lnn4, rs=3, rn=n3]]
-=&gt;[fid:20:27]:[Path id=3, seat=3, guest=n3]]
-=&gt;[fid:21:28]:[Chosen id=2, name=n3, hobbies=h3}]
-
-=&gt;[ActivationCreated(30): rule=makePath
-[fid:19:26]:[Seating id=3, pid=2, done=false, ls=2, ln=n4, rs=3, rn=n3]
-[fid:18:22]:[Path id=2, seat=1, guest=n5]*
-
-=&gt;[ActivationCreated(30): rule=makePath 
-[fid:19:26]:[Seating id=3, pid=2, done=false, ls=2, ln=n4, rs=3, rn=n3]
-[fid:16:18]:[Path id=2, seat=2, guest=n4]*
-
-=&gt;[ActivationCreated(30): rule=done 
-[fid:19:26]:[Seating id=3, pid=2, done=false, ls=2, ln=n4, rs=3, rn=n3]*
-
-<emphasis role="bold">Make Path</emphasis>
-=&gt;[fid:22:31]:[Path id=3, seat=1, guest=n5]
-
-<emphasis role="bold">Make Path </emphasis>
-=&gt;[fid:23:32] [Path id=3, seat=2, guest=n4]
-
-<emphasis role="bold">Path Done</emphasis>
-
-<emphasis role="bold">Continue Processing</emphasis>
-=&gt;[ActivationCreated(35): rule=findSeating
-[fid:19:33]:[Seating id=3, pid=2, done=true, ls=2, ln=n4, rs=3, rn=n3]
-[fid:4:4]:[Guest name=n3, sex=m, hobbies=h3]
-[fid:3:3]:[Guest name=n2, sex=f, hobbies=h3], [fid:12:29]*
-
-=&gt;[ActivationCreated(35): rule=findSeating 
-[fid:15:23]:[Seating id=2, pid=1, done=true, ls=1, ln=n5, rs=2, rn=n4] 
-[fid:5:5]:[Guest name=n4, sex=m, hobbies=h1]
-[fid:2:2]:[Guest name=n2, sex=f, hobbies=h1]
-
-=&gt;[ActivationCreated(35): rule=findSeating 
-[fid:13:13]:[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5] 
-[fid:9:9]:[Guest name=n5, sex=f, hobbies=h1], [fid:1:1] : [Guest name=n1, sex=m, hobbies=h1]
-
-<emphasis role="bold">Assign Seating</emphasis>
-=&gt;[fid:24:36]:[Seating id=4, pid=3, done=false, ls=3, ln=n3, rs=4, rn=n2]]
-=&gt;[fid:25:37]:[Path id=4, seat=4, guest=n2]]
-=&gt;[fid:26:38]:[Chosen id=3, name=n2, hobbies=h3]
-
-==&gt;[ActivationCreated(40): rule=makePath 
-[fid:24:36]:[Seating id=4, pid=3, done=false, ls=3, ln=n3, rs=4, rn=n2]
-[fid:23:32]:[Path id=3, seat=2, guest=n4]*
-
-==&gt;[ActivationCreated(40): rule=makePath 
-[fid:24:36]:[Seating id=4, pid=3, done=false, ls=3, ln=n3, rs=4, rn=n2] 
-[fid:20:27]:[Path id=3, seat=3, guest=n3]*
-
-=&gt;[ActivationCreated(40): rule=makePath 
-[fid:24:36]:[Seating id=4, pid=3, done=false, ls=3, ln=n3, rs=4, rn=n2]
-[fid:22:31]:[Path id=3, seat=1, guest=n5]*
-
-=&gt;[ActivationCreated(40): rule=done 
-[fid:24:36]:[Seating id=4, pid=3, done=false, ls=3, ln=n3, rs=4, rn=n2]*
-
-<emphasis role="bold">Make Path </emphasis>
-=&gt;fid:27:41:[Path id=4, seat=2, guest=n4]
-
-<emphasis role="bold">Make Path</emphasis>
-=&gt;fid:28:42]:[Path id=4, seat=1, guest=n5]]
-
-<emphasis role="bold">Make Path</emphasis>
-=&gt;fid:29:43]:[Path id=4, seat=3, guest=n3]]
-
-<emphasis role="bold">Path Done</emphasis>
-
-<emphasis role="bold">Continue  Processing</emphasis>
-=&gt;[ActivationCreated(46): rule=findSeating 
-[fid:15:23]:[Seating id=2, pid=1, done=true, ls=1, ln=n5, rs=2, rn=n4] 
-[fid:5:5]:[Guest name=n4, sex=m, hobbies=h1], [fid:2:2]
-[Guest name=n2, sex=f, hobbies=h1]
-
-=&gt;[ActivationCreated(46): rule=findSeating 
-[fid:24:44]:[Seating id=4, pid=3, done=true, ls=3, ln=n3, rs=4, rn=n2]
-[fid:2:2]:[Guest name=n2, sex=f, hobbies=h1]
-[fid:1:1]:[Guest name=n1, sex=m, hobbies=h1]*
-
-=&gt;[ActivationCreated(46): rule=findSeating 
-[fid:13:13]:[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5]
-[fid:9:9]:[Guest name=n5, sex=f, hobbies=h1]
-[fid:1:1]:[Guest name=n1, sex=m, hobbies=h1]
-
-<emphasis role="bold">Assign Seating</emphasis>
-=&gt;[fid:30:47]:[Seating id=5, pid=4, done=false, ls=4, ln=n2, rs=5, rn=n1]
-=&gt;[fid:31:48]:[Path id=5, seat=5, guest=n1]
-=&gt;[fid:32:49]:[Chosen id=4, name=n1, hobbies=h1]
-</literallayout>
-    </section>
-  </section>
-
-  <section>
-    <title>Conways Game Of Life Example</title>
-
-    <programlisting><emphasis role="bold">Name:</emphasis> Conways Game Of Life
-<emphasis role="bold">Main class:</emphasis> org.drools.examples.conway.ConwayAgendaGroupRun org.drools.examples.conway.ConwayRuleFlowGroupRun
-<emphasis role="bold">Type:</emphasis> java application
-<emphasis role="bold">Rules file:</emphasis> conway-ruleflow.drl conway-agendagroup.drl
-<emphasis role="bold">Objective:</emphasis> Demonstrates 'accumulate', 'collect' and 'from'</programlisting>
-
-    <para>Conway's Game Of Life, <ulink
-    url="http://en.wikipedia.org/wiki/Conway's_Game_of_Life">http://en.wikipedia.org/wiki/Conway's_Game_of_Life</ulink>
-    <ulink
-    url="http://www.math.com/students/wonders/life/life.html">http://www.math.com/students/wonders/life/life.html</ulink>,
-    is a famous cellular automaton conceived in the early 1970's by
-    mathematician John Conway. While the system is well known as "Conway's
-    Game Of Life", it really isn't a game at all. Conway's system is more like
-    a life simulation. Don't be intimidated. The system is terribly simple and
-    terribly interesting. Math and Computer Science students alike have
-    marvelled over Conway's system for more than 30 years now. The application
-    represented here is a Swing based implementation of Conway's Game of Life.
-    The rules that govern the system are implemented as business rules using
-    Drools. This document will explain the rules that drive the simulation and
-    discuss the Drools specific parts of the implementation.</para>
-
-    <para>We'll first introduce the grid view, shown below, to help
-    visualisation of the problem; this is where the life simuation takes
-    place. Initially the grid is empty, meaning that there are no live cells
-    in the system; ech cell can be considered "LIVE" or "DEAD", live cells
-    have a green ball in them. Pre-selected patterns of live cells can be
-    selected from the "Pattern" drop down or cells can be doubled-clicked to
-    toggle them between LIVE and DEAD. It's important to understand that each
-    cell is related to it's neighbour cells, which is a core part of the
-    game's rules and will be explained in a moment. Neighbors include not only
-    cells to the left, right, top and bottom but also cells that are connected
-    diagonally. Each cell has a total of 8 neighbors except the 4 corner cells
-    and all of the other cells along the 4 edges. Corner cells have 3
-    neighbors and other edge cells have 5 neighbors.</para>
-
-    <figure>
-      <title>Conways Example : Starting a new game</title>
-
-      <mediaobject>
-        <imageobject>
-		<imagedata fileref="conway1.png" />
-        </imageobject>
-      </mediaobject>
-    </figure>
-
-    <para>So what are the basic rules that govern this game? Each generation,
-    i.e. completion iteration and evalution of all cells, the system evolves
-    and cells may be born or killed, there are a very simple set of rules that
-    govern what the next generation will look like.</para>
-
-    <itemizedlist>
-      <listitem>
-        <para>If a live cell has fewer than 2 live neighbors, it dies of
-        loneliness</para>
-      </listitem>
-
-      <listitem>
-        <para>If a live cell has more than 3 live neighbors, it dies from
-        overcrowding</para>
-      </listitem>
-
-      <listitem>
-        <para>If a dead cell has exactly 3 live neighbors, it comes to
-        life</para>
-      </listitem>
-    </itemizedlist>
-
-    <para>That is all there is to it. Any cell that doesn't meet any of those
-    criteria is left as is for the next generation. With those simple rules in
-    mind, go back and play with the system a little bit more and step through
-    some generations one at a time and notice these rules taking their
-    effect.</para>
-
-    <para>The screnshot below shows an example generation, with a number of
-    live cells. Don't worry about matching the exact patterns represented in
-    the screen shot. Just get some groups of cells added to the grid. Once you
-    have groups of live cells in the grid, or select a pre-designed pattern,
-    click the "Next Generation" button and notice what happens. Some of the
-    live cells are killed (the green ball disappears) and some dead cells come
-    to life (a green ball appears). Cycle through several generations and see
-    if you notice any patterns. If you click on the "Start" button, the system
-    will evolve itself so you don't need to click the "Next Generation" button
-    over and over. Play with the system a little and then come back here for
-    more details of how the application works.</para>
-
-    <figure>
-      <title>Conways Example : A running game</title>
-
-      <mediaobject>
-        <imageobject>
-		<imagedata fileref="conway2.png" />
-        </imageobject>
-      </mediaobject>
-    </figure>
-
-    <para>Now lets delve into the code, as this is an advanced example we'll
-    assume that by now you know your way around the Drools framework and able
-    to connect many of the dots, so we'll just focus at a hgh level
-    overview.The example has two ways to execute, one way uses AgendaGroups to
-    manage execution flow the other uses RuleFlowGroups to manage execution
-    flow - so it's a great way to see the differences. - that's
-    ConwayAgendaGroupRun and ConwayRuleFlowGroupRun respectively. For this
-    example I'll cover the ruleflow version, as its what most people will
-    use.</para>
-
-    <para>All the Cells are inserted into the session and the rules in the
-    ruleflow-group "register neighbor" are allowed to execute by the ruleflow
-    process. What this group of rules does is for each cell it registers the
-    north east, north, north west and west cells using a Neighbor relation
-    class, notice this relation is bi-drectional which is why we don't have to
-    do any rules for southern facing cells. Note that the constraints make
-    sure we stay one column back from the end and 1 row back from the top. By
-    the time all activations have fired for these rules all cells are related
-    to all their neighboring cells.</para>
-
-    <example>
-      <title>Conways Example : Register all Cell Neighbour relations</title>
-
-      <programlisting>rule "register north east"
-    ruleflow-group "register neighbor"
-when
-    CellGrid( $numberOfColumns : numberOfColumns )
-    $cell: Cell( $row : row &gt; 0, $col : col &lt; ( $numberOfColumns - 1 ) )            
-    $northEast : Cell( row  == ($row - 1), col == ( $col + 1 ) )    
-then                    
-    insert( new Neighbor( $cell, $northEast ) );
-    insert( new Neighbor( $northEast, $cell ) );        
-end
-
-rule "register north"
-    ruleflow-group "register neighbor"  
-when
-    $cell: Cell( $row : row &gt; 0, $col : col )   
-    $north : Cell( row  == ($row - 1), col == $col )    
-then        
-    insert( new Neighbor( $cell, $north ) );
-    insert( new Neighbor( $north, $cell ) );        
-end
-
-rule "register north west"
-    ruleflow-group "register neighbor"
-when
-    $cell: Cell( $row : row &gt; 0, $col : col &gt; 0 )           
-    $northWest : Cell( row  == ($row - 1), col == ( $col - 1 ) )                        
-then        
-    insert( new Neighbor( $cell, $northWest ) );
-    insert( new Neighbor( $northWest, $cell ) );        
-end
-
-rule "register west"
-    ruleflow-group "register neighbor"
-when
-    $cell: Cell( $row : row &gt;= 0, $col : col &gt; 0 )          
-    $west : Cell( row  == $row, col == ( $col - 1 ) )                       
-then        
-    insert( new Neighbor( $cell, $west ) );
-    insert( new Neighbor( $west, $cell ) );         
-end</programlisting>
-    </example>
-
-    <para>Once all the cells are inserted some java code applies the pattern
-    to the grid setting certain cells to Live. Then when the user clicks
-    "start" or "next generation" it executes the "Generation" ruleflow. This
-    ruleflow is responsible for the management of all changes of cells in each
-    generation cycle.</para>
-
-    <figure>
-      <title>Conways Example : ruleflow "Generation"</title>
-
-      <mediaobject>
-        <imageobject>
-		<imagedata fileref="conway_ruleflow_generation.png" />
-        </imageobject>
-      </mediaobject>
-    </figure>
-
-    <para>The ruleflow process first enters the "evaluate" group, this means
-    any active rule in that group can fire. The rules in this group apply the
-    main game of life rules discussed in the beginning of the example, where
-    it determines what cells will be killed and which ones given life. We use
-    the "phase" attribute to drives the reasoning of the Cell by specific
-    groups of rules; typical the phase is tied to a RuleFlowGroup. in the
-    ruleflow process definition. Notice that it doesn't actually change the
-    state of any Cells at this point; this is because it's evaluating the Grid
-    in turn and it must complete the full evaluation until those changes can
-    be applied. To achieve this it sets the cell to a "phase" which is either
-    Phase.KILL or Phase.BIRTH, which is used later to control actions applied
-    to the Cell and when.</para>
-
-    <example>
-      <title>Conways Example : Evaluate Cells with state changes</title>
-
-      <programlisting>rule "Kill The Lonely"
-    ruleflow-group "evaluate"
-    no-loop
-when
-#   A live cell has fewer than 2 live neighbors
-    theCell: Cell(liveNeighbors &lt; 2, cellState == CellState.LIVE, phase == Phase.EVALUATE)
-then
-    theCell.setPhase(Phase.KILL);
-    update( theCell );
-end
-
-rule "Kill The Overcrowded"
-    ruleflow-group "evaluate"
-    no-loop
-when
-#   A live cell has more than 3 live neighbors
-    theCell: Cell(liveNeighbors &gt; 3, cellState == CellState.LIVE, phase == Phase.EVALUATE)
-then
-    theCell.setPhase(Phase.KILL);
-    update( theCell );
-end
-
-rule "Give Birth"
-    ruleflow-group "evaluate"
-    no-loop
-when
-#   A dead cell has 3 live neighbors
-    theCell: Cell(liveNeighbors == 3, cellState == CellState.DEAD, phase == Phase.EVALUATE)
-then
-    theCell.setPhase(Phase.BIRTH);
-    update( theCell );
-end
-</programlisting>
-    </example>
-
-    <para>Once all Cells in the grid have been evaluated we first clear any
-    calculation activations, that occured from any previous data changes, via
-    the "reset calculate" rule, which clears any activations in the
-    "calculate" group. We then enter a split which allows any activations in
-    the "kill" groups and "birth" groups to fire, these rules are responsible
-    for applying the state change.</para>
-
-    <example>
-      <title>Conways Example : Apply the state changes</title>
-
-      <programlisting>rule "reset calculate"
-    ruleflow-group "reset calculate"
-when
-then
-    WorkingMemory wm = drools.getWorkingMemory();
-    wm.clearRuleFlowGroup( "calculate" );
-end
-
-rule "kill"
-    ruleflow-group "kill"
-    no-loop
-when
-    theCell: Cell(phase == Phase.KILL)
-then
-    theCell.setCellState(CellState.DEAD);
-    theCell.setPhase(Phase.DONE);   
-    update( theCell );
-end 
- 
-rule "birth"
-    ruleflow-group "birth"
-    no-loop
-when
-    theCell: Cell(phase == Phase.BIRTH)
-then
-    theCell.setCellState(CellState.LIVE);
-    theCell.setPhase(Phase.DONE);
-    update( theCell );  
-end </programlisting>
-    </example>
-
-    <para>At this stage a number of Cells have been modified with the state
-    changed to either LIVE or DEAD, this is where we get to see the power of
-    the Neighbour cell and relational programming. When a cell becomes LIVE or
-    DEAD we use the Neigbor relation drive the iteration over all surrounding
-    Cells increasing or decreasing the LIVE neighbour count, any cell who has
-    their count changed is also set to to the EVALUATE phase, to make sure
-    they are reasoned over duing the evaluate stage of the ruleflow process.
-    Notice that we don't have to do any iteration ourselves, by simpy applying
-    the relations in the rules we can get the rule engine to do all the hard
-    work for us in a minimal amount of code - very nice :) Once the live count
-    for all Cells has been determiend and set the ruleflow process comes to
-    and end; the user can either tell it to evaluate another generation, of if
-    "start" was clicked the engine will start the ruleflow process
-    again.</para>
-
-    <example>
-      <title>Conways Example : Evaluate Cells with state changes</title>
-
-      <programlisting>rule "Calculate Live"
-    ruleflow-group "calculate"
-    lock-on-active  
-when
-    theCell: Cell(cellState == CellState.LIVE)
-    Neighbor(cell == theCell, $neighbor : neighbor) 
-then
-    $neighbor.setLiveNeighbors( $neighbor.getLiveNeighbors() + 1 );
-    $neighbor.setPhase( Phase.EVALUATE );   
-    update( $neighbor );
-end 
-
-rule "Calculate Dead"
-    ruleflow-group "calculate"
-    lock-on-active  
-when
-    theCell: Cell(cellState == CellState.DEAD)
-    Neighbor(cell == theCell, $neighbor : neighbor )
-then
-    $neighbor.setLiveNeighbors( $neighbor.getLiveNeighbors() - 1 );
-    $neighbor.setPhase( Phase.EVALUATE );
-    update( $neighbor );    
-end </programlisting>
-    </example>
-  </section>
-
-	<section>
-		<title>Insurance Company Risk Factor and Policy price (using BRMS)</title>
-
-		<screen><emphasis role="bold">Name:</emphasis> drools-insurance 
-<emphasis role="bold">Type:</emphasis> java web application
-<emphasis role="bold">Rules file:</emphasis> exported repository from brms, repository_export.xml
-<emphasis role="bold">Objective:</emphasis> Demonstrates how to use, organize, deploy and execute a rulebase from BRMS</screen>
-
-		<section>
-			<title>BRMS editors</title>
-
-			<para>The BRMS has many GUI editors, and textual editors. This discusses a few example rules using some of the GUI features:</para>
-
-			<figure>
-				<title>Guided editor</title>
-
-				<mediaobject>
-					<imageobject>
-						<imagedata align="center" fileref="BRMS_Guided.png" format="PNG" scalefit="2" />
-					</imageobject>
-				</mediaobject>
-			</figure>
-
-			<para>The above example shows the guided editor in action. This is a slightly more complex example, as a few bound variables are used. We are binding "$driver" to the Driver fact, and also binding driverId to the id field of the driver (which is then used in the SupplementalInfo fact - to join the driverId with the actual driver id). Note the use of the ruleflow-group to specify what step of the processing this rule applies to.</para>
-
-			<figure>
-				<title>DSL Editor</title>
-				
-				<mediaobject>
-					<imageobject>
-						<imagedata align="center" fileref="BRMS_DSL.png" format="PNG" scalefit="2" />
-					</imageobject>
-				</mediaobject>
-			</figure>
-
-			<para>The above shows the editor using a DSL. In this case the "guided editor" was used - this is not a text area, but only provides text boxes to "fill in the blanks" as specified in the DSL configuration. Note you can also use text based DSLs where there is not this restriction.</para>
-		</section>
-
-		<section>
-			<title>Introduction</title>
-
-			<para>Insurance, in law and economics, is a form of risk management primarily used to hedge against the risk of a contingent loss. Insurance is defined as the equitable transfer of the risk of a loss, from one entity to another, in exchange for a premium. Insurer, in economics, is the company that sells the insurance. Insurance rate is a factor used to determine the amount, called the premium, to be charged for a certain amount of insurance coverage. Risk management, the practice of appraising and controlling risk, has evolved as a discrete field of study and practice.</para>
-		</section>
-
-		<section>
-			<title>The insurance logic</title>
-
-			<para>If you have a poor driving record, you may need to look into high risk auto insurance. Accidents increase these rates as well. If you have a low experience for example less than 3 years as a licensed driver, insurance companies believe that the chances that you will be involved in a traffic accident are higher than someone more expert.</para>
-
-			<para>Who you are also plays a factor. Men are considered more of a risk than women. Teens are considered more of a risk than adults as well if you have some younger driver in family like your 20 years old son.</para>
-		
-			<screen>rule "Young male single driver"
-ruleflow-group "risk assessment"
-when
- $driver : Driver( genre == Driver.MALE, age &lt; 25, maritalState == Driver.SINGLE )
-then 
- $driver.updateInsuranceFactor(1.6);
-end
-
-rule "no expert driver"
-ruleflow-group "risk assessment"
-when
- $driver : Driver ( licenceYears &lt; 3 )
-then
- $driver.updateInsuranceFactor(1.2);
-end
-</screen>
-
-			<para>Extra coverage over glasses, additional car and accessories, like your expansive "pimped" sound system will increase your insurance final price, not the risk factor. </para>
-		
-			<screen>ruleflow-group "insurancecalcule"
-salience 20
-when
- not Rejection()
- $driver : Driver ( driverID : id )
- $access : AccessoriesCoverage ( driverId == driverID)
- $policy : Policy( approved == true )
-then
- $policy.setInsurancePrice( $policy.getInsurancePrice() + 
-  ($access.getAlarmSystemValue() * 0.10) + 
-  ($access.getArmorValue() * 0.20) +
-  ($access.getSoundSystemValue() * 0.30 ));
-</screen>
-
-			<para>This example uses the previously explained <emphasis role="bold">RuleFlow</emphasis> feature, the following diagram gives you an overview of the insurance factor and calculate logic: As you can see, we first calculate the insurance factor, if the driver matches with some rejection condition we don't execute the group that contains the Policy price calculus, just returning and not approved policy </para>
-
-			<screen>ruleflow-group "insurancecalcule"
-salience 10
-when
- not Rejection()
- $driver : Driver(ifactor : insuranceFactor)
- $policy : Policy( approved == true, bp : basePrice, ip : insurancePrice )
-then
- $policy.setInsurancePrice((bp * ifactor) + ip);
-</screen>
-
-
-			<figure>
-				<title>The insurance rule flow</title>
-	
-				<mediaobject>
-					<imageobject>
-						<imagedata align="center" fileref="insurance-ruleflow.png" format="PNG" scalefit="1" />
-					</imageobject>
-				</mediaobject>
-			</figure>
-		</section>
-
-		<section>
-			<title>Downloading and installing the BRMS</title>
-	
-			<itemizedlist>
-				<listitem>
-					<para>Download the latest version of BRMS from http://cruisecontrol.jboss.com/cc/artifacts/jboss-rules</para>
-				</listitem>
-	
-				<listitem>
-					<para>Deploy BRMS WAR file into JBoss4.2 AS or JBossWeb, other containers can be used as well possibly with some tweaking of dependencies (check this url if you using a different application server http://wiki.jboss.org/wiki/Wiki.jsp?page=JBRMSjsfdependencies).</para>
-				</listitem>
-	
-				<listitem>
-					<para>Check you can access and run the BRMS.</para>
-				</listitem>
-	
-				<listitem>
-					<para>Check out the demo project from the Drools subversion repository http://anonsvn.labs.jboss.com/labs/jbossrules/trunk/drools-examples/drools-insurance/</para>
-				</listitem>
-	
-				<listitem>
-					<para>Import the demo business rules insurance repository file into BRMS, the compressed can be found at "files" folder in the demo project. To do this, open the "files" directory, unzip the file there locally, and then go to the "Admin" section and "Manage import/export" of the BRMS, select the file, and press "Import" - follow instructions.</para>
-				</listitem>
-	
-				<listitem>
-					<para>Navigate through the BRMS web application to see how things are placed and organized and try to create some rules.</para>
-				</listitem>
-	
-				<listitem>
-					<para>Go to the "Packages" feature and build the package (you should see no errors).</para>
-				</listitem>
-	
-				<listitem>
-					<para>Now go to the "Deployment" feature, when you click on the package, it will show you one snapshot (which was part of the import, you can create more if you like from the previous step).</para>
-				</listitem>
-			</itemizedlist>
-		</section>
-	
-		<section>
-			<title>Deploying the insurance example in your application server</title>
-	
-			<itemizedlist>
-				<listitem>
-					<para>Go into your downloaded project and execute <programlisting>mvn clean package</programlisting></para>
-				</listitem>
-	
-				<listitem>
-					<para>You should see the RuleAgent downloadomg the pre-compiled package from brms, if something goes wrong and all tests fails, check if the BRMS is up and running and try rebuild the package snapshot.</para>
-					
-				<screen>Running org.acme.insurance.test.DriverTest
-RuleAgent(insuranceconfig) INFO (Wed Sep 18 14:11:44 BRT 2007): Configuring with newInstance=true, secondsToRefresh=30
-RuleAgent(insuranceconfig) INFO (Wed Sep 18 14:11:44 BRT 2007): Configuring package provider : URLScanner monitoring URLs:  
-                          http://localhost:8080/drools-jbrms/org.drools.brms.JBRMS/package/org.acme.insurance.base/InsuranceDemo
-
-RuleAgent(insuranceconfig) INFO (Wed Sep 18 14:11:45 BRT 2007): Applying changes to the rulebase.
-RuleAgent(insuranceconfig) INFO (Wed Sep 18 14:11:45 BRT 2007): Creating a new rulebase as per settings.
-RuleAgent(insuranceconfig) INFO (Wed Sep 18 14:11:45 BRT 2007): Adding package called org.acme.insurance.base
-
-... snip ...
-
-Insurance calculate
-Insurance Calcule: 0.0
-Driver wants non related expenses coverage: 1.05
-Driver wants glass coverage: 1.1025
-Driver wants extra assistence: 1.1576250000000001Driver wants an extra Car: 1.2155062500000002
-Driver Single Young Male Driver factor: 1.9448100000000004
-New Licenced driver 2.333772
-approve: 0.0
-Policy aproved focusing insurance calcule agenda-group
-Insurance calculate
-Insurance Calcule: 0.0
-Night Vehicle Place: 1.44
-Day Vehicle Place: 1.656
-approve: 0.0
-Policy aproved focusing insurance calcule agenda-group
-Insurance calculate
-Insurance extra itens percent: 545.0
-Insurance Calcule: 545.0
-Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 sec
-
-Results :
-Tests run: 16, Failures: 0, Errors: 0, Skipped: 0
-</screen>
-				</listitem>
-			</itemizedlist>
-		</section>
-
-		<section>
-			<title>Running the example from the web page</title>
-	
-			<para>After running and packing you are able to deploy the war into your application server, just following the previous instructions for BRMS, then point your browser to the example url, that should be something like this http://localhost:8080/drools-insurance. Just play around the example and change some values and press the execute button, after the rules fired the result will be displayed in the bottom of the page.</para>
-	
-			<figure>
-				<title>The insurance web page</title>
-	
-				<mediaobject>
-					<imageobject>
-						<imagedata align="center" fileref="insurance-website.png" format="PNG" scalefit="2" />
-					</imageobject>
-				</mediaobject>
-			</figure>
-		</section>
-	</section>
-</section>

Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-InsuranceExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-InsuranceExample.xml	                        (rev 0)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-InsuranceExample.xml	2008-06-14 16:26:55 UTC (rev 20482)
@@ -0,0 +1,212 @@
+<?xml version="1.0" encoding="UTF-8"?>
+	<section xml:base="../" >
+		<title>Insurance Company Risk Factor and Policy price (using BRMS)</title>
+
+		<screen><emphasis role="bold">Name:</emphasis> drools-insurance 
+<emphasis role="bold">Type:</emphasis> java web application
+<emphasis role="bold">Rules file:</emphasis> exported repository from brms, repository_export.xml
+<emphasis role="bold">Objective:</emphasis> Demonstrates how to use, organize, deploy and execute a rulebase from BRMS</screen>
+
+		<section>
+			<title>BRMS editors</title>
+
+			<para>The BRMS has many GUI editors, and textual editors. This discusses a few example rules using some of the GUI features:</para>
+
+			<figure>
+				<title>Guided editor</title>
+
+				<mediaobject>
+					<imageobject>
+						<imagedata align="center" fileref="InsuranceExample/BRMS_Guided.png" format="PNG" scalefit="2" />
+					</imageobject>
+				</mediaobject>
+			</figure>
+
+			<para>The above example shows the guided editor in action. This is a slightly more complex example, as a few bound variables are used. We are binding "$driver" to the Driver fact, and also binding driverId to the id field of the driver (which is then used in the SupplementalInfo fact - to join the driverId with the actual driver id). Note the use of the ruleflow-group to specify what step of the processing this rule applies to.</para>
+
+			<figure>
+				<title>DSL Editor</title>
+				
+				<mediaobject>
+					<imageobject>
+						<imagedata align="center" fileref="InsuranceExample/BRMS_DSL.png" format="PNG" scalefit="2" />
+					</imageobject>
+				</mediaobject>
+			</figure>
+
+			<para>The above shows the editor using a DSL. In this case the "guided editor" was used - this is not a text area, but only provides text boxes to "fill in the blanks" as specified in the DSL configuration. Note you can also use text based DSLs where there is not this restriction.</para>
+		</section>
+
+		<section>
+			<title>Introduction</title>
+
+			<para>Insurance, in law and economics, is a form of risk management primarily used to hedge against the risk of a contingent loss. Insurance is defined as the equitable transfer of the risk of a loss, from one entity to another, in exchange for a premium. Insurer, in economics, is the company that sells the insurance. Insurance rate is a factor used to determine the amount, called the premium, to be charged for a certain amount of insurance coverage. Risk management, the practice of appraising and controlling risk, has evolved as a discrete field of study and practice.</para>
+		</section>
+
+		<section>
+			<title>The insurance logic</title>
+
+			<para>If you have a poor driving record, you may need to look into high risk auto insurance. Accidents increase these rates as well. If you have a low experience for example less than 3 years as a licensed driver, insurance companies believe that the chances that you will be involved in a traffic accident are higher than someone more expert.</para>
+
+			<para>Who you are also plays a factor. Men are considered more of a risk than women. Teens are considered more of a risk than adults as well if you have some younger driver in family like your 20 years old son.</para>
+		
+			<screen>rule "Young male single driver"
+ruleflow-group "risk assessment"
+when
+ $driver : Driver( genre == Driver.MALE, age &lt; 25, maritalState == Driver.SINGLE )
+then 
+ $driver.updateInsuranceFactor(1.6);
+end
+
+rule "no expert driver"
+ruleflow-group "risk assessment"
+when
+ $driver : Driver ( licenceYears &lt; 3 )
+then
+ $driver.updateInsuranceFactor(1.2);
+end
+</screen>
+
+			<para>Extra coverage over glasses, additional car and accessories, like your expansive "pimped" sound system will increase your insurance final price, not the risk factor. </para>
+		
+			<screen>ruleflow-group "insurancecalcule"
+salience 20
+when
+ not Rejection()
+ $driver : Driver ( driverID : id )
+ $access : AccessoriesCoverage ( driverId == driverID)
+ $policy : Policy( approved == true )
+then
+ $policy.setInsurancePrice( $policy.getInsurancePrice() + 
+  ($access.getAlarmSystemValue() * 0.10) + 
+  ($access.getArmorValue() * 0.20) +
+  ($access.getSoundSystemValue() * 0.30 ));
+</screen>
+
+			<para>This example uses the previously explained <emphasis role="bold">RuleFlow</emphasis> feature, the following diagram gives you an overview of the insurance factor and calculate logic: As you can see, we first calculate the insurance factor, if the driver matches with some rejection condition we don't execute the group that contains the Policy price calculus, just returning and not approved policy </para>
+
+			<screen>ruleflow-group "insurancecalcule"
+salience 10
+when
+ not Rejection()
+ $driver : Driver(ifactor : insuranceFactor)
+ $policy : Policy( approved == true, bp : basePrice, ip : insurancePrice )
+then
+ $policy.setInsurancePrice((bp * ifactor) + ip);
+</screen>
+
+
+			<figure>
+				<title>The insurance rule flow</title>
+	
+				<mediaobject>
+					<imageobject>
+						<imagedata align="center" fileref="InsuranceExample/insurance-ruleflow.png" format="PNG" scalefit="1" />
+					</imageobject>
+				</mediaobject>
+			</figure>
+		</section>
+
+		<section>
+			<title>Downloading and installing the BRMS</title>
+	
+			<itemizedlist>
+				<listitem>
+					<para>Download the latest version of BRMS from http://cruisecontrol.jboss.com/cc/artifacts/jboss-rules</para>
+				</listitem>
+	
+				<listitem>
+					<para>Deploy BRMS WAR file into JBoss4.2 AS or JBossWeb, other containers can be used as well possibly with some tweaking of dependencies (check this url if you using a different application server http://wiki.jboss.org/wiki/Wiki.jsp?page=JBRMSjsfdependencies).</para>
+				</listitem>
+	
+				<listitem>
+					<para>Check you can access and run the BRMS.</para>
+				</listitem>
+	
+				<listitem>
+					<para>Check out the demo project from the Drools subversion repository http://anonsvn.labs.jboss.com/labs/jbossrules/trunk/drools-examples/drools-insurance/</para>
+				</listitem>
+	
+				<listitem>
+					<para>Import the demo business rules insurance repository file into BRMS, the compressed can be found at "files" folder in the demo project. To do this, open the "files" directory, unzip the file there locally, and then go to the "Admin" section and "Manage import/export" of the BRMS, select the file, and press "Import" - follow instructions.</para>
+				</listitem>
+	
+				<listitem>
+					<para>Navigate through the BRMS web application to see how things are placed and organized and try to create some rules.</para>
+				</listitem>
+	
+				<listitem>
+					<para>Go to the "Packages" feature and build the package (you should see no errors).</para>
+				</listitem>
+	
+				<listitem>
+					<para>Now go to the "Deployment" feature, when you click on the package, it will show you one snapshot (which was part of the import, you can create more if you like from the previous step).</para>
+				</listitem>
+			</itemizedlist>
+		</section>
+	
+		<section>
+			<title>Deploying the insurance example in your application server</title>
+	
+			<itemizedlist>
+				<listitem>
+					<para>Go into your downloaded project and execute <programlisting>mvn clean package</programlisting></para>
+				</listitem>
+	
+				<listitem>
+					<para>You should see the RuleAgent downloadomg the pre-compiled package from brms, if something goes wrong and all tests fails, check if the BRMS is up and running and try rebuild the package snapshot.</para>
+					
+				<screen>Running org.acme.insurance.test.DriverTest
+RuleAgent(insuranceconfig) INFO (Wed Sep 18 14:11:44 BRT 2007): Configuring with newInstance=true, secondsToRefresh=30
+RuleAgent(insuranceconfig) INFO (Wed Sep 18 14:11:44 BRT 2007): Configuring package provider : URLScanner monitoring URLs:  
+                          http://localhost:8080/drools-jbrms/org.drools.brms.JBRMS/package/org.acme.insurance.base/InsuranceDemo
+
+RuleAgent(insuranceconfig) INFO (Wed Sep 18 14:11:45 BRT 2007): Applying changes to the rulebase.
+RuleAgent(insuranceconfig) INFO (Wed Sep 18 14:11:45 BRT 2007): Creating a new rulebase as per settings.
+RuleAgent(insuranceconfig) INFO (Wed Sep 18 14:11:45 BRT 2007): Adding package called org.acme.insurance.base
+
+... snip ...
+
+Insurance calculate
+Insurance Calcule: 0.0
+Driver wants non related expenses coverage: 1.05
+Driver wants glass coverage: 1.1025
+Driver wants extra assistence: 1.1576250000000001Driver wants an extra Car: 1.2155062500000002
+Driver Single Young Male Driver factor: 1.9448100000000004
+New Licenced driver 2.333772
+approve: 0.0
+Policy aproved focusing insurance calcule agenda-group
+Insurance calculate
+Insurance Calcule: 0.0
+Night Vehicle Place: 1.44
+Day Vehicle Place: 1.656
+approve: 0.0
+Policy aproved focusing insurance calcule agenda-group
+Insurance calculate
+Insurance extra itens percent: 545.0
+Insurance Calcule: 545.0
+Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 sec
+
+Results :
+Tests run: 16, Failures: 0, Errors: 0, Skipped: 0
+</screen>
+				</listitem>
+			</itemizedlist>
+		</section>
+
+		<section>
+			<title>Running the example from the web page</title>
+	
+			<para>After running and packing you are able to deploy the war into your application server, just following the previous instructions for BRMS, then point your browser to the example url, that should be something like this http://localhost:8080/drools-insurance. Just play around the example and change some values and press the execute button, after the rules fired the result will be displayed in the bottom of the page.</para>
+	
+			<figure>
+				<title>The insurance web page</title>
+	
+				<mediaobject>
+					<imageobject>
+						<imagedata align="center" fileref="InsuranceExample/insurance-website.png" format="PNG" scalefit="2" />
+					</imageobject>
+				</mediaobject>
+			</figure>
+		</section>
+	</section>
\ No newline at end of file

Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-MannersExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-MannersExample.xml	                        (rev 0)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-MannersExample.xml	2008-06-14 16:26:55 UTC (rev 20482)
@@ -0,0 +1,606 @@
+<?xml version="1.0" encoding="UTF-8"?>
+	<section xml:base="../" >
+    <title>Miss Manners and Benchmarking</title>
+
+    <programlisting><emphasis role="bold">Name:</emphasis> Miss Manners
+<emphasis role="bold">Main class:</emphasis> org.drools.benchmark.manners.MannersBenchmark
+<emphasis role="bold">Type:</emphasis> java application
+<emphasis role="bold">Rules file:</emphasis> manners.drl
+<emphasis role="bold">Objective:</emphasis> Advanced walkthrough on the Manners benchmark, covers Depth conflict resolution in depth.</programlisting>
+
+    <section>
+      <title>Introduction</title>
+
+      <para>Miss Manners is throwing a party and being the good host she wants
+      to arrange good seating. Her initial design arranges everyone in male
+      female pairs, but then she worries about people have things to talk
+      about; what is a good host to do? So she decides to note the hobby of
+      each guest so she can then arrange guests in not only male and female
+      pairs but also ensure that a guest has someone to talk about a common
+      hobby, from either their left or right side.</para>
+
+      <figure>
+        <title>Miss Manners' Guests</title>
+
+        <mediaobject>
+
+          <imageobject>
+            <imagedata align="center" fileref="MannersExample/guests_at_table.png"
+                       format="PNG" scalefit="1" />
+          </imageobject>
+        </mediaobject>
+      </figure>
+
+      <section>
+        <title>BenchMarking</title>
+
+        <para>5 benchmarks were established in the 1991 paper "Effects of
+        Database Size on Rule System Performance: Five Case Studies" by Brant,
+        Timothy Grose, Bernie Lofaso, &amp; Daniel P. Miranker.</para>
+
+        <itemizedlist>
+          <listitem>
+            <para>Manners</para>
+
+            <itemizedlist>
+              <listitem>
+                <para>Uses a depth-first search approach to determine the
+                seating arrangements of boy/girl and one common hobby for
+                dinner guests</para>
+              </listitem>
+            </itemizedlist>
+          </listitem>
+
+          <listitem>
+            <para>Waltz</para>
+
+            <itemizedlist>
+              <listitem>
+                <para>line labeling for simple scenes by constraint
+                propagation</para>
+              </listitem>
+            </itemizedlist>
+          </listitem>
+
+          <listitem>
+            <para>WaltzDB</para>
+
+            <itemizedlist>
+              <listitem>
+                <para>More general version of Walts to be able to adapt to a
+                database of facts</para>
+              </listitem>
+            </itemizedlist>
+          </listitem>
+
+          <listitem>
+            <para>ARP</para>
+
+            <itemizedlist>
+              <listitem>
+                <para>Route planner for a robotic air vehicle using the A*
+                search algorithm</para>
+              </listitem>
+            </itemizedlist>
+          </listitem>
+
+          <listitem>
+            <para>Weavera</para>
+
+            <itemizedlist>
+              <listitem>
+                <para>VLSI router for channels and boxes using a black-board
+                technique</para>
+              </listitem>
+            </itemizedlist>
+          </listitem>
+        </itemizedlist>
+
+        <para>Manners has become the de facto rule engine benchmark; however
+        it's behavior is now well known and many engines optimize for this
+        thus negating its usefulness as a benchmark which is why Waltz is
+        becoming more favorable. These 5 benchmarks are also published at the
+        University of Texas <ulink
+        url="http://www.cs.utexas.edu/ftp/pub/ops5-benchmark-suite/">http://www.cs.utexas.edu/ftp/pub/ops5-benchmark-suite/</ulink>.</para>
+      </section>
+
+      <section>
+        <title>Miss Manners Execution Flow</title>
+
+        <para>After the first Seating arrangement has been assigned a
+        depth-first recursion occurs which repeatedly assigns correct Seating
+        arrangements until the last seat is assigned. Manners uses a Context
+        instance to control execution flow; the activity diagram is
+        partitioned to show the relation of the rule execution to the current
+        Context state.</para>
+
+        <figure>
+          <title>Manners Activity Diagram</title>
+
+          <mediaobject>
+
+            <imageobject>
+		    <imagedata align="center" fileref="MannersExample/manners_activity_diagram.png"
+                         format="PNG" scalefit="1" />
+            </imageobject>
+          </mediaobject>
+        </figure>
+      </section>
+
+      <section>
+        <title>The Data and Results</title>
+
+        <para>Before going deeper into the rules lets first take a look at the
+        asserted data and the resulting Seating arrangement. The data is a
+        simple set of 5 guests who should be arranged in male/female pairs
+        with common hobbies.</para>
+
+        <para><emphasis role="bold">The Data</emphasis></para>
+
+        <para>Each line of the results list is printed per execution of the
+        "Assign Seat" rule. They key bit to notice is that each line has pid
+        one greater than the last, the significance of this will be explained
+        in t he "Assign Seating" rule description. The 'l' and the 'r' refer
+        to the left and right, 's' is sean and 'n' is the guest name. In my
+        actual implementation I used longer notation, 'leftGuestName', but
+        this is not practice in a printed article. I found the notation of
+        left and right preferable to the original OPS5 '1' and '2</para>
+
+        <literallayout>(guest (name n1) (sex m) (hobby  h1)  )
+(guest (name n2) (sex f) (hobby  h1)  )
+(guest (name n2) (sex f) (hobby  h3)  )
+(guest (name n3) (sex m) (hobby  h3)  )
+(guest (name n4) (sex m) (hobby  h1)  )
+(guest (name n4) (sex f) (hobby  h2)  )
+(guest (name n4) (sex f) (hobby  h3)  )
+(guest (name n5) (sex f) (hobby  h2)  )
+(guest (name n5) (sex f) (hobby  h1)  )
+(last_seat (seat 5)  )</literallayout>
+
+        <para><emphasis role="bold">The Results</emphasis></para>
+
+        <literallayout>[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5] 
+[Seating id=2, pid=1, done=false, ls=1, ln=n5, rs=2, rn=n4] 
+[Seating id=3, pid=2, done=false, ls=2, ln=n4, rs=3, rn=n3] 
+[Seating id=4, pid=3, done=false, ls=3, rn=n3, rs=4, rn=n2] 
+[Seating id=5, pid=4, done=false, ls=4, ln=n2, rs=5, rn=n1]</literallayout>
+      </section>
+    </section>
+
+    <section>
+      <title>Indepth look</title>
+
+      <section>
+        <title>Cheating</title>
+
+        <para>Manners has been around a long time and is a contrived benchmark
+        meant to exercise the cross product joins and agenda, many people not
+        understanding this tweak the example to achieve better performance,
+        making their use of the Manners benchmark pointless. Known cheats to
+        Miss Manners are:</para>
+
+        <itemizedlist>
+          <listitem>
+            <para>Using arrays for a guests hobbies, instead of asserting each
+            one as a single fact. This massively reduces the cross
+            products.</para>
+          </listitem>
+
+          <listitem>
+            <para>The altering of the sequence of data can also reducing the
+            amount of matching increase execution speed</para>
+          </listitem>
+
+          <listitem>
+            <para>Changing NOT CE (conditional element) such that the test
+            algorithm only uses the "first-best-match". Basically, changing
+            the test algorithm to backward chaining. the results are only
+            comparable to other backward chaining rule engines or ports of
+            Manners.</para>
+          </listitem>
+
+          <listitem>
+            <para>Removing the context so the rule engine matches the guests
+            and seats pre-maturely. A proper port will prevent facts from
+            matching using the context start.</para>
+          </listitem>
+
+          <listitem>
+            <para>Any change which prevents the rule engine from performing
+            combinatorial pattern matching</para>
+          </listitem>
+
+          <listitem>
+            <para>If no facts are retracted in the reasoning cycle, as a
+            result of NOT CE, the port is incorrect.</para>
+          </listitem>
+        </itemizedlist>
+      </section>
+
+      <section>
+        <title>Conflict Resolution</title>
+
+        <para>Manners benchmark was written for OPS5 which has two conflict
+        resolution strategies, LEX and MEA; LEX is a chain of several
+        strategies including Salience, Recency, Complexity. The Recency part
+        of the strategy drives the depth first (LIFO) firing order. The Clips
+        manual documents the recency strategy as:</para>
+
+        <blockquote>
+          <attribution>Clips Reference Manual</attribution>
+
+          <para>Every fact and instance is marked internally with a "time tag"
+          to indicate its relative recency with respect to every other fact
+          and instance in the system. The pattern entities associated with
+          each rule activation are sorted in descending order for determining
+          placement. An activation with a more recent pattern entities is
+          placed before activations with less recent pattern entities. To
+          determine the placement order of two activations, compare the sorted
+          time tags of the two activations one by one starting with the
+          largest time tags. The comparison should continue until one
+          activation’s time tag is greater than the other activation’s
+          corresponding time tag. The activation with the greater time tag is
+          placed before the other activation on the agenda. If one activation
+          has more pattern entities than the other activation and the compared
+          time tags are all identical, then the activation with more time tags
+          is placed before the other activation on the agenda.</para>
+        </blockquote>
+
+        <para>However Jess and Clips both use the Depth strategy, which is
+        simpler and lighter, which Drools also adopted. The Clips manual
+        documents the Depth strategy as:</para>
+
+        <blockquote>
+          <attribution>Clips Reference Manual</attribution>
+
+          <para>Newly activated rules are placed above all rules of the same
+          salience. For example, given that fact-a activates rule-1 and rule-2
+          and fact-b activates rule-3 and rule-4, then if fact-a is asserted
+          before fact-b, rule-3 and rule-4 will be above rule-1 and rule-2 on
+          the agenda. However, the position of rule-1 relative to rule-2 and
+          rule-3 relative to rule-4 will be arbitrary.</para>
+        </blockquote>
+
+        <para>The initial Drools implementation for the Depth strategy would
+        not work for manners without the use of salience on the "make_path"
+        rule, the Clips support team had this to say:</para>
+
+        <blockquote>
+          <attribution>Clips Support Forum</attribution>
+
+          <para>The default conflict resolution strategy for CLIPS, depth, is
+          different than the default conflict resolution strategy used by
+          OPS5. Therefore if you directly translate an OPS5 program to CLIPS,
+          but use the default depth conflict resolution strategy, you're only
+          likely to get the correct behavior by coincidence. The lex and mea
+          conflict resolution strategies are provided in CLIPS to allow you to
+          quickly convert and correctly run an OPS5 program in CLIPS</para>
+        </blockquote>
+
+        <para>Investigation into the Clips code reveals there is undocumented
+        functionality in the Depth strategy. There is an accumulated time tag
+        used in this strategy; it's not an extensively fact by fact comparison
+        as in the recency strategy, it simply adds the total of all the time
+        tags for each activation and compares.</para>
+      </section>
+
+      <section>
+        <title>Assign First Seat</title>
+
+        <para>Once the context is changed to START_UP Activations are created
+        for all asserted Guests; because all Activations are created as the
+        result of a single Working Memory action, they all have the same
+        Activation time tag. The last asserted Guest would have a higher fact
+        time tag and its Activation would fire, becuase it has the highest
+        accumulated fact time tag. The execution order in this rule has little
+        importance, but has a big impact in the rule "Assign Seat". The
+        Activation fires and asserts the first Seating arrangement, a Path and
+        then sets the Context's state to create Activation for "Assign
+        Seat".</para>
+
+        <programlisting>rule assignFirstSeat
+    when
+        context : Context( state == Context.START_UP )
+        guest : Guest()
+        count : Count()
+    then
+        String guestName = guest.getName();        
+
+        insert( new Seating( count.getValue(), 1, true, 1, guestName, 1, guestName) );        
+        insert( new Path( count.getValue(), 1, guestName ) );        
+
+        count.setValue(  count.getValue() + 1 );        
+        update( count );
+        context.setState( Context.ASSIGN_SEATS );       
+        update( context );
+end</programlisting>
+      </section>
+
+      <section>
+        <title>Assign Seat</title>
+
+        <para>This rule determines each of the Seating arrangements. The Rule
+        creates cross product solutions for ALL asserted Seating arrangements
+        against ALL the asserted guests; accept against itself or any already
+        assigned Chosen solutions.</para>
+
+        <programlisting>rule findSeating
+   when 
+       context : Context( state == Context.ASSIGN_SEATS )
+       $s      : Seating( pathDone == true )
+       $g1     : Guest( name == $s.rightGuestName )
+       $g2     : Guest( sex != $g1.sex, hobby == $g1.hobby )
+       count   : Count()
+       not ( Path( id == $s.id, guestName == $g2.name) )
+       not ( Chosen( id == $s.id, guestName == $g2.name, hobby == $g1.hobby) )
+   then
+       int rightSeat = $s.getRightSeat();
+       int seatId = $s.getId();
+       int countValue = count.getValue();
+       
+       insert( new Seating( countValue, seatId, false, rightSeat, $s.getRightGuestName(), rightSeat + 1, $g2.getName() ) );                                
+       insert( new Path( countValue, rightSeat + 1, $g2.getName() ) );       
+       insert( new Chosen( seatId, $g2.getName(), $g1.getHobby() ) );
+
+       count.setValue(  countValue + 1 );
+       update( count );       
+       context.setState( Context.MAKE_PATH );
+       update( context );
+end</programlisting>
+
+        <para>However, as can be seen from the printed results shown earlier,
+        it is essential that only the Seating with the highest pid cross
+        product be chosen – yet how can this be possible if we have
+        Activations, of the same time tag, for nearly all existing Seating and
+        Guests. For example on the third iteration of "Assing Seat" these are
+        the produced Activations, remember this is from a very small data set
+        and with larger data sets there would be many more possible Activated
+        Seating solutions, with multiple solutions per pid:</para>
+
+        <literallayout>=&gt;[ActivationCreated(35): rule=findSeating 
+[fid:19:33]:[Seating id=3, pid=2, done=true, ls=2, ln=n4, rs=3, rn=n3] 
+[fid:4:4]:[Guest name=n3, sex=m, hobbies=h3] 
+[fid:3:3]:[Guest name=n2, sex=f, hobbies=h3]
+
+=&gt;[ActivationCreated(35): rule=findSeating 
+[fid:15:23]:[Seating id=2, pid=1, done=true, ls=1, ln=n5, rs=2, rn=n4] 
+[fid:5:5]:[Guest name=n4, sex=m, hobbies=h1] 
+[fid:2:2]:[Guest name=n2, sex=f, hobbies=h1] 
+
+=&gt;[ActivationCreated(35): rule=findSeating 
+[fid:13:13]:[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5] 
+[fid:9:9]:[Guest name=n5, sex=f, hobbies=h1] 
+[fid:1:1]:[Guest name=n1, sex=m, hobbies=h1]</literallayout>
+
+        <para>The creation of all these redundant Activations might seem
+        pointless, but it must be remembered that Manners is not about good
+        rule design; it's purposefully designed as a bad ruleset to fully
+        stress test the cross product matching process and the agenda, which
+        this clearly does. Notice that each Activation has the same time tag
+        of 35, as they were all activated by the change in Context to
+        ASSIGN_SEATS. With OPS5 and LEX it would correctly fire the Activation
+        with the last asserted Seating. With Depth the accumulated fact time
+        tag ensures the Activation with the last asserted Seating
+        fires.</para>
+      </section>
+
+      <section>
+        <title>Make Path and Path Done</title>
+
+        <para>"Make Path" must always fires before "Path Done". A Path is
+        asserted for each Seating arrangement up to the last asserted Seating.
+        Notice that "Path Done" is a subset of "Make Path", so how do we
+        ensure that "Make Path" fires first?</para>
+
+        <programlisting>rule makePath
+    when 
+        Context( state == Context.MAKE_PATH )
+        Seating( seatingId:id, seatingPid:pid, pathDone == false )
+        Path( id == seatingPid, pathGuestName:guestName, pathSeat:seat )
+        not Path( id == seatingId, guestName == pathGuestName )
+    then
+        insert( new Path( seatingId, pathSeat, pathGuestName ) );
+end</programlisting>
+
+        <programlisting>rule pathDone
+    when
+        context : Context( state == Context.MAKE_PATH ) 
+        seating : Seating( pathDone == false ) 
+    then
+        seating.setPathDone( true ); 
+        update( seating );
+        
+        context.setState( Context.CHECK_DONE ); 
+        update( context );
+end</programlisting>
+
+        <figure>
+          <title>Rete Diagram</title>
+
+          <mediaobject>
+
+            <imageobject>
+		    <imagedata align="center" fileref="MannersExample/make_path.png" format="PNG"
+                         scalefit="1" />
+            </imageobject>
+          </mediaobject>
+        </figure>
+
+        <para>Both rules end up on the Agenda in conflict and with identical
+        activation time tags, however the accumulate fact time tag is greater
+        for "Make Path" so it gets priority.</para>
+      </section>
+
+      <section>
+        <title>Continue and Are We Done</title>
+
+        <para>"Are We Done" only activates when the last seat is assigned, at
+        which point both rules will be activated. For the same reason that
+        "Make Path" always wins over "Path Done" "Are We Done" will take
+        priority over "Continue".</para>
+
+        <programlisting>rule areWeDone
+    when
+        context : Context( state == Context.CHECK_DONE ) 
+        LastSeat( lastSeat: seat )
+        Seating( rightSeat == lastSeat ) 
+    then
+        context.setState(Context.PRINT_RESULTS ); 
+        update( context );
+end
+</programlisting>
+
+        <programlisting>rule continue
+    when
+        context : Context( state == Context.CHECK_DONE ) 
+    then
+        context.setState( Context.ASSIGN_SEATS ); 
+        update( context );
+end
+</programlisting>
+      </section>
+    </section>
+
+    <section>
+      <title>Output Summary</title>
+
+      <literallayout><emphasis role="bold">Assign First seat</emphasis>
+=&gt;[fid:13:13]:[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5]
+=&gt;[fid:14:14]:[Path id=1, seat=1, guest=n5]
+
+==&gt;[ActivationCreated(16): rule=findSeating
+[fid:13:13]:[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5]
+[fid:9:9]:[Guest name=n5, sex=f, hobbies=h1]
+[fid:1:1]:[Guest name=n1, sex=m, hobbies=h1]
+
+==&gt;[ActivationCreated(16): rule=findSeating
+[fid:13:13]:[Seating id=1 , pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5]
+[fid:9:9]:[Guest name=n5, sex=f, hobbies=h1]
+[fid:5:5]:[Guest name=n4, sex=m, hobbies=h1]*
+
+<emphasis role="bold">Assign Seating</emphasis>
+=&gt;[fid:15:17] :[Seating id=2 , pid=1 , done=false, ls=1, lg=n5, rs=2, rn=n4]
+=&gt;[fid:16:18]:[Path id=2, seat=2, guest=n4]
+=&gt;[fid:17:19]:[Chosen id=1, name=n4, hobbies=h1]
+
+=&gt;[ActivationCreated(21): rule=makePath 
+[fid:15:17] : [Seating id=2, pid=1, done=false, ls=1, ln=n5, rs=2, rn=n4]
+[fid:14:14] : [Path id=1, seat=1, guest=n5]*
+
+==&gt;[ActivationCreated(21): rule=pathDone
+[Seating id=2, pid=1, done=false, ls=1, ln=n5, rs=2, rn=n4]*
+
+<emphasis role="bold">Make Path</emphasis>
+=&gt;[fid:18:22:[Path id=2, seat=1, guest=n5]]
+
+<emphasis role="bold">Path Done</emphasis>
+
+<emphasis role="bold">Continue Process</emphasis>
+=&gt;[ActivationCreated(25): rule=findSeating
+[fid:15:23]:[Seating id=2, pid=1, done=true, ls=1, ln=n5, rs=2, rn=n4]
+[fid:7:7]:[Guest name=n4, sex=f, hobbies=h3]
+[fid:4:4] : [Guest name=n3, sex=m, hobbies=h3]*
+
+=&gt;[ActivationCreated(25): rule=findSeating
+[fid:15:23]:[Seating id=2, pid=1, done=true, ls=1, ln=n5, rs=2, rn=n4]
+[fid:5:5]:[Guest name=n4, sex=m, hobbies=h1]
+[fid:2:2]:[Guest name=n2, sex=f, hobbies=h1], [fid:12:20] : [Count value=3]
+
+=&gt;[ActivationCreated(25): rule=findSeating
+[fid:13:13]:[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5]
+[fid:9:9]:[Guest name=n5, sex=f, hobbies=h1]
+[fid:1:1]:[Guest name=n1, sex=m, hobbies=h1]
+
+<emphasis role="bold">Assign Seating</emphasis>
+=&gt;[fid:19:26]:[Seating id=3, pid=2, done=false, ls=2, lnn4, rs=3, rn=n3]]
+=&gt;[fid:20:27]:[Path id=3, seat=3, guest=n3]]
+=&gt;[fid:21:28]:[Chosen id=2, name=n3, hobbies=h3}]
+
+=&gt;[ActivationCreated(30): rule=makePath
+[fid:19:26]:[Seating id=3, pid=2, done=false, ls=2, ln=n4, rs=3, rn=n3]
+[fid:18:22]:[Path id=2, seat=1, guest=n5]*
+
+=&gt;[ActivationCreated(30): rule=makePath 
+[fid:19:26]:[Seating id=3, pid=2, done=false, ls=2, ln=n4, rs=3, rn=n3]
+[fid:16:18]:[Path id=2, seat=2, guest=n4]*
+
+=&gt;[ActivationCreated(30): rule=done 
+[fid:19:26]:[Seating id=3, pid=2, done=false, ls=2, ln=n4, rs=3, rn=n3]*
+
+<emphasis role="bold">Make Path</emphasis>
+=&gt;[fid:22:31]:[Path id=3, seat=1, guest=n5]
+
+<emphasis role="bold">Make Path </emphasis>
+=&gt;[fid:23:32] [Path id=3, seat=2, guest=n4]
+
+<emphasis role="bold">Path Done</emphasis>
+
+<emphasis role="bold">Continue Processing</emphasis>
+=&gt;[ActivationCreated(35): rule=findSeating
+[fid:19:33]:[Seating id=3, pid=2, done=true, ls=2, ln=n4, rs=3, rn=n3]
+[fid:4:4]:[Guest name=n3, sex=m, hobbies=h3]
+[fid:3:3]:[Guest name=n2, sex=f, hobbies=h3], [fid:12:29]*
+
+=&gt;[ActivationCreated(35): rule=findSeating 
+[fid:15:23]:[Seating id=2, pid=1, done=true, ls=1, ln=n5, rs=2, rn=n4] 
+[fid:5:5]:[Guest name=n4, sex=m, hobbies=h1]
+[fid:2:2]:[Guest name=n2, sex=f, hobbies=h1]
+
+=&gt;[ActivationCreated(35): rule=findSeating 
+[fid:13:13]:[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5] 
+[fid:9:9]:[Guest name=n5, sex=f, hobbies=h1], [fid:1:1] : [Guest name=n1, sex=m, hobbies=h1]
+
+<emphasis role="bold">Assign Seating</emphasis>
+=&gt;[fid:24:36]:[Seating id=4, pid=3, done=false, ls=3, ln=n3, rs=4, rn=n2]]
+=&gt;[fid:25:37]:[Path id=4, seat=4, guest=n2]]
+=&gt;[fid:26:38]:[Chosen id=3, name=n2, hobbies=h3]
+
+==&gt;[ActivationCreated(40): rule=makePath 
+[fid:24:36]:[Seating id=4, pid=3, done=false, ls=3, ln=n3, rs=4, rn=n2]
+[fid:23:32]:[Path id=3, seat=2, guest=n4]*
+
+==&gt;[ActivationCreated(40): rule=makePath 
+[fid:24:36]:[Seating id=4, pid=3, done=false, ls=3, ln=n3, rs=4, rn=n2] 
+[fid:20:27]:[Path id=3, seat=3, guest=n3]*
+
+=&gt;[ActivationCreated(40): rule=makePath 
+[fid:24:36]:[Seating id=4, pid=3, done=false, ls=3, ln=n3, rs=4, rn=n2]
+[fid:22:31]:[Path id=3, seat=1, guest=n5]*
+
+=&gt;[ActivationCreated(40): rule=done 
+[fid:24:36]:[Seating id=4, pid=3, done=false, ls=3, ln=n3, rs=4, rn=n2]*
+
+<emphasis role="bold">Make Path </emphasis>
+=&gt;fid:27:41:[Path id=4, seat=2, guest=n4]
+
+<emphasis role="bold">Make Path</emphasis>
+=&gt;fid:28:42]:[Path id=4, seat=1, guest=n5]]
+
+<emphasis role="bold">Make Path</emphasis>
+=&gt;fid:29:43]:[Path id=4, seat=3, guest=n3]]
+
+<emphasis role="bold">Path Done</emphasis>
+
+<emphasis role="bold">Continue  Processing</emphasis>
+=&gt;[ActivationCreated(46): rule=findSeating 
+[fid:15:23]:[Seating id=2, pid=1, done=true, ls=1, ln=n5, rs=2, rn=n4] 
+[fid:5:5]:[Guest name=n4, sex=m, hobbies=h1], [fid:2:2]
+[Guest name=n2, sex=f, hobbies=h1]
+
+=&gt;[ActivationCreated(46): rule=findSeating 
+[fid:24:44]:[Seating id=4, pid=3, done=true, ls=3, ln=n3, rs=4, rn=n2]
+[fid:2:2]:[Guest name=n2, sex=f, hobbies=h1]
+[fid:1:1]:[Guest name=n1, sex=m, hobbies=h1]*
+
+=&gt;[ActivationCreated(46): rule=findSeating 
+[fid:13:13]:[Seating id=1, pid=0, done=true, ls=1, ln=n5, rs=1, rn=n5]
+[fid:9:9]:[Guest name=n5, sex=f, hobbies=h1]
+[fid:1:1]:[Guest name=n1, sex=m, hobbies=h1]
+
+<emphasis role="bold">Assign Seating</emphasis>
+=&gt;[fid:30:47]:[Seating id=5, pid=4, done=false, ls=4, ln=n2, rs=5, rn=n1]
+=&gt;[fid:31:48]:[Path id=5, seat=5, guest=n1]
+=&gt;[fid:32:49]:[Chosen id=4, name=n1, hobbies=h1]
+</literallayout>
+    </section>
+  </section>
\ No newline at end of file

Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-PetStoreExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-PetStoreExample.xml	                        (rev 0)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-PetStoreExample.xml	2008-06-14 16:26:55 UTC (rev 20482)
@@ -0,0 +1,511 @@
+<?xml version="1.0" encoding="UTF-8"?>
+	<section xml:base="../" >
+			<title>Pet Store Example</title>
+
+			<programlisting><emphasis role="bold">Name:</emphasis> Pet Store 
+<emphasis role="bold">Main class:</emphasis> org.drools.examples.PetStore
+<emphasis role="bold">Type:</emphasis> Java application
+<emphasis role="bold">Rules file:</emphasis> PetStore.drl
+<emphasis role="bold">Objective:</emphasis> Demonstrate use of Agenda Groups, Global Variables and integration with a GUI (including callbacks from within the Rules)
+</programlisting>
+
+			<para>The Pet Store example shows how to integrate Rules with a GUI (in this case a Swing based Desktop application). Within the rules file, it shows how to use agenda groups and auto-focus to control which of a set of rules is allowed to fire at any given time. It also shows mixing of Java and MVEL dialects within the rules, the use of accumulate functions and calling of Java functions from within the ruleset.</para>
+
+			<para>Like the rest of the the samples, all the Java Code is contained in one file. The PetStore.java contains the following principal classes (in addition to several minor classes to handle Swing Events)</para>
+
+			<itemizedlist>
+				<listitem>
+					<para><emphasis role="italic"> Petstore</emphasis> - containing the main() method that we will look at shortly.</para>
+				</listitem>
+
+				<listitem>
+					<para><emphasis role="italic">PetStoreUI</emphasis> - responsible for creating and displaying the Swing based GUI. It contains several smaller classes , mainly for responding to various GUI events such as mouse and button clicks.</para>
+				</listitem>
+
+				<listitem>
+					<para><emphasis role="italic">TabelModel</emphasis> - for holding the table data. Think of it as a JavaBean that extends the Swing AbstractTableModel class.</para>
+				</listitem>
+
+				<listitem>
+					<para><emphasis role="italic">CheckoutCallback</emphasis> - Allows the GUI to interact with the Rules.</para>
+				</listitem>
+
+				<listitem>
+					<para><emphasis role="italic">Ordershow </emphasis> - the items that we wish to buy.</para>
+				</listitem>
+
+				<listitem>
+					<para><emphasis role="italic">Purchase</emphasis> - Details of the order and the products we are buying.</para>
+				</listitem>
+
+				<listitem>
+					<para><emphasis role="italic">Product</emphasis> - JavaBean holding details of the product available for purchase, and it's price.</para>
+				</listitem>
+			</itemizedlist>
+
+			<para>Much of the Java code is either JavaBeans (simple enough to understand) or Swing based. We will touch on some Swing related points in the this tutorial , but a good place to get more Swing component information is <ulink url="???"><uri>http://java.sun.com/docs/books/tutorial/uiswing/</uri> available at the Sun Swing website.<citebiblioid /></ulink></para>
+
+			<para>There are two important Rules related pieces of Java code in <emphasis role="italic">Petstore.java</emphasis>.</para>
+
+			<example>
+				<title>Creating the PetStore RuleBase - extract from PetStore.java main() method</title>
+
+				<programlisting>PackageBuilder builder = new PackageBuilder();
+builder.addPackageFromDrl( new InputStreamReader( 
+PetStore.class.getResourceAsStream( "PetStore.drl" ) ) );
+RuleBase ruleBase = RuleBaseFactory.newRuleBase();
+ruleBase.addPackage( builder.getPackage() );
+
+//RuleB
+Vector stock = new Vector();
+stock.add( new Product( "Gold Fish",5 ) );
+stock.add( new Product( "Fish Tank", 25 ) );
+stock.add( new Product( "Fish Food", 2 ) );
+
+//The callback is responsible for populating working memory and
+// fireing all rules
+PetStoreUI ui = new PetStoreUI( stock, new CheckoutCallback( ruleBase ) );
+ui.createAndShowGUI();
+</programlisting>
+			</example>
+
+			<para>This code above loads the rules (drl) file from the classpath. Unlike other examples where the facts are asserted and fired straight away, this example defers this step to later. The way it does this is via the second last line where the PetStoreUI is created using a constructor the passes in the Vector called stock containing products, and an instance of the CheckoutCallback class containing the RuleBase that we have just loaded.</para>
+
+			<para>The actual Javacode that fires the rules is within the <emphasis role="italic">CheckoutCallBack.checkout()</emphasis> method. This is triggered (eventually) when the 'Checkout' button is pressed by the user.</para>
+
+			<example>
+				<title>Firing the Rules - extract from the CheckOutCallBack.checkout() method</title>
+
+				<programlisting>public String checkout(JFrame frame, List items) throws FactException {           
+    Order order = new Order();
+
+    //Iterate through list and add to cart
+    for ( int i = 0; i &lt; items.size(); i++ ) {
+        order.addItem( new Purchase( order, (Product) items.get( i ) ) );
+    }
+
+    //add the JFrame to the ApplicationData to allow for user interaction
+    WorkingMemory workingMemory = ruleBase.newStatefulSession();
+    workingMemory.setGlobal( "frame", frame );
+    workingMemory.setGlobal( "textArea",  this.output );
+
+    workingMemory.insert( new Product( "Gold Fish", 5 ) );
+    workingMemory.insert( new Product( "Fish Tank", 25 ) );
+    workingMemory.insert( new Product( "Fish Food",  2 ) );
+    workingMemory.insert( new Product( "Fish Food Sample", 0 ) );            
+           
+    workingMemory.insert( order );
+    workingMemory.fireAllRules();
+
+    //returns the state of the cart
+    return order.toString();
+}
+</programlisting>
+			</example>
+
+			<para>Two items get passed into this method; A handle to the JFrame Swing Component surrounding the output text frame (bottom of the GUI if / when you run the component). The second item is a list of order items; this comes from the TableModel the stores the information from the 'Table' area at the top right section of the GUI.</para>
+
+			<para>The <emphasis role="italic">for()</emphasis> loop transforms the list of order items coming from the GUI into the Order JavaBean (also contained in the PetStore.java file). Note that it would be possible to refer to the Swing dataset directly within the rules, but it is better coding practice to do it this way (using Simple Java Objects). It means that we are not tied to Swing if we wanted to transform the sample into a Web application.</para>
+
+			<para>It is important to note that <emphasis role="bold">all state in this example is stored in the Swing components, and that the rules are effectively stateless. </emphasis>Each time the 'Checkout' button is pressed, this code copies the contents of the Swing <emphasis>TableModel</emphasis> into the Session / Working Memory.</para>
+
+			<para>Within this code, there are nine calls to the working memory. The first of these creates a new workingMemory (statefulSession) from the Rulebase - remember that we passed in this Rulebase when we created the CheckoutCallBack class in the <emphasis role="italic">main()</emphasis> method. The next two calls pass in two objects that we will hold as Global variables in the rules - the Swing text area and Swing frame that we will use for writing messages later.</para>
+
+			<para>More inserts put information on products into the working memory, as well as the order list. The final call is the standard <emphasis role="italic">fireAllRules()</emphasis>. Next, we look at what this method causes to happen within the Rules file.</para>
+			
+			<example>
+				<title>Package, Imports , Globals and Dialect - extract (1) from PetStore.drl</title>
+
+				<programlisting>package org.drools.examples
+
+import org.drools.WorkingMemory
+import org.drools.examples.PetStore.Order
+import org.drools.examples.PetStore.Purchase
+import org.drools.examples.PetStore.Product
+import java.util.ArrayList
+import javax.swing.JOptionPane;
+
+import javax.swing.JFrame 
+        
+global JFrame frame 
+global javax.swing.JTextArea textArea
+ 
+dialect "mvel"
+</programlisting>
+			</example>
+    
+			<para>The first part of the <emphasis role="italic">PetStore.drl</emphasis> file contains the standard package and import statement to make various Java classes available to the rules. We've seen the dialect been defaulted to "mvel" before in other examples. What is new are the two globals <emphasis>frame and textArea. </emphasis>These hold references to the Swing JFrame and Textarea components that were previous passed by the Java code calling the <emphasis>setGlobal() </emphasis>method. Unlike normal variables in Rules , which expire as soon as the rule has fired, Global variables retain their value for the lifetime of the (Stateful in this case) Session.</para>
+
+			<para>The next extract (below) is from the <emphasis role="bold">end</emphasis> of the PetStore.drl file. It contains two functions that are referenced by the rules that we will look at shortly.</para>
+			
+			<example>
+				<title>Java Functions in the Rules - extract (2) from PetStore.drl</title>
+
+				<programlisting>function void doCheckout(JFrame frame, WorkingMemory workingMemory) {
+    Object[] options = {"Yes",
+                        "No"};
+                            
+    int n = JOptionPane.showOptionDialog(frame,
+                                         "Would you like to checkout?",
+                                         "",
+                                         JOptionPane.YES_NO_OPTION,
+                                         JOptionPane.QUESTION_MESSAGE,
+                                         null,
+                                         options,
+                                         options[0]);
+
+    if (n == 0) {
+        workingMemory.setFocus( "checkout" );
+    }   
+}
+
+function boolean requireTank(JFrame frame, WorkingMemory workingMemory, Order order, Product fishTank, int total) {
+    Object[] options = {"Yes",
+                        "No"};
+                            
+    int n = JOptionPane.showOptionDialog(frame,
+                                         "Would you like to buy a tank for your " + total + " fish?",
+                                         "Purchase Suggestion",
+                                         JOptionPane.YES_NO_OPTION,
+                                         JOptionPane.QUESTION_MESSAGE,
+                                         null,
+                                         options,
+                                         options[0]);
+                                             
+    System.out.print( "SUGGESTION: Would you like to buy a tank for your "
+                      + total + " fish? - " );
+
+    if (n == 0) {
+        Purchase purchase = new Purchase( order, fishTank );
+        workingMemory.insert( purchase );
+        order.addItem( purchase );
+        System.out.println( "Yes" );
+    } else {
+        System.out.println( "No" );
+    }      
+    return true;
+}
+</programlisting>
+			</example>
+  
+
+			<para>Having these functions in the rules file makes the PetStore sample more compact - in real life you probably have the functions in a file of their own (within the same rules package), or as a static method on a standard Java class (and import them using the <emphasis role="bold">import function my.package.Foo.hello </emphasis>syntax).</para>
+
+			<para>The above functions are</para>
+
+			<itemizedlist>
+				<listitem>
+					<para><emphasis role="italic">doCheckout()</emphasis> - Displays a dialog asking the user if they wish to checkout. If they do, focus is set to the <emphasis role="italic">checkOut</emphasis> agenda-group, allowing rules in that group to (potentially) fire.</para>
+				</listitem>
+
+				<listitem>
+					<para><emphasis role="italic">requireTank()</emphasis> - Displays a dialog asking the user if they wish to buy a tank. If so, a new FishTank <emphasis role="italic">Product</emphasis> added to the orderlist in working memory.</para>
+				</listitem>
+			</itemizedlist>
+			
+			<para>We'll see later the rules that call these functions.The next set of examples are from the PetStore rules themselves. The first extract is the one that happens to fire first (partly because it has the <emphasis role="italic">auto-focus</emphasis> attibute set to true).</para>
+				
+			<example>
+				<title>Putting each (individual) item into working memory - extract (3) from PetStore.drl</title>
+
+				<programlisting>// insert each item in the shopping cart into the Working Memory 
+rule "Explode Cart"
+    agenda-group "init"
+    auto-focus true    
+    salience 10
+    dialect "java"
+when
+    $order : Order( grossTotal == -1 )
+    $item : Purchase() from $order.items
+then
+   insert( $item );
+   drools.setFocus( "show items" );
+   drools.setFocus( "evaluate" );
+end
+
+</programlisting>
+			</example>
+
+			<para>This rule matches against all orders that do not yet have an Order.grossTotal calculated . It loops for each purchase item in that order. Some of the <emphasis role="italic">Explode Cart</emphasis> Rule should be familiar ; the rule name, the salience (suggesting of the order that the rules should be fired in) and the dialect set to <emphasis role="italic">java</emphasis>. There are three new items:</para>
+
+			<itemizedlist>
+				<listitem>
+					<para role="bold"><emphasis role="bold">agenda-group "init" </emphasis>- the name of the agenda group. In this case, there is only one rule in the group. However, nothing in Java code / nor a rule sets the focus to this group , so it relies on the next attibute for it's chance to fire.</para>
+				</listitem>
+
+				<listitem>
+					<para><emphasis role="bold">auto-focus true - </emphasis>This is the only rule in the sample, so when <emphasis role="italic">fireAllRules()</emphasis> is called from within the Java code, this rule is the first to get a chance to fire.</para>
+				</listitem>
+
+				<listitem>
+					<para><emphasis role="bold">drools.setFocus() </emphasis>This sets the focus to the <emphasis role="italic">show items </emphasis>and <emphasis role="italic">evaluate</emphasis> agenda groups in turn , giving their rules a chance to fire. In practice , we loop through all items on the order, inserting them into memory, then firing the other rules after each insert.</para>
+				</listitem>
+			</itemizedlist>
+
+			<para>The next two listings shows the rules within the <emphasis role="italic">show items </emphasis>and <emphasis role="italic">evaluate</emphasis> agenda groups. We look at them in the order that they are called.</para>
+				
+			<example>
+				<title>Show Items in the GUI extract (4) from PetStore.drl</title>
+
+				<programlisting>rule "Show Items"
+    agenda-group "show items"
+    dialect "mvel"
+when
+    $order : Order( )
+    $p : Purchase( order == $order )
+then
+   textArea.append( $p.product + "\n");
+end
+</programlisting>
+			</example>
+
+			<para>The <emphasis role="italic">show items</emphasis> agenda-group has only one rule, also called <emphasis role="italic">Show Items</emphasis> (note the difference in case). For each purchase on the order currently in the working memory (session) it logs details to the text area (at the bottom of the GUI). The <emphasis role="italic">textArea</emphasis> variable used to do this is one of the Global Variables we looked at earlier.</para>
+
+			<para>The <emphasis role="italic">evaluate</emphasis> Agenda group also gains focus from the <emphasis role="italic">explode cart </emphasis>rule above. This Agenda group has two rules (below) <emphasis role="italic">Free Fish Food Sample </emphasis> and <emphasis role="italic">Suggest Tank</emphasis>.</para>
+
+			<example>
+				<title>Evaluate Agenda Group extract (5) from PetStore.drl</title>
+
+				<programlisting>// Free Fish Food sample when we buy a Gold Fish if we haven't already  bought 
+// Fish Food and dont already have a Fish Food Sample
+rule "Free Fish Food Sample"
+    agenda-group "evaluate"
+    dialect "mvel"
+when
+    $order : Order()
+    not ( $p : Product( name == "Fish Food") &amp;&amp; Purchase( product == $p ) )
+    not ( $p : Product( name == "Fish Food Sample") &amp;&amp; Purchase( product == $p ) )
+    exists ( $p : Product( name == "Gold Fish") &amp;&amp; Purchase( product == $p ) )
+    $fishFoodSample : Product( name == "Fish Food Sample" );
+then
+    System.out.println( "Adding free Fish Food Sample to cart" );
+    purchase = new Purchase($order, $fishFoodSample);
+    insert( purchase );
+    $order.addItem( purchase ); 
+end
+
+// Suggest a tank if we have bought more than 5 gold fish and dont already have one
+rule "Suggest Tank"
+    agenda-group "evaluate"
+    dialect "java"
+when
+    $order : Order()
+    not ( $p : Product( name == "Fish Tank") &amp;&amp; Purchase( product == $p ) )
+    ArrayList( $total : size &gt; 5 ) from collect( Purchase( product.name == "Gold Fish" ) )
+    $fishTank : Product( name == "Fish Tank" )
+then
+    requireTank(frame, drools.getWorkingMemory(), $order, $fishTank, $total); 
+end
+</programlisting>
+			</example>
+      
+
+			<para>The <emphasis role="italic">Free Fish Food Sample</emphasis> rule will only fire if</para>
+
+			<itemizedlist>
+				<listitem>
+					<para>We <emphasis role="italic">don't </emphasis>already have any fish food.</para>
+				</listitem>
+
+				<listitem>
+					<para>We <emphasis role="italic">don't</emphasis> already have a free fish food sample.</para>
+				</listitem>
+
+				<listitem>
+					<para>We <emphasis role="italic">do</emphasis> have a Gold Fish in our order.</para>
+				</listitem>
+			</itemizedlist>
+
+			<para>If the rule does fire, it creates a new product (Fish Food Sample), and adds it to the Order in working memory.</para>
+
+			<para>The <emphasis role="italic">Suggest Tank</emphasis> rule will only fire if</para>
+
+			<itemizedlist>
+				<listitem>
+					<para>We <emphasis role="italic">don't </emphasis>already have a Fish Tank in our order</para>
+				</listitem>
+
+				<listitem>
+					<para>If we <emphasis role="italic">can</emphasis> find more than 5 Gold Fish Products in our order.</para>
+				</listitem>
+			</itemizedlist>
+
+			<para>If the rule does fire, it calls the <emphasis role="italic">requireTank</emphasis>() function that we looked at earlier (showing a Dialog to the user, and adding a Tank to the order / working memory if confirmed). When calling the <emphasis role="italic">requireTank</emphasis>() function the rule passes the global <emphasis role="italic">frame</emphasis> variable so that the function has a handle to the Swing GUI.</para>
+
+			<para>The next rule we look at is <emphasis role="italic">do checkout.</emphasis></para>
+				
+			<example>
+				<title>Doing the Checkout - extract (6) from PetStore.drl</title>
+
+				<programlisting>rule "do checkout"
+    dialect "java"
+    when
+    then
+        doCheckout(frame, drools.getWorkingMemory());
+end</programlisting>
+			</example>
+
+			<para>The <emphasis role="italic">do checkout</emphasis> rule has <emphasis role="bold">no agenda-group set and no auto-focus attribute</emphasis>. As such, is is deemed part of the default (MAIN) agenda-group - the same as the other non PetStore examples where agenda groups are not used. This group gets focus by default when all the rules/agenda-groups that explicity had focus set to them have run their course.</para>
+
+			<para>There is no LHS to the rule, so the RHS will always call the <emphasis role="italic">doCheckout</emphasis>() function. When calling the <emphasis role="italic">doCheckout</emphasis>() function the rule passes the global <emphasis role="italic">frame</emphasis> variable so the function has a handle to the Swing GUI. As we saw earlier, the <emphasis role="italic">doCheckout</emphasis>() function shows a confirmation dialog to the user. If confirmed, the function sets the focus to the <emphasis role="italic">checkout</emphasis> agenda-group, allowing the next lot of rules to fire.</para>
+
+			<example>
+				<title>Checkout Rules- extract (7) from PetStore.drl</title>
+
+				<programlisting>rule "Gross Total"
+    agenda-group "checkout"
+    dialect "mvel"
+when
+   $order : Order( grossTotal == -1)
+   Number( total : doubleValue ) from accumulate( Purchase( $price : product.price ),
+                 sum( $price ) )
+then
+    modify( $order ) { grossTotal = total };
+    textArea.append( "\ngross total=" + total + "\n" );
+end
+
+rule "Apply 5% Discount"
+    agenda-group "checkout"
+dialect "mvel"
+when
+   $order : Order( grossTotal &gt;= 10 &amp;&amp; &lt; 20 )
+then
+   $order.discountedTotal = $order.grossTotal * 0.95;
+   textArea.append( "discountedTotal total=" + $order.discountedTotal + "\n" );
+end
+
+
+rule "Apply 10% Discount"
+    agenda-group "checkout"
+dialect "mvel"
+when
+   $order : Order( grossTotal &gt;= 20 )
+then
+   $order.discountedTotal = $order.grossTotal * 0.90;
+   textArea.append( "discountedTotal total=" + $order.discountedTotal + "\n" );
+end
+</programlisting>
+			</example>
+
+			<para>There are three rules in the <emphasis role="italic">checkout</emphasis> agenda-group</para>
+
+			<itemizedlist>
+				<listitem>
+					<para><emphasis role="bold">Gross Total </emphasis> - if we haven't already calculated the gross total, accumulates the product prices into a total, puts this total into working memory, and displays it via the Swing TextArea (using the <emphasis role="italic">textArea </emphasis>global variable yet again).</para>
+				</listitem>
+
+				<listitem>
+					<para><emphasis role="bold">Apply 5% Discount</emphasis> - if our gross total is between 10 and 20, then calculate the discounted total and add it to working memory / display in the text area.</para>
+				</listitem>
+
+				<listitem>
+					<para><emphasis role="bold">Apply 10% Discount</emphasis> - if our gross total is equal to or greater than 20, calculate the discounted total and add it to working memory / display in the text area.</para>
+				</listitem>
+			</itemizedlist>
+			
+			<para>Now we've run through what happens in the code, lets have a look at what happens when we run the code for real. The <emphasis role="italic">PetStore.java </emphasis>example contains a <emphasis role="italic">main()</emphasis> method, so it can be run as a standard Java application (either from the command line or via the IDE). This assumes you have your classpath set correctly (see the start of the examples section for more information).</para>
+
+			<para>The first screen that we see is the Pet Store Demo. It has a List of available products (top left) , an empty list of selected products (top right), checkout and reset buttons (middle) and an empty system messages area (bottom).</para>
+
+			<figure>
+				<title>Figure 1 - PetStore Demo just after Launch</title>
+
+				<mediaobject>
+					<imageobject>
+						<imagedata fileref="PetstoreExample/1-PetStore-Start-Screen.png" />
+					</imageobject>
+				</mediaobject>
+			</figure>
+			
+			<para>To get to this point, the following things have happened:</para>
+
+			<orderedlist>
+				<listitem>
+					<para>The <emphasis role="italic">main()</emphasis> method has run and loaded the RuleBase <emphasis role="bold">but not yet fired the rules</emphasis>. This is the only rules related code to run so far.</para>
+				</listitem>
+
+				<listitem>
+					<para>A new <emphasis role="italic">PetStoreUI</emphasis> class is created and given a handle to the RuleBase (for later use).</para>
+				</listitem>
+
+				<listitem>
+					<para>Various Swing Components do their stuff, and the above screen is shown and <emphasis role="bold">waits for user input</emphasis>.</para>
+				</listitem>
+			</orderedlist>
+			
+			<para>Clicking on various products from the list might give you a screen similar to the one below.</para>
+
+			<figure>
+				<title>Figure 2 - PetStore Demo with Products Selected</title>
+
+				<mediaobject>
+					<imageobject>
+						<imagedata fileref="PetstoreExample/2-stock-added-to-order-list.png" />
+					</imageobject>
+				</mediaobject>
+			</figure>
+			
+			<para>Note that <emphasis role="bold">no rules code has been fired here</emphasis>. This is only swing code, listening for the mouse click event, and added the clicked product to the <emphasis>TableModel</emphasis> object for display in the top right hand section (as an aside , this is a classic use of the Model View Controller - MVC - design pattern).</para>
+
+			<para>It is only when we press the <emphasis role="bold">Checkout</emphasis> that we fire our business rules, in roughly the same order that we walked through the code earlier.</para>
+
+			<orderedlist>
+				<listitem>
+					<para>The <emphasis role="italic">CheckOutCallBack.checkout()</emphasis> method is called (eventually) by the Swing class waiting for the click on the checkout button. This inserts the data from the <emphasis>TableModel</emphasis> object (top right hand side of the GUI), and handles from the GUI into the session / working memory. It then fires the rules.</para>
+				</listitem>
+
+				<listitem>
+					<para>The <emphasis role="italic">Explode Cart</emphasis> rule is the first to fire, given that has <emphasis role="italic">auto-focus </emphasis>set to true. It loops through all the products in the cart, makes sure the products are in the working memory, then gives the <emphasis role="italic">Show Items</emphasis> and <emphasis role="italic">Evaluation</emphasis> agenda groups a chance to fire. The rules in these groups, add the contents of the cart to the text area (bottom), decide whether or not to give us free fish food and whether to ask if we want to buy a fish tank (Figure 3 below).</para>
+				</listitem>
+			</orderedlist>
+
+			<figure>
+				<title>Figure 3 - Do we want to buy a fish tank?</title>
+
+				<mediaobject>
+					<imageobject>
+						<imagedata fileref="PetstoreExample/3-purchase-suggestion.png" />
+					</imageobject>
+				</mediaobject>
+			</figure>
+
+			<orderedlist>
+				<listitem>
+					<para>The <emphasis role="italic">Do Checkout</emphasis> rule is the next to fire as it (a) No other agenda group currently has focus and (b) it is part of the default (MAIN) agenda group. It always calls the<emphasis role="italic"> doCheckout() function </emphasis>which displays a 'Would you like to Checkout?' Dialog Box.</para>
+				</listitem>
+
+				<listitem>
+					<para>The <emphasis role="italic">doCheckout() function</emphasis> sets the focus to the <emphasis role="italic">checkout </emphasis>agenda-group, giving the rules in that group the option to fire.</para>
+				</listitem>
+
+				<listitem>
+					<para>The rules in the the <emphasis role="italic">checkout</emphasis> agenda-group, display the contents of the cart and apply the appropriate discount.</para>
+				</listitem>
+
+				<listitem>
+					<para><emphasis role="bold">Swing then waits for user input</emphasis> to either checkout more products (and to cause the rules to fire again) or to close the GUI - Figure 4 below.</para>
+				</listitem>
+			</orderedlist>
+
+			<figure>
+				<title>Figure 4 - Petstore Demo after all rules have fired.</title>
+
+				<mediaobject>
+					<imageobject>
+						<imagedata fileref="PetstoreExample/4-Petstore-final-screen.png" />
+					</imageobject>
+				</mediaobject>
+			</figure>
+
+			<para>Should we choose, we could add more System.out calls to demonstrate this flow of events. The current output of the console of the above sample is as per the listing below.</para>
+	
+			<example>
+				<title>Console (System.out) from running the PetStore GUI</title>
+
+				<programlisting>Adding free Fish Food Sample to cart 
+SUGGESTION: Would you like to buy a tank for your 6 fish? - Yes</programlisting>
+			</example>
+     
+
+			<!---<para>Todo : Add Audit and Agenda Views for this sample.</para>-->
+		</section>
\ No newline at end of file

Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-PricingExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-PricingExample.xml	                        (rev 0)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-PricingExample.xml	2008-06-14 16:26:55 UTC (rev 20482)
@@ -0,0 +1,81 @@
+<?xml version="1.0" encoding="UTF-8"?>
+	<section xml:base="../" >
+
+		<title>Pricing Rule Decision Table Example</title>
+
+		<para>The Pricing Rule decision table demonstrates the use of a decision table in a spreadsheet (XLS format) in calculating the retail cost of an insurance policy. The purpose of the set of rules provided is to calculate a base price, and an additional discount for a car driver applying for a specific policy. The drivers age, history and the policy type all contribute to what the basic premium is, and an additional chunk of rules deals with refining this with a subtractive percentage discount.</para>
+
+		<programlisting><emphasis role="bold">Name:</emphasis> Example Policy Pricing
+<emphasis role="bold">Main class:</emphasis> org.drools.examples.PricingRuleDTExample
+<emphasis role="bold">Type:</emphasis> java application
+<emphasis role="bold">Rules file:</emphasis> ExamplePolicyPricing.xls
+<emphasis role="bold">Objective:</emphasis> demonstrate spreadsheet based decision tables.    </programlisting>
+
+		<section>
+			<title>Executing the example</title>
+
+			<para>Open the PricingRuleDTExample.java and execute it as a Java application. It should produce the following console output:</para>
+
+			<programlisting>Cheapest possible
+BASE PRICE IS: 120
+DISCOUNT IS: 20     </programlisting>
+
+			<para>The code to the execute the example is very similar to the other examples. The rules are loaded, the facts inserted and a stateless session is used. What is different is how the rules are obtained:</para>
+
+			<programlisting>SpreadsheetCompiler compiler = new SpreadsheetCompiler();
+String drl = compiler.compile(getSpreadsheetStream(), InputType.XLS);
+</programlisting>
+
+			<para>Note the use of the SpreadsheetCompiler class. It is what takes the XLS (as a binary InputStream to the XLS file), and outputs ordinary DRL (which is then dealt with in the usual way). You can (if you like) also print out the DRL. If you use the BRMS, all this is of course taken care of for you.</para>
+
+			<para>There are 2 facts used in this example, Driver, and Policy. Both are used with their default values. The Driver is 30 years old, has had no prior claims and currently has a risk profile of LOW. The Policy being applied for is COMPREHENSIVE, and the policy has not yet been approved.</para>
+		</section>
+		
+		<section>
+			<title>The decision table</title>
+
+			<para>In this decision table, each row is a rule, and each column is a condition or an action.</para>
+
+			<figure>
+				<title>Decision table configuration</title>
+
+				<mediaobject>
+					<imageobject>
+						<imagedata fileref="PricingExample/DT_Config.png" />
+					</imageobject>
+				</mediaobject>
+			</figure>
+
+			<para>Referring to the above, we have the RuleSet declaration, which provides the package name. There are also other optional items you can have here, such as Variables for global variables, and Imports for importing classes. In this case, the namespace of the rules is the same as the fact classes we are using, so we can omit it.</para>
+
+			<para>Moving further down, we can see the RuleTable declaration. The name after this (Pricing bracket) is used as the prefix for all the generated rules. Below that, we have CONDITION or ACTION - this indicates the purpose of the column (ie does it form part of the condition, or an action of a rule that will be generated).</para>
+
+			<para>You can see there is a Driver which is spanned across 3 cells, this means the template expressions below it apply to that fact. So we look at the drivers age range (which uses $1 and $2 with comma separated values), locationRiskProfile, and priorClaims in the respective columns. In the action columns, we are setting the policy base price, and then logging a message.</para>
+
+			<figure>
+				<title>Base price calculation</title>
+
+				<mediaobject>
+					<imageobject>
+						<imagedata fileref="PricingExample/DT_Table1.png" />
+					</imageobject>
+				</mediaobject>
+			</figure>
+
+			<para>Referring to the above, we can see there are broad category brackets (indicated by the comment in the left most column). As we know the details of our driver and their policy, we can tell (with a bit of thought) that they should match row number 18, as they have no prior accidents, and are 30 years old. This gives us a base price of 120.</para>
+
+			<figure>
+				<title>Discount calculation</title>
+
+				<mediaobject>
+					<imageobject>
+						<imagedata fileref="PricingExample/DT_Table2.png" />
+					</imageobject>
+				</mediaobject>
+			</figure>
+
+			<para>Referring to the above, we are seeing if there is any discount we can give our driver. Based on the Age bracket, number of priot claims, and the policy type, a discount is provided. In our case, the drive is 3, with no priors, and they are applying for COMPREHENSIVE, this means we can give a discount of 20%. Note that this is actually a separate table, but in the same worksheet. This different templates apply.</para>
+
+			<para>It is important to note that decision tables generate rules, this means they aren't simply top down logic, but more a means to capture data that generate rules (this is a subtle difference that confuses some people). The evaluation of the rules is not "top down" necessarily, all the normal indexing and mechanics of the rule engine still apply.</para>
+		</section>
+	</section>	
\ No newline at end of file

Added: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-ShoppingExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-ShoppingExample.xml	                        (rev 0)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/Section-ShoppingExample.xml	2008-06-14 16:26:55 UTC (rev 20482)
@@ -0,0 +1,107 @@
+<?xml version="1.0" encoding="UTF-8"?>
+	<section xml:base="../" >
+		<title>Shopping Example</title>
+
+		<programlisting><emphasis role="bold">Name:</emphasis>Shopping Example
+<emphasis role="bold">Main class:</emphasis> org.drools.examples.ShoppingExample
+<emphasis role="bold">Type:</emphasis> java application
+<emphasis role="bold">Rules file:</emphasis> Shopping.drl
+<emphasis role="bold">Objective:</emphasis> demonstrate truth maintenance, accumulate
+</programlisting>
+
+		<para>The shopping example simulates a very simple shopping cart type application, where the idea is to track a users purchases in a stateful session, and apply discounts as appropriate.</para>
+		
+		<section>
+			<title>Running the example</title>
+
+			<para>The following is a listing of the interesting parts that are used to launch the example:</para>
+
+			<programlisting>Customer mark = new Customer( "mark",
+                              0 );
+session.insert( mark );
+Product shoes = new Product( "shoes",
+                             60 );
+session.insert( shoes );
+Product hat = new Product( "hat",
+                           60 );
+session.insert( hat );
+session.insert( new Purchase( mark,
+                              shoes ) );
+FactHandle hatPurchaseHandle = session.insert( new Purchase( mark,
+                                                             hat ) );
+session.fireAllRules();
+session.retract( hatPurchaseHandle );
+System.out.println( "Customer mark has returned the hat" );
+session.fireAllRules();      </programlisting>
+
+			<para>Refering the the above listing, we can see there is a Customer ("mark"), and there are 2 Products ("shoes" and "hat") which are available for Purchase. In this case, a Purchase combines a customer with a product (and a product has a price attribute).</para>
+
+			<para>Note that after we fireAllRules(), we then retract the purchase of a hat (but leave the purchase of shoes in). Running the example as a java application should see the following output:</para>
+
+			<programlisting>Customer mark just purchased hat
+Customer mark just purchased shoes
+Customer mark now has a shopping total of 120.0
+Customer mark now has a discount of 10
+Customer mark has returned the hat
+Customer mark now has a discount of 0      </programlisting>
+
+		</section>
+
+		<section>
+			<title>Discounts and purchases</title>
+
+			<para>We want to give discounts to customers who purchase stuff of enough value. This discount could also be removed should the customer decide not to purchase enough to fall within the threshold.</para>
+
+			<programlisting>rule "Purchase notification"
+    salience 10
+
+ when
+  $c : Customer()
+  $p : Purchase( customer == $c)	    
+ then
+     System.out.println( "Customer " + $c.name + " just purchased " + $p.product.name );
+end 
+
+rule "Discount removed notification"
+ when
+     $c : Customer()
+  not Discount( customer == $c )
+ then
+  $c.discount = 0 ;
+  System.out.println( "Customer " + $c.name + " now has a discount of " + $c.discount );
+end
+
+rule "Discount awarded notification"
+ when
+     $c : Customer()
+     $d : Discount( customer == $c )
+ then
+  System.out.println( "Customer " + $c.name + " now has a discount of " + $d.amount );
+end      </programlisting>
+
+			<para>The "Purchase notification" rule simply makes note of the purchase event for a given customer. The "Discount removed notification" rule removes the customer discount (by checking for the non existence of a discount for that customer). The "Discount awarded notification" simply makes not of the fact that the discount was applied.</para>
+		</section>
+		
+		<section>
+			<title>Calculating the discount</title>
+
+			<para>Calculating the discount is done with a single rule, using the higher order logic of "accumulate".</para>
+
+			<programlisting>rule "Apply 10% discount if total purcahses is over 100"
+ no-loop true
+ dialect "java"
+    when
+      $c : Customer()
+      $i : Double(doubleValue  &gt; 100) from accumulate ( Purchase( customer == $c, $price : product.price ), 
+                                                            sum( $price ) )
+    then
+      $c.setDiscount( 10 );
+      insertLogical( new Discount($c, 10) );
+      System.out.println( "Customer " + $c.getName() + " now has a shopping total of " + $i );
+end      </programlisting>
+
+			<para>An interesting part of this rule is the "accumulate": this is saying to accumulate a total (sum) of the $price of a product (product.price) for all Purchase facts that belong to the customer ($c). The result of this is a Double. The rule then checks to see if this total is greater then 100. If it is, it applies the discount (of 10), and then inserts a logical fact of the Discount object.</para>
+
+			<para>The purpose of the logical insertion of the Discount, is to automatically retract the Discount object should the total of the purchases not add up to &gt; 100 (when the LHS is no longer satisified, restract the resulting logical assertions - this is what is meant by "truth maintenance"). The act of inserting the Discount, causes the "Discount awarded notification" rule to activate. However, should the discount fact be retracted, the "Discount removed notification" will activate, resulting in the customers discount being wiped out. In the example you can see this happen, as after the first fireAllRules(), a purchase is retracted, causing the total to fall below 100, which means the conditions that satisfied the "Apply 10% discount..." rule no longer apply, hence the logical fact of "Discount" is automatically retracted.</para>
+		</section>
+	</section>
\ No newline at end of file

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExample (from rev 20480, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExampleExample)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExample/state_example_agenda1.png
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExample/state_example_agenda1.png (from rev 20481, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExampleExample/state_example_agenda1.png)
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExample/state_example_audit1.png
===================================================================
(Binary files differ)

Copied: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExample/state_example_audit1.png (from rev 20481, labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/StateExampleExample/state_example_audit1.png)
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/conway1.jpg
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/conway2.jpg
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/conway_ruleflow_generation.png
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/insurance-ruleflow.png
===================================================================
(Binary files differ)

Deleted: labs/jbossrules/trunk/drools-docs/drools-docs-expert/en/Chapter-Examples/insurance-website.png
===================================================================
(Binary files differ)




More information about the jboss-svn-commits mailing list