[jboss-svn-commits] JBL Code SVN: r24308 - labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples.

jboss-svn-commits at lists.jboss.org jboss-svn-commits at lists.jboss.org
Mon Dec 8 16:21:26 EST 2008


Author: Rikkola
Date: 2008-12-08 16:21:26 -0500 (Mon, 08 Dec 2008)
New Revision: 24308

Modified:
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-BankingExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-FibonacciExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-HelloWorldExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-HonestPoliticianExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-MannersExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-NumberGuessExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-PetStoreExample.xml
   labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-PricingExample.xml
Log:
Updated the drools-api to examples in the documentations

Modified: labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-BankingExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-BankingExample.xml	2008-12-08 18:34:44 UTC (rev 24307)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-BankingExample.xml	2008-12-08 21:21:26 UTC (rev 24308)
@@ -16,40 +16,42 @@
 
 		<para>This tutorial will demonstrate the process of developing a complete personal banking application that will handle credits, debits, currencies and that will use a set of design patterns that have been created for the process. In order to make the examples documented here clear and modular, I will try and steer away from re-visiting existing code to add new functionality, and will instead extend and inject where appropriate.</para>
 
-		<para>The RuleRunner class is a simple harness to execute one or more drls against a set of data. It compiles the Packages and creates the RuleBase for each execution, this allows us to easy execute each scenario and see the outputs. In reality this is not a good solution for a production system where the RuleBase should be built just once and cached, but for the purposes of this tutorial it shall suffice.</para>
+		<para>The RuleRunner class is a simple harness to execute one or more drls against a set of data. It compiles the Packages and creates the KnowledgeBase for each execution, this allows us to easy execute each scenario and see the outputs. In reality this is not a good solution for a production system where the KnowledgeBase should be built just once and cached, but for the purposes of this tutorial it shall suffice.</para>
 
 		<example>
 			<title>Banking Tutorial : RuleRunner</title>
 
-			<programlisting>public class RuleRunner {
-
-    public RuleRunner() {
-    }
-
-    public void runRules(String[] rules,
-                         Object[] facts) throws Exception {
-
-        RuleBase ruleBase = RuleBaseFactory.newRuleBase();
-        PackageBuilder builder = new PackageBuilder();
-
-        for ( int i = 0; i &lt; rules.length; i++ ) {
-            String ruleFile = rules[i];
-            System.out.println( "Loading file: " + ruleFile );            
-            builder.addPackageFromDrl(new InputStreamReader( RuleRunner.class.getResourceAsStream( ruleFile ) ) );
-        }
-
-        Package pkg = builder.getPackage();
-        ruleBase.addPackage( pkg );
-        WorkingMemory workingMemory = ruleBase.newStatefulSession();
-
-        for ( int i = 0; i &lt; facts.length; i++ ) {
-            Object fact = facts[i];
-            System.out.println( "Inserting fact: " + fact );
-            workingMemory.insert( fact );
-        }
-
-        workingMemory.fireAllRules();
-    }
+			<programlisting>public class RuleRunner {
+
+    public RuleRunner() {
+    }
+
+    public void runRules(String[] rules,
+                         Object[] facts) throws Exception {
+
+        KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
+        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
+
+        for ( int i = 0; i < rules.length; i++ ) {
+            String ruleFile = rules[i];
+            System.out.println( "Loading file: " + ruleFile );
+            kbuilder.add( ResourceFactory.newClassPathResource( ruleFile,
+                                                                        RuleRunner.class ),
+                                  ResourceType.DRL );
+        }
+
+        Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
+        kbase.addKnowledgePackages( pkgs );
+        StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
+
+        for ( int i = 0; i < facts.length; i++ ) {
+            Object fact = facts[i];
+            System.out.println( "Inserting fact: " + fact );
+            ksession.insert( fact );
+        }
+
+        ksession.fireAllRules();
+    }
 }</programlisting>
 		</example>
 
@@ -595,4 +597,4 @@
 </programlisting>
 		</example>
 		
-	</section>
\ No newline at end of file
+	</section>

Modified: labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-FibonacciExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-FibonacciExample.xml	2008-12-08 18:34:44 UTC (rev 24307)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-FibonacciExample.xml	2008-12-08 21:21:26 UTC (rev 24308)
@@ -74,8 +74,8 @@
 		<example>
 			<title>Fibonacci Example Execution</title>
 
-			<programlisting>session.insert( new Fibonacci( 50 ) );
-session.fireAllRules();</programlisting>
+			<programlisting>ksession.insert( new Fibonacci( 50 ) );
+ksession.fireAllRules();</programlisting>
 		</example>
 
 		<para>The recurse rule is very simple, it matches each asserted Fibonacci object with a value of -1, it then creates and asserts a new Fibonacci object with a sequence of one less than the currently matched object. Each time a Fibonacci object is added, as long as one with a "sequence == 1" does not exist, the rule re-matches again and fires; causing the recursion. The 'not' conditional element is used to stop the rule matching once we have all 50 Fibonacci objects in memory. The rule also has a salience value, this is because we need to have all 50 Fibonacci objects asserted before we execute the Bootstrap rule.</para>
@@ -172,4 +172,4 @@
 				</imageobject>
 			</mediaobject>
 		</figure>
-	</section>
\ No newline at end of file
+	</section>

Modified: labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-HelloWorldExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-HelloWorldExample.xml	2008-12-08 18:34:44 UTC (rev 24307)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-HelloWorldExample.xml	2008-12-08 21:21:26 UTC (rev 24308)
@@ -17,63 +17,57 @@
   <para>The "Hello World" example shows a simple example of rules usage, and
   both the MVEL and Java dialects.</para>
 
-  <para>In this example it will be shown how to build rulebases and sessions
+  <para>In this example it will be shown how to build knowledgebases and sessions
   and how to add audit logging and debug outputs, this information is ommitted
-  from other examples as it's all very similar. PackageBuilder is used to turn
-  a drl source file into Package objects which the RuleBase can consume,
-  addPackageFromDrl takes a Reader interface as the parameter. Reader can be
+  from other examples as it's all very similar. KnowledgeBuilder is used to turn
+  a drl source file into Package objects which the KnowledgeBase can consume,
+  add takes a Resource interface and ResourceType as parameters. Resource can be 
   used to retrieve a source drl file from various locations, in this case the
-  drl file is being retrieved from the classpath as an InputStream which we
-  turn into a Reader by wrapping it with InputStreamReader; but it could come
-  the disk or a url. The use of the Reader interface means that Drools does
-  not have to care. In this case we only add a single drl source file, but
-  multiple drl files can be added and all are merged into a single Package.
-  All drl files added to the PackageBuilder must declare themselves in the
-  same package namespace, if you wish to build a Package in a different
-  namespace a new instance of PackageBuilder must be created; multiple
-  packages of differerent namespaces can be added to the same RuleBase. When
+  drl file is being retrieved from the classpath using ResourceFactory; but it could come from
+  the disk or a url. In this case we only add a single drl source file, but
+  multiple drl files can be added. Drl files with different namespaces can be added, 
+  KnowledgeBuilder creates a package for each namespace. Multiple
+  packages of different namespaces can be added to the same KnowledgeBase. When
   all the drl files have been added we should check the builder for errors;
-  while the RuleBase will validate the packge it will only have access to the
+  while the KnowledgeBase will validate the package it will only have access to the
   error information as a String, so if you wish to debug the error information
   you should do it on the builder instance. Once we know the builder is error
-  free get the Package, instantiate a RuleBase from the RuleBaseFactory and
-  add the package.</para>
+  free get the Package collection, instantiate a KnowledgeBase from the KnowledgeBaseFactory and
+  add the package collection.</para>
 
   <example>
-    <title>HelloWorld example: Creating the RuleBase and Session</title>
+    <title>HelloWorld example: Creating the KnowledgeBase and Session</title>
 
-    <programlisting>//read in the source
-Reader source = new InputStreamReader( HelloWorldExample.class.getResourceAsStream( "HelloWorld.drl" ) );
+    <programlisting>final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
 
-PackageBuilder builder = new PackageBuilder();
+// this will parse and compile in one step
+kbuilder.add(ResourceFactory.newClassPathResource("HelloWorld.drl",
+				HelloWorldExample.class), ResourceType.DRL);
 
-//this will parse and compile in one step
-builder.addPackageFromDrl( source );
-
 // Check the builder for errors
-if ( builder.hasErrors() ) {
-    System.out.println( builder.getErrors().toString() );
-    throw new RuntimeException( "Unable to compile \"HelloWorld.drl\".");
+if (kbuilder.hasErrors()) {
+	System.out.println(kbuilder.getErrors().toString());
+	throw new RuntimeException("Unable to compile \"HelloWorld.drl\".");
 }
 
-//get the compiled package (which is serializable)
-Package pkg = builder.getPackage();
+// get the compiled packages (which are serializable)
+final Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
 
-//add the package to a rulebase (deploy the rule package).
-RuleBase ruleBase = RuleBaseFactory.newRuleBase();
-ruleBase.addPackage( pkg );
+// add the packages to a knowledgebase (deploy the knowledge packages).
+final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
+kbase.addKnowledgePackages(pkgs);
 
-StatefulSession session = ruleBase.newStatefulSession();</programlisting>
+final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();</programlisting>
   </example>
 
   <para>Drools has an event model that exposes much of what's happening
   internally, two default debug listeners are supplied
   DebugAgendaEventListener and DebugWorkingMemoryEventListener which print out
   debug event information to the err console, adding listeners to a session is
-  trivial and shown below. The WorkingMemoryFileLogger provides execution
+  trivial and shown below. The KnowledgeRuntimeLogger provides execution
   auditing which can be viewed in a graphical viewer; it's actually a
   specialised implementation built on the agenda and working memory listeners,
-  when the engine has finished executing logger.writeToDisk() must be
+  when the engine has finished executing logger.close() must be
   called.</para>
 
   <para>Most of the examples use the Audit logging features of Drools to
@@ -87,8 +81,7 @@
 session.addEventListener( new DebugWorkingMemoryEventListener() );
         
 // setup the audit logging
-WorkingMemoryFileLogger logger = new WorkingMemoryFileLogger( session );
-logger.setFileName( "log/helloworld" );     </programlisting>
+KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "log/helloworld");</programlisting>
   </example>
 
   <para>The single class used in this example is very simple, it has two
@@ -118,23 +111,23 @@
   <example>
     <title>HelloWorld example: Execution</title>
 
-    <programlisting>Message message = new Message();
-message.setMessage( "Hello World" );
-message.setStatus( Message.HELLO );
-session.insert( message );
-        
-session.fireAllRules();
-        
-logger.writeToDisk();
-      
-session.dispose();    </programlisting>
+    <programlisting>final Message message = new Message();
+message.setMessage("Hello World");
+message.setStatus(Message.HELLO);
+ksession.insert(message);
+
+ksession.fireAllRules();
+
+logger.close();
+
+ksession.dispose();    </programlisting>
   </example>
 
   <para>To execute the example from Java.</para>
 
   <orderedlist>
     <listitem>
-      <para>Open the class org.drools.examples.FibonacciExample in your
+      <para>Open the class org.drools.examples.HelloWorldExample in your
       Eclipse IDE</para>
     </listitem>
 
@@ -145,7 +138,7 @@
   </orderedlist>
 
   <para>If we put a breakpoint on the fireAllRules() method and select the
-  session variable we can see that the "Hello World" view is already activated
+  ksession variable we can see that the "Hello World" view is already activated
   and on the Agenda, showing that all the pattern matching work was already
   done during the insert.</para>
 
@@ -267,8 +260,8 @@
 end</programlisting>
   </example>
 
-  <para>If you remember at the start of this example in the java code we
-  created a WorkingMemoryFileLogger and called logger.writeToDisk() at the
+  <para>If you remember at the start of this example in the java code we used KnowledgeRuntimeLoggerFactory.newFileLogger to create a KnowledgeRuntimeLogger
+  and called logger.close() at the
   end, this created an audit log file that can be shown in the Audit view. We
   use the audit view in many of the examples to try and understand the example
   execution flow. In the view below we can see the object is inserted which
@@ -288,4 +281,4 @@
       </imageobject>
     </mediaobject>
   </figure>
-</section>
\ No newline at end of file
+</section>

Modified: labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-HonestPoliticianExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-HonestPoliticianExample.xml	2008-12-08 18:34:44 UTC (rev 24307)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-HonestPoliticianExample.xml	2008-12-08 21:21:26 UTC (rev 24308)
@@ -30,12 +30,12 @@
 Politician chirac  = new Politician("chirac", true);
 Politician schroder   = new Politician("schroder", true);
         
-session.insert( blair );
-session.insert( bush );
-session.insert( chirac );
-session.insert( schroder );
+ksession.insert( blair );
+ksession.insert( bush );
+ksession.insert( chirac );
+ksession.insert( schroder );
 
-session.fireAllRules();</programlisting>
+ksession.fireAllRules();</programlisting>
       </example>The console out shows that while there is atleast one honest
     polician democracy lives, however as each politician is in turn corrupted
     by an evil corporation, when all politicians are dishonest democracy is
@@ -91,7 +91,7 @@
     iterates over those rules firing each one in turn, corrupting each
     politician so that they are no longer honest. When all four politicians
     have been corrupted we have no politicians with the property "honest ==
-    true" thus the rule "We hvae an honest Politician" is no longer true and
+    true" thus the rule "We have an honest Politician" is no longer true and
     the object it logical inserts "new Hope()" is automatically
     retracted.</para>
 

Modified: labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-MannersExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-MannersExample.xml	2008-12-08 18:34:44 UTC (rev 24307)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-MannersExample.xml	2008-12-08 21:21:26 UTC (rev 24308)
@@ -304,21 +304,27 @@
         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 );
+        <programlisting>rule assignFirstSeat
+    when
+        context : Context( state == Context.START_UP )
+        guest : Guest()
+        count : Count()
+    then
+        String guestName = guest.getName();
+        
+        Seating seating =  new Seating( count.getValue(), 1, true, 1, guestName, 1, guestName);
+        insert( seating );
+        
+        Path path = new Path( count.getValue(), 1, guestName );
+        insert( path );
+        
+        modify( count ) { setValue ( count.getValue() + 1 )  }
+
+		System.out.println( "assign first seat :  " + seating + " : " + path );
+
+        modify( context ) {
+            setState( Context.ASSIGN_SEATS )
+        } 
 end</programlisting>
       </section>
 
@@ -330,28 +336,35 @@
         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 );
+        <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();
+       
+       Seating seating = new Seating( countValue, seatId, false, rightSeat, $s.getRightGuestName(), rightSeat + 1, $g2.getName() );
+       insert( seating );     
+                            
+       Path path = new Path( countValue, rightSeat + 1, $g2.getName()  );
+       insert( path );
+       
+       Chosen chosen = new Chosen( seatId, $g2.getName(), $g1.getHobby() );
+       insert( chosen  );
+
+	   System.err.println( "find seating : " + seating + " : " + path + " : " + chosen);
+
+       modify( count ) {setValue(  countValue + 1 )}        
+       modify( context ) {setState( Context.MAKE_PATH )} 
 end</programlisting>
 
         <para>However, as can be seen from the printed results shown earlier,
@@ -408,16 +421,14 @@
         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 );
+        <programlisting>rule pathDone
+    when
+        context : Context( state == Context.MAKE_PATH ) 
+        seating : Seating( pathDone == false ) 
+    then
+        modify( seating ) {setPathDone( true )} 
+        
+		modify( context ) {setState( Context.CHECK_DONE)}
 end</programlisting>
 
         <figure>
@@ -445,23 +456,21 @@
         "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 );
+        <programlisting>rule areWeDone
+    when
+        context : Context( state == Context.CHECK_DONE ) 
+        LastSeat( lastSeat: seat )
+        Seating( rightSeat == lastSeat ) 
+    then
+        modify( context ) {setState(Context.PRINT_RESULTS )}
 end
 </programlisting>
 
-        <programlisting>rule continue
-    when
-        context : Context( state == Context.CHECK_DONE ) 
-    then
-        context.setState( Context.ASSIGN_SEATS ); 
-        update( context );
+        <programlisting>rule continue
+    when
+        context : Context( state == Context.CHECK_DONE ) 
+    then
+        modify( context ) {setState( Context.ASSIGN_SEATS )}
 end
 </programlisting>
       </section>
@@ -609,4 +618,4 @@
 =&gt;[fid:32:49]:[Chosen id=4, name=n1, hobbies=h1]
 </literallayout>
     </section>
-  </section>
\ No newline at end of file
+  </section>

Modified: labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-NumberGuessExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-NumberGuessExample.xml	2008-12-08 18:34:44 UTC (rev 24307)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-NumberGuessExample.xml	2008-12-08 21:21:26 UTC (rev 24308)
@@ -24,44 +24,50 @@
         <title>Creating the Number Guess RuleBase - extract 1 from
         NumberGuessExample.java main() method</title>
 
-        <programlisting>final PackageBuilder builder = new PackageBuilder();
+        <programlisting>final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
+        kbuilder.add( ResourceFactory.newClassPathResource( "NumberGuess.drl",
+                                                                    ShoppingExample.class ),
+                              ResourceType.DRL );
+        kbuilder.add( ResourceFactory.newClassPathResource( "NumberGuess.rf",
+                                                                    ShoppingExample.class ),
+                              ResourceType.DRF );
+
+        final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
+        kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
 
-builder.addPackageFromDrl( new InputStreamReader( 
-         ShoppingExample.class.getResourceAsStream( "NumberGuess.drl" ) ) );
-builder.addRuleFlow( new InputStreamReader( 
-         ShoppingExample.class.getResourceAsStream( "NumberGuess.rfm" ) ) );
-
-final RuleBase ruleBase = RuleBaseFactory.newRuleBase();
-ruleBase.addPackage( builder.getPackage() );
-
 </programlisting>
       </example>
 
       <para>The creation of the package, and the loading of the rules (using
-      the addPackageFromDrl() method ) is the same as the previous examples.
-      There is a additional line to add the RuleFlow (NumberGuess.rfm) as you
-      have the option of specifying different ruleflows for the same RuleBase.
-      Otherwise the RuleBase is created in the same manner as before.</para>
+      the add() method ) is the same as the previous examples.
+      There is a additional line to add the RuleFlow (NumberGuess.rf) as you
+      have the option of specifying different ruleflows for the same KnowledgeBase.
+      Otherwise the KnowledgeBase is created in the same manner as before.</para>
 
       <example>
         <title>Starting the RuleFlow - extract 2 from NumberGuessExample.java
         main() method</title>
 
-        <programlisting>final StatefulSession session = ruleBase.newStatefulSession();
+        <programlisting>final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
+
+        KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, "log/numberguess");
+
+        ksession.insert( new GameRules( 100,
+                                        5 ) );
+        ksession.insert( new RandomNumber() );
+        ksession.insert( new Game() );
+
+        ksession.startProcess( "Number Guess" );
+        ksession.fireAllRules();
+
+        logger.close();
+
+        ksession.dispose();
 
-session.insert( new GameRules( 100,  5 ) );
-session.insert( new RandomNumber() );
-session.insert( new Game() );
-
-session.startProcess( "Number Guess" );
-session.fireAllRules();
-
-session.dispose();
-
 </programlisting>
       </example>
 
-      <para>Once we have a RuleBase we can use it to obtain a stateful
+      <para>Once we have a KnowledgeBase we can use it to obtain a stateful
       session. Into our session we insert our facts (standard Java Objects).
       For simplicity in this sample, these classes are all contained within
       our NumberGuessExample.java file. The GameRules class provides the
@@ -376,4 +382,4 @@
           </listitem>
         </orderedlist>
 
-    </section>
\ No newline at end of file
+    </section>

Modified: labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-PetStoreExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-PetStoreExample.xml	2008-12-08 18:34:44 UTC (rev 24307)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-PetStoreExample.xml	2008-12-08 21:21:26 UTC (rev 24308)
@@ -56,22 +56,28 @@
 			<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>KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
+
+            kbuilder.add( ResourceFactory.newClassPathResource( "PetStore.drl",
+                                                                        PetStore.class ),
+                                  ResourceType.DRL );
+            KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
+            kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
+
+            //RuleB
+            Vector<Product> stock = new Vector<Product>();
+            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( kbase ) );
+            ui.createAndShowGUI();
 </programlisting>
 			</example>
 
@@ -82,30 +88,39 @@
 			<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> public String checkout(JFrame frame, List<Product> items) {
+            Order order = new Order();
+
+            //Iterate through list and add to cart
+            for ( int i = 0; i < items.size(); i++ ) {
+                order.addItem( new Purchase( order,
+                                             (Product) items.get( i ) ) );
+            }
+
+            //add the JFrame to the ApplicationData to allow for user interaction
+
+            StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
+            ksession.setGlobal( "frame",
+                                frame );
+            ksession.setGlobal( "textArea",
+                                this.output );
+
+            ksession.insert( new Product( "Gold Fish",
+                                          5 ) );
+            ksession.insert( new Product( "Fish Tank",
+                                          25 ) );
+            ksession.insert( new Product( "Fish Food",
+                                          2 ) );
+
+            ksession.insert( new Product( "Fish Food Sample",
+                                          0 ) );
+
+            ksession.insert( order );
+            ksession.fireAllRules();
+
+            //returns the state of the cart
+            return order.toString();
+        }
 </programlisting>
 			</example>
 
@@ -115,7 +130,7 @@
 
 			<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>Within this code, there are nine calls to the working memory. The first of these creates a new workingMemory (StatefulKnowledgeSession) from the Knowledgebase - remember that we passed in this Knowledgebase 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>
 			
@@ -136,11 +151,10 @@
 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 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. 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>
 			
@@ -215,18 +229,19 @@
 				<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" );
+// 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.getKnowledgeRuntime().getAgenda().getAgendaGroup( "show items" ).setFocus();		
+		drools.getKnowledgeRuntime().getAgenda().getAgendaGroup( "evaluate" ).setFocus();		
 end
 
 </programlisting>
@@ -514,4 +529,4 @@
      
 
 			<!---<para>Todo : Add Audit and Agenda Views for this sample.</para>-->
-		</section>
\ No newline at end of file
+		</section>

Modified: labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-PricingExample.xml
===================================================================
--- labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-PricingExample.xml	2008-12-08 18:34:44 UTC (rev 24307)
+++ labs/jbossrules/trunk/drools-docs/drools-docs-expert/src/main/docbook/en-US/Chapter-Examples/Section-PricingExample.xml	2008-12-08 21:21:26 UTC (rev 24308)
@@ -26,13 +26,19 @@
 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>
+			<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 added:</para>
 
-			<programlisting>SpreadsheetCompiler compiler = new SpreadsheetCompiler();
-String drl = compiler.compile(getSpreadsheetStream(), InputType.XLS);
+			<programlisting>DecisionTableConfiguration dtableconfiguration = KnowledgeBuilderFactory.newDecisionTableConfiguration();
+        dtableconfiguration.setInputType( DecisionTableInputType.XLS );
+
+        KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
+
+        kbuilder.add( ResourceFactory.newClassPathResource( "ExamplePolicyPricing.xls", getClass() ),
+                              ResourceType.DTABLE,
+                              dtableconfiguration );
 </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>Note the use of the DecisionTableConfiguration class. It is what takes the DecisionTableInputType.XLS as input type. 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>
@@ -84,4 +90,4 @@
 
 			<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
+	</section>	




More information about the jboss-svn-commits mailing list