[jboss-svn-commits] JBL Code SVN: r20789 - in labs/jbossrules/trunk/drools-clips/src: test/java/org/drools/clips and 1 other directory.

jboss-svn-commits at lists.jboss.org jboss-svn-commits at lists.jboss.org
Thu Jun 26 04:16:02 EDT 2008


Author: michael.neale at jboss.com
Date: 2008-06-26 04:16:02 -0400 (Thu, 26 Jun 2008)
New Revision: 20789

Modified:
   labs/jbossrules/trunk/drools-clips/src/main/java/org/drools/clips/Shell.java
   labs/jbossrules/trunk/drools-clips/src/test/java/org/drools/clips/ShellTest.java
Log:
small tweaks

Modified: labs/jbossrules/trunk/drools-clips/src/main/java/org/drools/clips/Shell.java
===================================================================
--- labs/jbossrules/trunk/drools-clips/src/main/java/org/drools/clips/Shell.java	2008-06-26 08:08:47 UTC (rev 20788)
+++ labs/jbossrules/trunk/drools-clips/src/main/java/org/drools/clips/Shell.java	2008-06-26 08:16:02 UTC (rev 20789)
@@ -4,24 +4,23 @@
 package org.drools.clips;
 
 import java.io.ByteArrayOutputStream;
-import java.io.InputStreamReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
 import java.io.PrintStream;
 import java.io.Reader;
 import java.io.Serializable;
 import java.io.StringReader;
-import java.io.ObjectInput;
-import java.io.IOException;
-import java.io.ObjectOutput;
-import java.nio.CharBuffer;
 import java.util.HashMap;
-import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
-import java.util.Stack;
 import java.util.Map.Entry;
-import java.util.logging.ConsoleHandler;
 
 import org.antlr.runtime.ANTLRReaderStream;
 import org.antlr.runtime.CommonTokenStream;
@@ -53,29 +52,29 @@
 import org.drools.clips.functions.SwitchFunction;
 import org.drools.common.InternalRuleBase;
 import org.drools.compiler.PackageBuilder;
-import org.drools.compiler.PackageBuilderConfiguration;
 import org.drools.lang.descr.AttributeDescr;
 import org.drools.lang.descr.FunctionDescr;
 import org.drools.lang.descr.ImportDescr;
 import org.drools.lang.descr.PackageDescr;
-import org.drools.lang.descr.PatternDescr;
 import org.drools.lang.descr.RuleDescr;
 import org.drools.lang.descr.TypeDeclarationDescr;
-import org.drools.lang.descr.TypeFieldDescr;
 import org.drools.rule.ImportDeclaration;
 import org.drools.rule.MVELDialectRuntimeData;
 import org.drools.rule.Namespaceable;
 import org.drools.rule.Package;
-import org.drools.rule.builder.dialect.mvel.MVELDialectConfiguration;
+import org.drools.rule.TypeDeclaration;
 import org.drools.spi.GlobalResolver;
 import org.mvel.MVEL;
 import org.mvel.ParserContext;
 import org.mvel.ast.Function;
-import org.mvel.compiler.CompiledExpression;
 import org.mvel.compiler.ExpressionCompiler;
-import org.mvel.debug.DebugTools;
-import org.mvel.util.CompilerTools;
 
+/**
+ * An interactive Clips session shell.
+ * You can launch this as a Main class, no parameters are required.
+ * @author Michael Neale
+ *
+ */
 public class Shell
     implements
     ParserHandler,
@@ -110,7 +109,7 @@
         StringBuffer buf = new StringBuffer();
         FunctionHandlers handlers = FunctionHandlers.getInstance();
         handlers.registerFunction( new PlusFunction() );
-        handlers.registerFunction( new MinusFunction() );            
+        handlers.registerFunction( new MinusFunction() );
         handlers.registerFunction( new MultiplyFunction() );
         handlers.registerFunction( new ModifyFunction() );
         handlers.registerFunction( new CreateListFunction() );
@@ -132,38 +131,110 @@
         handlers.registerFunction( new AssertFunction() );
         Shell shell = new Shell();
         ByteArrayOutputStream out = new ByteArrayOutputStream();
-        shell.addRouter( "t",
-                new PrintStream( out ) );
+        shell.addRouter( "t", new PrintStream( out ) );
+
         System.out.print("Drools>");
+
+        StringBuffer sessionLog = new StringBuffer();
         while(true) {
             byte name[] = new byte[256];
 
-	        Thread.sleep(1);
 	        System.in.read(name);
 	        String cmd = (new String(name)).trim();
+
 	        //System.out.println("ECHO:" + cmd);
-	        if (cmd.equals("(exit)") || cmd.equals("(quit)")) break;
+
+	        if (cmd.equals("(exit)") || cmd.equals("(quit)")) {
+	        	sessionLog.append(cmd);
+	        	break;
+	        }
 	        buf.append(cmd);
 
 	        if (isBalancedBrackets(buf)) {
-	        	shell.eval(buf.toString());
-	        	String output = new String(out.toByteArray());
-	        	if (output != null && output.trim().length() > 0) {
-	        		System.out.println(output);
+	        	String exp = buf.toString();
+	        	if (exp.startsWith("(save ")) {
+	        		String file = getFileName(exp);
+	        		System.out.println("Saving transcript to [" + file + "]");
+	        		writeFile(file, sessionLog);
+	        		sessionLog = new StringBuffer();
+	        		System.out.print("Drools>");
 	        	} else {
-	        		//System.out.println("OK");
+	        		sessionLog.append(cmd + "\n");
+
+	        		if (exp.startsWith("(load ")) {
+	        			String file = getFileName(exp);
+	        			System.out.println("Loading transcript from [" + file + "]");
+	        			exp = loadFile(file);
+	        		}
+
+		        	shell.eval(exp);
+		        	String output = new String(out.toByteArray());
+		        	if (output != null && output.trim().length() > 0) {
+		        		System.out.println(output);
+		        	}
+		        	out.reset();
+		        	System.out.print("Drools>");
+		        	buf = new StringBuffer();
 	        	}
-	        	out.reset();
-	        	System.out.print("Drools>");
-	        	buf = new StringBuffer();
 	        }
         }
 
-        System.out.println("Goobye !");
+        System.out.println("Goodbye, and good luck !");
 
     }
 
-    private static boolean isBalancedBrackets(StringBuffer buf) {
+	private static String loadFile(String fileName) throws IOException {
+		File f = new File(fileName);
+        InputStream is = new FileInputStream(f);
+
+        long length = f.length();
+        byte[] bytes = new byte[(int)length];
+
+        int offset = 0;
+        int numRead = 0;
+        while (offset < bytes.length
+               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
+            offset += numRead;
+        }
+
+        if (offset < bytes.length) {
+            throw new IOException("Could not completely read file "+f.getName());
+        }
+
+        is.close();
+		return new String(bytes);
+	}
+
+	private static String getFileName(String exp) {
+		char qt = '\'';
+		if (exp.contains("\"")) {
+			qt = '"';
+		}
+		String file = exp.substring(exp.indexOf(qt) + 1, exp.lastIndexOf(qt));
+		return file;
+	}
+
+    private static void writeFile(String file, StringBuffer sessionLog) {
+    	FileOutputStream fout;
+		try {
+			File f = new File(file);
+			if (!f.exists()) {
+				f.createNewFile();
+			}
+			fout = new FileOutputStream(f);
+			fout.write(sessionLog.toString().getBytes());
+			fout.flush();
+			fout.close();
+		} catch (FileNotFoundException e) {
+			System.err.println("File " + file + " does not exist.");
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+
+
+	}
+
+	private static boolean isBalancedBrackets(StringBuffer buf) {
 		char[] cs = buf.toString().toCharArray();
 		int stack = 0;
 		for (int i = 0; i < cs.length; i++) {
@@ -328,6 +399,7 @@
                                            (Class) cls );
                     }
                 }
+
             } catch ( Exception e ) {
                 e.printStackTrace();
             }

Modified: labs/jbossrules/trunk/drools-clips/src/test/java/org/drools/clips/ShellTest.java
===================================================================
--- labs/jbossrules/trunk/drools-clips/src/test/java/org/drools/clips/ShellTest.java	2008-06-26 08:08:47 UTC (rev 20788)
+++ labs/jbossrules/trunk/drools-clips/src/test/java/org/drools/clips/ShellTest.java	2008-06-26 08:16:02 UTC (rev 20789)
@@ -45,7 +45,7 @@
     public void setUp() {
         FunctionHandlers handlers = FunctionHandlers.getInstance();
         handlers.registerFunction( new PlusFunction() );
-        handlers.registerFunction( new MinusFunction() );        
+        handlers.registerFunction( new MinusFunction() );
         handlers.registerFunction( new MultiplyFunction() );
         handlers.registerFunction( new ModifyFunction() );
         handlers.registerFunction( new CreateListFunction() );
@@ -56,7 +56,7 @@
         handlers.registerFunction( new MoreThanFunction() );
         handlers.registerFunction( new EqFunction() );
         handlers.registerFunction( new SwitchFunction() );
-        //handlers.registerFunction( new DeffunctionFunction() );    
+        //handlers.registerFunction( new DeffunctionFunction() );
         handlers.registerFunction( new ReturnFunction() );
         handlers.registerFunction( new RunFunction() );
         handlers.registerFunction( new BindFunction() );
@@ -75,15 +75,15 @@
 
     //    public void test1() {
     //        String expr = "(* (+ 4 4 ) 2) (create$ 10 20 (+ 10 10) a) (modify ?p (name mark) (location \"london\")(age (+ 16 16) ) ) (printout t a b c (+ 4 4) )";
-    //        
+    //
     //        SExpression[] lisplists = evalString( expr );
     //
-    //        StringBuilderAppendable appendable = new StringBuilderAppendable();        
-    //        MVELClipsContext context = new MVELClipsContext();         
+    //        StringBuilderAppendable appendable = new StringBuilderAppendable();
+    //        MVELClipsContext context = new MVELClipsContext();
     //        for ( SExpression sExpression : lisplists ) {
     //            FunctionHandlers.dump( sExpression, appendable, context );
     //        }
-    //        
+    //
     //        System.out.println( appendable );
     //    }
 
@@ -210,7 +210,7 @@
         assertEquals( "[Person name='bob' likes='stilton' age='35']",
                       new String( this.baos.toByteArray() ) );
     }
-    
+
     public void testRuleCreation() {
         this.shell.eval( "(import org.drools.Person)" );
 
@@ -241,9 +241,18 @@
                                35 ) );
         wm.fireAllRules();
         assertEquals( "yy truexx true",
-                      new String( this.baos.toByteArray() ) );        
-    }    
-    
+                      new String( this.baos.toByteArray() ) );
+    }
+
+    public void FIXME_testTemplateCreation2() throws Exception {
+    	this.shell.eval( "(deftemplate PersonTemplate (slot name (type String) ) (slot age (type int) ) )" );
+        this.shell.eval( "(defrule xxx (PersonTemplate (name ?name&bob) (age 30) ) (PersonTemplate  (name ?name) (age 35)) => (printout t xx \" \" (eq 1 1) ) )" );
+        this.shell.eval( "(assert (PersonTemplate (name 'mike') (age 34)))");
+
+        Class personClass = this.shell.getStatefulSession().getRuleBase().getPackage( "MAIN" ).getPackageScopeClassLoader().loadClass( "MAIN.PersonTemplate" );
+        assertNotNull(personClass);
+    }
+
     public void testTemplateCreation() throws Exception {
         this.shell.eval( "(deftemplate Person (slot name (type String) ) (slot age (type int) ) )" );
 
@@ -265,26 +274,26 @@
 
         WorkingMemory wm = shell.getStatefulSession();
         Class personClass = this.shell.getStatefulSession().getRuleBase().getPackage( "MAIN" ).getPackageScopeClassLoader().loadClass( "MAIN.Person" );
-        
+
         Method nameMethod = personClass.getMethod( "setName", new Class[] { String.class } );
         Method ageMethod = personClass.getMethod( "setAge", new Class[] { int.class } );
-        
+
         Object bob1 = personClass.newInstance();
         nameMethod.invoke( bob1, "bob" );
         ageMethod.invoke( bob1, 30 );
 
-        
+
         Object bob2 = personClass.newInstance();
         nameMethod.invoke( bob2, "bob" );
         ageMethod.invoke( bob2, 35 );
-        //Constructor constructor = personClass.getConstructor( new Class[] { String.class,String.class, int.class} );        
+        //Constructor constructor = personClass.getConstructor( new Class[] { String.class,String.class, int.class} );
         wm.insert( bob1 );
         wm.insert( bob2 );
-        
-        
+
+
         wm.fireAllRules();
         assertEquals( "yy truexx true",
-                      new String( this.baos.toByteArray() ) );      	
+                      new String( this.baos.toByteArray() ) );
     }
 
     public void testEmptyLHSRule() {
@@ -306,15 +315,15 @@
     public void testRuleCallDeftemplate() {
         String function = "(deffunction max (?a ?b) (if (> ?a ?b) then (return ?a) else (return ?b) ) )";
         this.shell.eval( function );
-        
+
         this.shell.eval( "(import org.drools.*)" );
         this.shell.eval( "(defrule testRule (Person (age ?age) ) => (printout t hello) (printout t \" \" (max 3 ?age) ) )" );
         this.shell.eval( "(assert (Person (name mark) (age 32) ) )" );
         this.shell.eval( "(run)" );
         assertEquals( "hello 32",
-                      new String( this.baos.toByteArray() ) );        
+                      new String( this.baos.toByteArray() ) );
     }
-    
+
     public void testTwoSimpleRulesWithModify() {
         this.shell.eval( "(import org.drools.*)" );
         this.shell.eval( "(defrule testRule1 ?p <- (Person (name ?name&mark) ) => (printout t hello) (printout t \" \" ?name) (modify ?p (name bob) ) )" );
@@ -335,7 +344,7 @@
         assertEquals( "hello markhello bob",
                       new String( this.baos.toByteArray() ) );
     }
-    
+
     public void testPredicate() {
         this.shell.eval( "(import org.drools.Person)" );
         this.shell.eval( "(defrule testRule1 (Person (name ?name) (age ?age&:(> ?age 30)) ) => (printout t hello) (printout t \" \" ?name) )" );
@@ -343,9 +352,9 @@
         this.shell.eval( "(assert (Person (name bob) (age 35) ) )" );
         this.shell.eval( "(run)" );
         assertEquals( "hello bob",
-                      new String( this.baos.toByteArray() ) );        
+                      new String( this.baos.toByteArray() ) );
     }
-    
+
     public void testReturnValue() {
         this.shell.eval( "(import org.drools.Person)" );
         this.shell.eval( "(defrule testRule1 (Person (age ?age) ) (Person (name ?name) (age =(- ?age 3)) ) => (printout t hello) (printout t \" \" ?name) )" );
@@ -353,9 +362,9 @@
         this.shell.eval( "(assert (Person (name bob) (age 35) ) )" );
         this.shell.eval( "(run)" );
         assertEquals( "hello mark",
-                      new String( this.baos.toByteArray() ) );           
+                      new String( this.baos.toByteArray() ) );
     }
-    
+
     public void testTest() {
         this.shell.eval( "(import org.drools.Person)" );
         this.shell.eval( "(defrule testRule1 (Person (age ?age1) ) (Person (name ?name) (age ?age2) ) (test(eq ?age1 (+ ?age2 3) )) => (printout t hello) )" );
@@ -363,7 +372,7 @@
         this.shell.eval( "(assert (Person (name bob) (age 35) ) )" );
         this.shell.eval( "(run)" );
         assertEquals( "hello",
-                      new String( this.baos.toByteArray() ) );           
+                      new String( this.baos.toByteArray() ) );
     }
 
     public void testRun() {




More information about the jboss-svn-commits mailing list