[jboss-svn-commits] JBL Code SVN: r20823 - 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 16:41:43 EDT 2008
Author: mark.proctor at jboss.com
Date: 2008-06-26 16:41:43 -0400 (Thu, 26 Jun 2008)
New Revision: 20823
Added:
labs/jbossrules/trunk/drools-clips/src/main/java/org/drools/clips/ClipsShell.java
labs/jbossrules/trunk/drools-clips/src/test/java/org/drools/clips/ClipsShellTest.java
Removed:
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:
JBRULES-720 Clips Parser
-renamed Shell to ClipsShell
Copied: labs/jbossrules/trunk/drools-clips/src/main/java/org/drools/clips/ClipsShell.java (from rev 20820, labs/jbossrules/trunk/drools-clips/src/main/java/org/drools/clips/Shell.java)
===================================================================
--- labs/jbossrules/trunk/drools-clips/src/main/java/org/drools/clips/ClipsShell.java (rev 0)
+++ labs/jbossrules/trunk/drools-clips/src/main/java/org/drools/clips/ClipsShell.java 2008-06-26 20:41:43 UTC (rev 20823)
@@ -0,0 +1,585 @@
+/**
+ *
+ */
+package org.drools.clips;
+
+import java.io.ByteArrayOutputStream;
+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.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.antlr.runtime.ANTLRReaderStream;
+import org.antlr.runtime.CommonTokenStream;
+import org.drools.FactHandle;
+import org.drools.RuleBase;
+import org.drools.RuleBaseFactory;
+import org.drools.StatefulSession;
+import org.drools.base.ClassTypeResolver;
+import org.drools.base.mvel.DroolsMVELFactory;
+import org.drools.clips.functions.AssertFunction;
+import org.drools.clips.functions.BindFunction;
+import org.drools.clips.functions.CallFunction;
+import org.drools.clips.functions.CreateListFunction;
+import org.drools.clips.functions.EqFunction;
+import org.drools.clips.functions.GetFunction;
+import org.drools.clips.functions.IfFunction;
+import org.drools.clips.functions.LessThanFunction;
+import org.drools.clips.functions.MinusFunction;
+import org.drools.clips.functions.ModifyFunction;
+import org.drools.clips.functions.MoreThanFunction;
+import org.drools.clips.functions.MultiplyFunction;
+import org.drools.clips.functions.NewFunction;
+import org.drools.clips.functions.PlusFunction;
+import org.drools.clips.functions.PrintoutFunction;
+import org.drools.clips.functions.PrognFunction;
+import org.drools.clips.functions.ReturnFunction;
+import org.drools.clips.functions.RunFunction;
+import org.drools.clips.functions.SetFunction;
+import org.drools.clips.functions.SwitchFunction;
+import org.drools.common.InternalRuleBase;
+import org.drools.compiler.PackageBuilder;
+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.RuleDescr;
+import org.drools.lang.descr.TypeDeclarationDescr;
+import org.drools.rule.ImportDeclaration;
+import org.drools.rule.MVELDialectRuntimeData;
+import org.drools.rule.Namespaceable;
+import org.drools.rule.Package;
+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.ExpressionCompiler;
+
+/**
+ * An interactive Clips session shell.
+ * You can launch this as a Main class, no parameters are required.
+ * @author Michael Neale
+ *
+ */
+public class ClipsShell
+ implements
+ ParserHandler,
+ VariableContext,
+ FunctionContext,
+ PrintRouterContext {
+ private Map<String, Object> vars;
+
+ private PackageBuilder packageBuilder;
+ private RuleBase ruleBase;
+ private StatefulSession session;
+
+ // private Map functions;
+
+ // private Map directImports;
+ // private Set dynamicImports;
+
+ private ClassTypeResolver typeResolver;
+
+ private String moduleName;
+ private static final String MAIN = "MAIN";
+
+ private DroolsMVELFactory factory;
+
+ public ClipsShell() {
+ this( RuleBaseFactory.newRuleBase() );
+ }
+
+ public static void main(String[] args) throws Exception {
+
+
+ StringBuffer buf = new StringBuffer();
+ FunctionHandlers handlers = FunctionHandlers.getInstance();
+ handlers.registerFunction( new PlusFunction() );
+ handlers.registerFunction( new MinusFunction() );
+ handlers.registerFunction( new MultiplyFunction() );
+ handlers.registerFunction( new ModifyFunction() );
+ handlers.registerFunction( new CreateListFunction() );
+ handlers.registerFunction( new PrintoutFunction() );
+ handlers.registerFunction( new PrognFunction() );
+ handlers.registerFunction( new IfFunction() );
+ handlers.registerFunction( new LessThanFunction() );
+ handlers.registerFunction( new MoreThanFunction() );
+ handlers.registerFunction( new EqFunction() );
+ handlers.registerFunction( new SwitchFunction() );
+ //handlers.registerFunction( new DeffunctionFunction() );
+ handlers.registerFunction( new ReturnFunction() );
+ handlers.registerFunction( new RunFunction() );
+ handlers.registerFunction( new BindFunction() );
+ handlers.registerFunction( new NewFunction() );
+ handlers.registerFunction( new SetFunction() );
+ handlers.registerFunction( new GetFunction() );
+ handlers.registerFunction( new CallFunction() );
+ handlers.registerFunction( new AssertFunction() );
+ ClipsShell shell = new ClipsShell();
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ shell.addRouter( "t", new PrintStream( out ) );
+
+ System.out.print("Drools>");
+
+ StringBuffer sessionLog = new StringBuffer();
+ while(true) {
+ byte name[] = new byte[256];
+
+ System.in.read(name);
+ String cmd = (new String(name)).trim();
+
+ //System.out.println("ECHO:" + cmd);
+
+ if (cmd.equals("(exit)") || cmd.equals("(quit)")) {
+ sessionLog.append(cmd);
+ break;
+ }
+ buf.append(cmd);
+
+ if (isBalancedBrackets(buf)) {
+ 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 {
+ 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();
+ }
+ }
+ }
+
+ System.out.println("Goodbye, and good luck !");
+
+ }
+
+ 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++) {
+ if (cs[i] == '(') stack++;
+ if (cs[i] == ')') stack--;
+ }
+ return stack == 0;
+ }
+
+ public ClipsShell(RuleBase ruleBase) {
+ this.moduleName = MAIN;
+ this.ruleBase = ruleBase;
+
+ this.packageBuilder = new PackageBuilder( this.ruleBase );
+
+ this.session = this.ruleBase.newStatefulSession();
+ // this.functions = new HashMap();
+ // this.directImports = new HashMap();
+ // this.dynamicImports = new HashSet();
+
+ // this.typeResolver = new ClassTypeResolver( new HashSet(),
+ // ((InternalRuleBase) this.ruleBase).getConfiguration().getClassLoader() );
+
+ this.factory = (DroolsMVELFactory) new DroolsMVELFactory( null,
+ null,
+ ((InternalRuleBase) this.ruleBase).getGlobals() );
+
+ this.vars = new HashMap<String, Object>();
+ GlobalResolver2 globalResolver = new GlobalResolver2( this.vars,
+ this.session.getGlobalResolver() );
+ this.session.setGlobalResolver( globalResolver );
+
+ this.factory.setContext( null,
+ null,
+ null,
+ this.session,
+ this.vars );
+
+ addRouter( "t",
+ System.out );
+ }
+
+ public StatefulSession getStatefulSession() {
+ return this.session;
+ }
+
+ public static class GlobalResolver2
+ implements
+ GlobalResolver {
+ private Map<String, Object> vars;
+ private GlobalResolver resolver;
+
+ public GlobalResolver2() {
+ }
+
+ public GlobalResolver2(Map<String, Object> vars,
+ GlobalResolver resolver) {
+ this.vars = vars;
+ this.resolver = resolver;
+ }
+
+ public void readExternal(ObjectInput in) throws IOException,
+ ClassNotFoundException {
+ vars = (Map<String, Object>) in.readObject();
+ resolver = (GlobalResolver) in.readObject();
+ }
+
+ public void writeExternal(ObjectOutput out) throws IOException {
+ out.writeObject( vars );
+ out.writeObject( resolver );
+ }
+
+ public Object resolveGlobal(String identifier) {
+ Object object = this.vars.get( identifier );
+ if ( object == null ) {
+ object = resolver.resolveGlobal( identifier );
+ }
+ return object;
+ }
+
+ public void setGlobal(String identifier,
+ Object value) {
+ this.resolver.setGlobal( identifier,
+ value );
+
+ }
+ }
+
+ public void importHandler(ImportDescr descr) {
+ // use the current focus as the default namespace for these imports
+ PackageDescr pkgDescr = createPackageDescr( this.session.getAgenda().getFocus().getName() );
+ pkgDescr.addImport( descr );
+ this.packageBuilder.addPackage( pkgDescr );
+ }
+
+ public void functionHandler(FunctionDescr functionDescr) {
+ // for now all functions are in MAIN
+ //setModuleName( functionDescr );
+ functionDescr.setNamespace( "MAIN" );
+ Appendable builder = new StringBuilderAppendable();
+
+ // strip lead/trailing quotes
+ String name = functionDescr.getName().trim();
+ if ( name.charAt( 0 ) == '"' ) {
+ name = name.substring( 1 );
+ }
+
+ if ( name.charAt( name.length() - 1 ) == '"' ) {
+ name = name.substring( 0,
+ name.length() - 1 );
+ }
+ builder.append( "function " + name + "(" );
+
+ for ( int i = 0, length = functionDescr.getParameterNames().size(); i < length; i++ ) {
+ builder.append( functionDescr.getParameterNames().get( i ) );
+ if ( i < length - 1 ) {
+ builder.append( ", " );
+ }
+ }
+
+ builder.append( ") {\n" );
+ List list = (List) functionDescr.getContent();
+ for ( Iterator it = list.iterator(); it.hasNext(); ) {
+ FunctionHandlers.dump( (LispForm) it.next(),
+ builder );
+ }
+ builder.append( "}" );
+
+ functionDescr.setContent( builder.toString() );
+ functionDescr.setDialect( "clips" );
+
+ PackageDescr pkgDescr = createPackageDescr( functionDescr.getNamespace() );
+ pkgDescr.addFunction( functionDescr );
+
+ this.packageBuilder.addPackage( pkgDescr );
+ }
+
+ public void lispFormHandler(LispForm lispForm) {
+ StringBuilderAppendable appendable = new StringBuilderAppendable();
+ FunctionHandlers.dump( lispForm,
+ appendable );
+
+ ParserContext context = new ParserContext();
+
+
+ String namespace = this.session.getAgenda().getFocus().getName();
+
+ Package pkg = this.ruleBase.getPackage( namespace );
+ if ( pkg == null ) {
+ this.packageBuilder.addPackage( createPackageDescr( namespace ) );
+ pkg = this.ruleBase.getPackage( namespace );
+
+ }
+
+ if ( pkg != null ) {
+ // only time this will be null is if we have yet to do any packagedescr work
+
+ try {
+ for ( Iterator it = pkg.getImports().entrySet().iterator(); it.hasNext(); ) {
+ Entry entry = (Entry) it.next();
+ String importName = ((ImportDeclaration) entry.getValue()).getTarget();
+ if ( importName.endsWith( "*" )) {
+ context.addPackageImport( importName.substring( 0,
+ importName.length() - 2 ) );
+ } else {
+ Class cls = pkg.getDialectRuntimeRegistry().getClassLoader().loadClass( importName );
+ context.addImport( cls.getSimpleName(),
+ (Class) cls );
+ }
+ }
+
+ } catch ( Exception e ) {
+ e.printStackTrace();
+ }
+
+ MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData( "clips" );
+ this.factory.setNextFactory( data.getFunctionFactory() );
+ }
+
+ ClassLoader tempClassLoader = Thread.currentThread().getContextClassLoader();
+ Thread.currentThread().setContextClassLoader( pkg.getPackageScopeClassLoader() );
+
+ ExpressionCompiler expr = new ExpressionCompiler( appendable.toString() );
+ Serializable executable = expr.compile( context );
+
+ MVEL.executeExpression( executable,
+ this,
+ this.factory );
+ Thread.currentThread().setContextClassLoader( tempClassLoader );
+ }
+
+ public void templateHandler(TypeDeclarationDescr typeDescr) {
+ setModuleName( typeDescr );
+
+ PackageDescr pkg = createPackageDescr( typeDescr.getNamespace() );
+ //pkg.addRule( ruleDescr );
+ pkg.addTypeDeclaration( typeDescr );
+
+ this.packageBuilder.addPackage( pkg );
+
+ // try {
+ // this.ruleBase.addPackage( builder.getPackage() );
+ // } catch ( Exception e ) {
+ // e.printStackTrace();
+ // }
+ }
+
+ public void ruleHandler(RuleDescr ruleDescr) {
+ setModuleName( ruleDescr );
+ PackageDescr pkg = createPackageDescr( ruleDescr.getNamespace() );
+ pkg.addRule( ruleDescr );
+
+ this.packageBuilder.addPackage( pkg );
+
+ this.session.fireAllRules();
+
+ // try {
+ // this.ruleBase.addPackage( builder.getPackage() );
+ // } catch ( Exception e ) {
+ // e.printStackTrace();
+ // }
+ }
+
+ public void setModuleName(Namespaceable namespaceable) {
+ // if the namespace is not set, set it to the current focus module
+ if ( isEmpty( namespaceable.getNamespace() ) ) {
+ namespaceable.setNamespace( this.session.getAgenda().getFocus().getName() );
+ }
+ }
+
+ public boolean isEmpty(String string) {
+ return (string == null || string.trim().length() == 0);
+ }
+
+ public void eval(String string) {
+ eval( new StringReader( string ) );
+ }
+
+ public void eval(Reader reader) {
+ ClipsParser parser;
+ try {
+ parser = new ClipsParser( new CommonTokenStream( new ClipsLexer( new ANTLRReaderStream( reader ) ) ) );
+ parser.eval( this );
+ } catch ( Exception e ) {
+ e.printStackTrace();
+ }
+ }
+
+ public void run() {
+ this.session.fireAllRules();
+ }
+
+ public void run(int fireLimit) {
+ this.session.fireAllRules( fireLimit );
+ }
+
+ public FactHandle insert(Object object) {
+ return this.session.insert( object );
+ }
+
+ public void importEntry(String importEntry) {
+
+ }
+
+ public void addFunction(Function function) {
+ this.factory.createVariable( function.getAbsoluteName(),
+ function );
+ }
+
+ public boolean removeFunction(String functionName) {
+ return false; //(this.vars.remove( functionName ) != null);
+ }
+
+ public Map<String, Function> getFunctions() {
+ Map<String, Function> map = new HashMap<String, Function>();
+ // for ( Iterator it = this.vars.entrySet().iterator(); it.hasNext(); ) {
+ // Entry entry = (Entry) it.next();
+ // if ( entry.getValue() instanceof Function ) {
+ // map.put( (String) entry.getKey(),
+ // (Function) entry.getValue() );
+ // }
+ // }
+ return map;
+ }
+
+ public void addRouter(String name,
+ PrintStream out) {
+
+ Map routers = (Map) this.vars.get( "printrouters" );
+ if ( routers == null ) {
+ routers = new HashMap();
+ this.factory.createVariable( "printrouters",
+ routers );
+ }
+
+ routers.put( name,
+ out );
+
+ }
+
+ public boolean removeRouter(String name) {
+ return false; //(this.vars.remove( name ) != null);
+ }
+
+ // public Map<String, PrintStream> getRouters() {
+ // Map<String, PrintStream> map = new HashMap<String, PrintStream>();
+ // for ( Iterator it = this.vars.entrySet().iterator(); it.hasNext(); ) {
+ // Entry entry = (Entry) it.next();
+ // if ( entry.getValue() instanceof Function ) {
+ // map.put( (String) entry.getKey(),
+ // (PrintStream) entry.getValue() );
+ // }
+ // }
+ // return map;
+ // }
+
+ public void addVariable(String name,
+ Object value) {
+ if ( name.startsWith( "?" ) ) {
+ name = name.substring( 1 );
+ }
+ this.factory.createVariable( name,
+ value );
+ // this.session.setGlobal( name,
+ // value );
+ }
+
+ // public void removeVariable(String name) {
+ // String temp = this.varNameMap.get( name );
+ // if ( temp != null ) {
+ // name = temp;
+ // }
+ // this.session.getGlobal( identifier ).remove( name );
+ // }
+
+ private PackageDescr createPackageDescr(String moduleName) {
+ PackageDescr pkg = new PackageDescr( moduleName );
+ pkg.addAttribute( new AttributeDescr( "dialect",
+ "clips" ) );
+
+ // for ( Iterator it = this.typeResolver.getImports().iterator(); it.hasNext(); ) {
+ // pkg.addImport( new ImportDescr( (String) it.next() ) );
+ // }
+
+ return pkg;
+ }
+
+}
\ No newline at end of file
Deleted: 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 20:09:07 UTC (rev 20822)
+++ labs/jbossrules/trunk/drools-clips/src/main/java/org/drools/clips/Shell.java 2008-06-26 20:41:43 UTC (rev 20823)
@@ -1,585 +0,0 @@
-/**
- *
- */
-package org.drools.clips;
-
-import java.io.ByteArrayOutputStream;
-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.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.antlr.runtime.ANTLRReaderStream;
-import org.antlr.runtime.CommonTokenStream;
-import org.drools.FactHandle;
-import org.drools.RuleBase;
-import org.drools.RuleBaseFactory;
-import org.drools.StatefulSession;
-import org.drools.base.ClassTypeResolver;
-import org.drools.base.mvel.DroolsMVELFactory;
-import org.drools.clips.functions.AssertFunction;
-import org.drools.clips.functions.BindFunction;
-import org.drools.clips.functions.CallFunction;
-import org.drools.clips.functions.CreateListFunction;
-import org.drools.clips.functions.EqFunction;
-import org.drools.clips.functions.GetFunction;
-import org.drools.clips.functions.IfFunction;
-import org.drools.clips.functions.LessThanFunction;
-import org.drools.clips.functions.MinusFunction;
-import org.drools.clips.functions.ModifyFunction;
-import org.drools.clips.functions.MoreThanFunction;
-import org.drools.clips.functions.MultiplyFunction;
-import org.drools.clips.functions.NewFunction;
-import org.drools.clips.functions.PlusFunction;
-import org.drools.clips.functions.PrintoutFunction;
-import org.drools.clips.functions.PrognFunction;
-import org.drools.clips.functions.ReturnFunction;
-import org.drools.clips.functions.RunFunction;
-import org.drools.clips.functions.SetFunction;
-import org.drools.clips.functions.SwitchFunction;
-import org.drools.common.InternalRuleBase;
-import org.drools.compiler.PackageBuilder;
-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.RuleDescr;
-import org.drools.lang.descr.TypeDeclarationDescr;
-import org.drools.rule.ImportDeclaration;
-import org.drools.rule.MVELDialectRuntimeData;
-import org.drools.rule.Namespaceable;
-import org.drools.rule.Package;
-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.ExpressionCompiler;
-
-/**
- * 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,
- VariableContext,
- FunctionContext,
- PrintRouterContext {
- private Map<String, Object> vars;
-
- private PackageBuilder packageBuilder;
- private RuleBase ruleBase;
- private StatefulSession session;
-
- // private Map functions;
-
- // private Map directImports;
- // private Set dynamicImports;
-
- private ClassTypeResolver typeResolver;
-
- private String moduleName;
- private static final String MAIN = "MAIN";
-
- private DroolsMVELFactory factory;
-
- public Shell() {
- this( RuleBaseFactory.newRuleBase() );
- }
-
- public static void main(String[] args) throws Exception {
-
-
- StringBuffer buf = new StringBuffer();
- FunctionHandlers handlers = FunctionHandlers.getInstance();
- handlers.registerFunction( new PlusFunction() );
- handlers.registerFunction( new MinusFunction() );
- handlers.registerFunction( new MultiplyFunction() );
- handlers.registerFunction( new ModifyFunction() );
- handlers.registerFunction( new CreateListFunction() );
- handlers.registerFunction( new PrintoutFunction() );
- handlers.registerFunction( new PrognFunction() );
- handlers.registerFunction( new IfFunction() );
- handlers.registerFunction( new LessThanFunction() );
- handlers.registerFunction( new MoreThanFunction() );
- handlers.registerFunction( new EqFunction() );
- handlers.registerFunction( new SwitchFunction() );
- //handlers.registerFunction( new DeffunctionFunction() );
- handlers.registerFunction( new ReturnFunction() );
- handlers.registerFunction( new RunFunction() );
- handlers.registerFunction( new BindFunction() );
- handlers.registerFunction( new NewFunction() );
- handlers.registerFunction( new SetFunction() );
- handlers.registerFunction( new GetFunction() );
- handlers.registerFunction( new CallFunction() );
- handlers.registerFunction( new AssertFunction() );
- Shell shell = new Shell();
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- shell.addRouter( "t", new PrintStream( out ) );
-
- System.out.print("Drools>");
-
- StringBuffer sessionLog = new StringBuffer();
- while(true) {
- byte name[] = new byte[256];
-
- System.in.read(name);
- String cmd = (new String(name)).trim();
-
- //System.out.println("ECHO:" + cmd);
-
- if (cmd.equals("(exit)") || cmd.equals("(quit)")) {
- sessionLog.append(cmd);
- break;
- }
- buf.append(cmd);
-
- if (isBalancedBrackets(buf)) {
- 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 {
- 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();
- }
- }
- }
-
- System.out.println("Goodbye, and good luck !");
-
- }
-
- 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++) {
- if (cs[i] == '(') stack++;
- if (cs[i] == ')') stack--;
- }
- return stack == 0;
- }
-
- public Shell(RuleBase ruleBase) {
- this.moduleName = MAIN;
- this.ruleBase = ruleBase;
-
- this.packageBuilder = new PackageBuilder( this.ruleBase );
-
- this.session = this.ruleBase.newStatefulSession();
- // this.functions = new HashMap();
- // this.directImports = new HashMap();
- // this.dynamicImports = new HashSet();
-
- // this.typeResolver = new ClassTypeResolver( new HashSet(),
- // ((InternalRuleBase) this.ruleBase).getConfiguration().getClassLoader() );
-
- this.factory = (DroolsMVELFactory) new DroolsMVELFactory( null,
- null,
- ((InternalRuleBase) this.ruleBase).getGlobals() );
-
- this.vars = new HashMap<String, Object>();
- GlobalResolver2 globalResolver = new GlobalResolver2( this.vars,
- this.session.getGlobalResolver() );
- this.session.setGlobalResolver( globalResolver );
-
- this.factory.setContext( null,
- null,
- null,
- this.session,
- this.vars );
-
- addRouter( "t",
- System.out );
- }
-
- public StatefulSession getStatefulSession() {
- return this.session;
- }
-
- public static class GlobalResolver2
- implements
- GlobalResolver {
- private Map<String, Object> vars;
- private GlobalResolver resolver;
-
- public GlobalResolver2() {
- }
-
- public GlobalResolver2(Map<String, Object> vars,
- GlobalResolver resolver) {
- this.vars = vars;
- this.resolver = resolver;
- }
-
- public void readExternal(ObjectInput in) throws IOException,
- ClassNotFoundException {
- vars = (Map<String, Object>) in.readObject();
- resolver = (GlobalResolver) in.readObject();
- }
-
- public void writeExternal(ObjectOutput out) throws IOException {
- out.writeObject( vars );
- out.writeObject( resolver );
- }
-
- public Object resolveGlobal(String identifier) {
- Object object = this.vars.get( identifier );
- if ( object == null ) {
- object = resolver.resolveGlobal( identifier );
- }
- return object;
- }
-
- public void setGlobal(String identifier,
- Object value) {
- this.resolver.setGlobal( identifier,
- value );
-
- }
- }
-
- public void importHandler(ImportDescr descr) {
- // use the current focus as the default namespace for these imports
- PackageDescr pkgDescr = createPackageDescr( this.session.getAgenda().getFocus().getName() );
- pkgDescr.addImport( descr );
- this.packageBuilder.addPackage( pkgDescr );
- }
-
- public void functionHandler(FunctionDescr functionDescr) {
- // for now all functions are in MAIN
- //setModuleName( functionDescr );
- functionDescr.setNamespace( "MAIN" );
- Appendable builder = new StringBuilderAppendable();
-
- // strip lead/trailing quotes
- String name = functionDescr.getName().trim();
- if ( name.charAt( 0 ) == '"' ) {
- name = name.substring( 1 );
- }
-
- if ( name.charAt( name.length() - 1 ) == '"' ) {
- name = name.substring( 0,
- name.length() - 1 );
- }
- builder.append( "function " + name + "(" );
-
- for ( int i = 0, length = functionDescr.getParameterNames().size(); i < length; i++ ) {
- builder.append( functionDescr.getParameterNames().get( i ) );
- if ( i < length - 1 ) {
- builder.append( ", " );
- }
- }
-
- builder.append( ") {\n" );
- List list = (List) functionDescr.getContent();
- for ( Iterator it = list.iterator(); it.hasNext(); ) {
- FunctionHandlers.dump( (LispForm) it.next(),
- builder );
- }
- builder.append( "}" );
-
- functionDescr.setContent( builder.toString() );
- functionDescr.setDialect( "clips" );
-
- PackageDescr pkgDescr = createPackageDescr( functionDescr.getNamespace() );
- pkgDescr.addFunction( functionDescr );
-
- this.packageBuilder.addPackage( pkgDescr );
- }
-
- public void lispFormHandler(LispForm lispForm) {
- StringBuilderAppendable appendable = new StringBuilderAppendable();
- FunctionHandlers.dump( lispForm,
- appendable );
-
- ParserContext context = new ParserContext();
-
-
- String namespace = this.session.getAgenda().getFocus().getName();
-
- Package pkg = this.ruleBase.getPackage( namespace );
- if ( pkg == null ) {
- this.packageBuilder.addPackage( createPackageDescr( namespace ) );
- pkg = this.ruleBase.getPackage( namespace );
-
- }
-
- if ( pkg != null ) {
- // only time this will be null is if we have yet to do any packagedescr work
-
- try {
- for ( Iterator it = pkg.getImports().entrySet().iterator(); it.hasNext(); ) {
- Entry entry = (Entry) it.next();
- String importName = ((ImportDeclaration) entry.getValue()).getTarget();
- if ( importName.endsWith( "*" )) {
- context.addPackageImport( importName.substring( 0,
- importName.length() - 2 ) );
- } else {
- Class cls = pkg.getDialectRuntimeRegistry().getClassLoader().loadClass( importName );
- context.addImport( cls.getSimpleName(),
- (Class) cls );
- }
- }
-
- } catch ( Exception e ) {
- e.printStackTrace();
- }
-
- MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData( "clips" );
- this.factory.setNextFactory( data.getFunctionFactory() );
- }
-
- ClassLoader tempClassLoader = Thread.currentThread().getContextClassLoader();
- Thread.currentThread().setContextClassLoader( pkg.getPackageScopeClassLoader() );
-
- ExpressionCompiler expr = new ExpressionCompiler( appendable.toString() );
- Serializable executable = expr.compile( context );
-
- MVEL.executeExpression( executable,
- this,
- this.factory );
- Thread.currentThread().setContextClassLoader( tempClassLoader );
- }
-
- public void templateHandler(TypeDeclarationDescr typeDescr) {
- setModuleName( typeDescr );
-
- PackageDescr pkg = createPackageDescr( typeDescr.getNamespace() );
- //pkg.addRule( ruleDescr );
- pkg.addTypeDeclaration( typeDescr );
-
- this.packageBuilder.addPackage( pkg );
-
- // try {
- // this.ruleBase.addPackage( builder.getPackage() );
- // } catch ( Exception e ) {
- // e.printStackTrace();
- // }
- }
-
- public void ruleHandler(RuleDescr ruleDescr) {
- setModuleName( ruleDescr );
- PackageDescr pkg = createPackageDescr( ruleDescr.getNamespace() );
- pkg.addRule( ruleDescr );
-
- this.packageBuilder.addPackage( pkg );
-
- this.session.fireAllRules();
-
- // try {
- // this.ruleBase.addPackage( builder.getPackage() );
- // } catch ( Exception e ) {
- // e.printStackTrace();
- // }
- }
-
- public void setModuleName(Namespaceable namespaceable) {
- // if the namespace is not set, set it to the current focus module
- if ( isEmpty( namespaceable.getNamespace() ) ) {
- namespaceable.setNamespace( this.session.getAgenda().getFocus().getName() );
- }
- }
-
- public boolean isEmpty(String string) {
- return (string == null || string.trim().length() == 0);
- }
-
- public void eval(String string) {
- eval( new StringReader( string ) );
- }
-
- public void eval(Reader reader) {
- ClipsParser parser;
- try {
- parser = new ClipsParser( new CommonTokenStream( new ClipsLexer( new ANTLRReaderStream( reader ) ) ) );
- parser.eval( this );
- } catch ( Exception e ) {
- e.printStackTrace();
- }
- }
-
- public void run() {
- this.session.fireAllRules();
- }
-
- public void run(int fireLimit) {
- this.session.fireAllRules( fireLimit );
- }
-
- public FactHandle insert(Object object) {
- return this.session.insert( object );
- }
-
- public void importEntry(String importEntry) {
-
- }
-
- public void addFunction(Function function) {
- this.factory.createVariable( function.getAbsoluteName(),
- function );
- }
-
- public boolean removeFunction(String functionName) {
- return false; //(this.vars.remove( functionName ) != null);
- }
-
- public Map<String, Function> getFunctions() {
- Map<String, Function> map = new HashMap<String, Function>();
- // for ( Iterator it = this.vars.entrySet().iterator(); it.hasNext(); ) {
- // Entry entry = (Entry) it.next();
- // if ( entry.getValue() instanceof Function ) {
- // map.put( (String) entry.getKey(),
- // (Function) entry.getValue() );
- // }
- // }
- return map;
- }
-
- public void addRouter(String name,
- PrintStream out) {
-
- Map routers = (Map) this.vars.get( "printrouters" );
- if ( routers == null ) {
- routers = new HashMap();
- this.factory.createVariable( "printrouters",
- routers );
- }
-
- routers.put( name,
- out );
-
- }
-
- public boolean removeRouter(String name) {
- return false; //(this.vars.remove( name ) != null);
- }
-
- // public Map<String, PrintStream> getRouters() {
- // Map<String, PrintStream> map = new HashMap<String, PrintStream>();
- // for ( Iterator it = this.vars.entrySet().iterator(); it.hasNext(); ) {
- // Entry entry = (Entry) it.next();
- // if ( entry.getValue() instanceof Function ) {
- // map.put( (String) entry.getKey(),
- // (PrintStream) entry.getValue() );
- // }
- // }
- // return map;
- // }
-
- public void addVariable(String name,
- Object value) {
- if ( name.startsWith( "?" ) ) {
- name = name.substring( 1 );
- }
- this.factory.createVariable( name,
- value );
- // this.session.setGlobal( name,
- // value );
- }
-
- // public void removeVariable(String name) {
- // String temp = this.varNameMap.get( name );
- // if ( temp != null ) {
- // name = temp;
- // }
- // this.session.getGlobal( identifier ).remove( name );
- // }
-
- private PackageDescr createPackageDescr(String moduleName) {
- PackageDescr pkg = new PackageDescr( moduleName );
- pkg.addAttribute( new AttributeDescr( "dialect",
- "clips" ) );
-
- // for ( Iterator it = this.typeResolver.getImports().iterator(); it.hasNext(); ) {
- // pkg.addImport( new ImportDescr( (String) it.next() ) );
- // }
-
- return pkg;
- }
-
-}
\ No newline at end of file
Copied: labs/jbossrules/trunk/drools-clips/src/test/java/org/drools/clips/ClipsShellTest.java (from rev 20820, labs/jbossrules/trunk/drools-clips/src/test/java/org/drools/clips/ShellTest.java)
===================================================================
--- labs/jbossrules/trunk/drools-clips/src/test/java/org/drools/clips/ClipsShellTest.java (rev 0)
+++ labs/jbossrules/trunk/drools-clips/src/test/java/org/drools/clips/ClipsShellTest.java 2008-06-26 20:41:43 UTC (rev 20823)
@@ -0,0 +1,394 @@
+package org.drools.clips;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
+import junit.framework.TestCase;
+
+import org.drools.Person;
+import org.drools.WorkingMemory;
+import org.drools.clips.FunctionHandlers;
+import org.drools.clips.ClipsShell;
+import org.drools.clips.functions.AssertFunction;
+import org.drools.clips.functions.BindFunction;
+import org.drools.clips.functions.CallFunction;
+import org.drools.clips.functions.CreateListFunction;
+import org.drools.clips.functions.EqFunction;
+import org.drools.clips.functions.GetFunction;
+import org.drools.clips.functions.IfFunction;
+import org.drools.clips.functions.LessThanFunction;
+import org.drools.clips.functions.MinusFunction;
+import org.drools.clips.functions.ModifyFunction;
+import org.drools.clips.functions.MoreThanFunction;
+import org.drools.clips.functions.MultiplyFunction;
+import org.drools.clips.functions.NewFunction;
+import org.drools.clips.functions.PlusFunction;
+import org.drools.clips.functions.PrintoutFunction;
+import org.drools.clips.functions.PrognFunction;
+import org.drools.clips.functions.ReturnFunction;
+import org.drools.clips.functions.RunFunction;
+import org.drools.clips.functions.SetFunction;
+import org.drools.clips.functions.SwitchFunction;
+import org.drools.rule.Package;
+import org.drools.rule.Rule;
+
+public class ClipsShellTest extends TestCase {
+ private ByteArrayOutputStream baos;
+
+ ClipsShell shell;
+
+ public void setUp() {
+ FunctionHandlers handlers = FunctionHandlers.getInstance();
+ handlers.registerFunction( new PlusFunction() );
+ handlers.registerFunction( new MinusFunction() );
+ handlers.registerFunction( new MultiplyFunction() );
+ handlers.registerFunction( new ModifyFunction() );
+ handlers.registerFunction( new CreateListFunction() );
+ handlers.registerFunction( new PrintoutFunction() );
+ handlers.registerFunction( new PrognFunction() );
+ handlers.registerFunction( new IfFunction() );
+ handlers.registerFunction( new LessThanFunction() );
+ handlers.registerFunction( new MoreThanFunction() );
+ handlers.registerFunction( new EqFunction() );
+ handlers.registerFunction( new SwitchFunction() );
+ //handlers.registerFunction( new DeffunctionFunction() );
+ handlers.registerFunction( new ReturnFunction() );
+ handlers.registerFunction( new RunFunction() );
+ handlers.registerFunction( new BindFunction() );
+ handlers.registerFunction( new NewFunction() );
+ handlers.registerFunction( new SetFunction() );
+ handlers.registerFunction( new GetFunction() );
+ handlers.registerFunction( new CallFunction() );
+ handlers.registerFunction( new AssertFunction() );
+
+ this.shell = new ClipsShell();
+
+ this.baos = new ByteArrayOutputStream();
+ shell.addRouter( "t",
+ new PrintStream( baos ) );
+ }
+
+ // 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();
+ // for ( SExpression sExpression : lisplists ) {
+ // FunctionHandlers.dump( sExpression, appendable, context );
+ // }
+ //
+ // System.out.println( appendable );
+ // }
+
+ public void testBind() {
+ String expr = "(bind ?x (create$ 10 20 30) ) (printout t ?x)";
+
+ this.shell.eval( expr );
+
+ assertEquals( "[10, 20, 30]",
+ new String( baos.toByteArray() ) );
+ }
+
+ public void testProgn() {
+ String expr = "(progn (?x (create$ 10 20 30) ) (printout t ?x) )";
+
+ this.shell.eval( expr );
+
+ assertEquals( "102030",
+ new String( baos.toByteArray() ) );
+ }
+
+ public void testIf() {
+ String expr = "(if (< 1 3) then (printout t hello) (printout t hello) )";
+
+ this.shell.eval( expr );
+
+ assertEquals( "hellohello",
+ new String( baos.toByteArray() ) );
+ }
+
+ public void testIfElse() {
+ String expr = "(if (eq 1 3) then (printout t hello) (printout t 1) else (printout t hello) (printout t 2))";
+
+ this.shell.eval( expr );
+
+ assertEquals( "hello2",
+ new String( baos.toByteArray() ) );
+ }
+
+ public void testSwitch() throws IOException {
+ String expr = "(switch (?x) (case a then (printout t hello)(printout t 1)) (case b then (printout t hello)(printout t 2)) (default (printout t hello)(printout t 3)) )";
+
+ // check case a
+ this.shell.addVariable( "$x",
+ "a" );
+ this.shell.eval( expr );
+ assertEquals( "hello1",
+ new String( baos.toByteArray() ) );
+
+ // check default
+ this.shell.addVariable( "$x",
+ "M" );
+ this.shell.eval( expr );
+ assertEquals( "hello1hello3",
+ new String( baos.toByteArray() ) );
+
+ // check case b
+ this.shell.addVariable( "$x",
+ "b" );
+ this.shell.eval( expr );
+ assertEquals( "hello1hello3hello2",
+ new String( baos.toByteArray() ) );
+ }
+
+ // @FIXME - org.mvel.CompileException: unable to resolve property: unable to resolve method: org.drools.clips.Shell.max(java.lang.Integer, java.lang.Integer) [arglength=2]
+ public void testDeffunction() {
+ String function = "(deffunction max (?a ?b) (if (> ?a ?b) then (return ?a) else (return ?b) ) )";
+ this.shell.eval( function );
+
+ String expr = "(if (eq (max 3 5) 5) then (printout t hello) )";
+ this.shell.eval( expr );
+ assertEquals( "hello",
+ new String( baos.toByteArray() ) );
+
+ expr = "(if (eq (max ?a ?b) 5) then (printout t hello) )";
+ this.shell.addVariable( "$a",
+ "3" );
+ this.shell.addVariable( "$b",
+ "5" );
+ this.shell.eval( expr );
+ assertEquals( "hellohello",
+ new String( baos.toByteArray() ) );
+ }
+
+ public void testDirectImportAndNew() {
+ String t = "(import org.drools.Person) (bind ?p (new Person mark cheddar) ) (printout t ?p)";
+ this.shell.eval( t );
+ assertEquals( "[Person name='mark']",
+ new String( this.baos.toByteArray() ) );
+ }
+
+ public void testDynamicImportAndNew() {
+ String t = "(import org.drools.*) (bind ?p (new Person mark cheddar) ) (printout t ?p)";
+ this.shell.eval( t );
+ assertEquals( "[Person name='mark']",
+ new String( this.baos.toByteArray() ) );
+ }
+
+ public void testSet() {
+ String t = "(import org.drools.*) (bind ?p (new Person mark cheddar) ) (set ?p name bob) (printout t ?p)";
+ this.shell.eval( t );
+ assertEquals( "[Person name='bob']",
+ new String( this.baos.toByteArray() ) );
+ }
+
+ public void testGet() {
+ String t = "(import org.drools.*) (bind ?p (new Person mark cheddar) )(printout t (get ?p name))";
+ this.shell.eval( t );
+ assertEquals( "mark",
+ new String( this.baos.toByteArray() ) );
+ }
+
+
+ public void testExplicitCall() {
+ String t = "(import org.drools.*) (bind ?p (new Person mark cheddar) ) (call ?p setFields bob stilton 35) (printout t (call ?p toLongString))";
+ this.shell.eval( t );
+ assertEquals( "[Person name='bob' likes='stilton' age='35']",
+ new String( this.baos.toByteArray() ) );
+ }
+
+ public void testImplicitCall() {
+ String t = "(import org.drools.*) (bind ?p (new Person mark cheddar) ) (?p setFields bob stilton 35) (printout t (call ?p toLongString))";
+ this.shell.eval( t );
+ assertEquals( "[Person name='bob' likes='stilton' age='35']",
+ new String( this.baos.toByteArray() ) );
+ }
+
+ public void testRuleCreation() {
+ this.shell.eval( "(import org.drools.Person)" );
+
+ this.shell.eval( "(defrule yyy => (printout t yy \" \" (eq 1 1) ) ) )" );
+ Package pkg = shell.getStatefulSession().getRuleBase().getPackage( "MAIN" );
+
+ Rule rule = pkg.getRule( "yyy" );
+ assertEquals( "yyy",
+ rule.getName() );
+
+ this.shell.eval( "(defrule xxx (Person (name ?name&bob) (age 30) ) (Person (name ?name) (age 35)) => (printout t xx \" \" (eq 1 1) ) )" );
+
+ rule = pkg.getRule( "xxx" );
+ assertEquals( "xxx",
+ rule.getName() );
+
+ assertEquals( 2,
+ pkg.getRules().length );
+
+ assertTrue( pkg.getImports().containsKey( "org.drools.Person" ) );
+
+ WorkingMemory wm = shell.getStatefulSession();
+ wm.insert( new Person( "bob",
+ "cheddar",
+ 30 ) );
+ wm.insert( new Person( "bob",
+ "stilton",
+ 35 ) );
+ wm.fireAllRules();
+ assertEquals( "yy truexx true",
+ 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) ) )" );
+
+ this.shell.eval( "(defrule xxx (Person (name ?name&bob) (age 30) ) => (printout t hello bob ) )" );
+
+ this.shell.eval( "(assert (Person (name bob) (age 30) ) )" );
+ this.shell.eval( "(run)" );
+
+ assertEquals( "hellobob",
+ new String( this.baos.toByteArray() ) );
+ }
+
+ public void testTemplateCreationWithJava() throws Exception {
+ this.shell.eval( "(deftemplate Person (slot name (type String) ) (slot age (type int) ) )" );
+
+ this.shell.eval( "(defrule yyy => (printout t yy \" \" (eq 1 1) ) ) )" );
+ Package pkg = shell.getStatefulSession().getRuleBase().getPackage( "MAIN" );
+
+ Rule rule = pkg.getRule( "yyy" );
+ assertEquals( "yyy",
+ rule.getName() );
+
+ this.shell.eval( "(defrule xxx (Person (name ?name&bob) (age 30) ) (Person (name ?name) (age 35)) => (printout t xx \" \" (eq 1 1) ) )" );
+
+ rule = pkg.getRule( "xxx" );
+ assertEquals( "xxx",
+ rule.getName() );
+
+ assertEquals( 2,
+ pkg.getRules().length );
+
+ 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} );
+ wm.insert( bob1 );
+ wm.insert( bob2 );
+
+
+ wm.fireAllRules();
+ assertEquals( "yy truexx true",
+ new String( this.baos.toByteArray() ) );
+ }
+
+ public void testEmptyLHSRule() {
+ String rule1 = "(defrule testRule => (printout t hello) (printout t goodbye))";
+ this.shell.eval( rule1 );
+ assertEquals( "hellogoodbye",
+ new String( this.baos.toByteArray() ) );
+ }
+
+ public void testSimpleLHSRule() {
+ this.shell.eval( "(import org.drools.*)" );
+ this.shell.eval( "(defrule testRule (Person (name ?name&mark) ) => (printout t hello) (printout t \" \" ?name))" );
+ this.shell.eval( "(assert (Person (name mark) ) )" );
+ this.shell.eval( "(run)" );
+ assertEquals( "hello mark",
+ new String( this.baos.toByteArray() ) );
+ }
+
+ 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() ) );
+ }
+
+ 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) ) )" );
+ this.shell.eval( "(defrule testRule2 (Person (name ?name&bob) ) => (printout t hello) (printout t \" \" ?name))" );
+ this.shell.eval( "(assert (Person (name mark) ) )" );
+ this.shell.eval( "(run)" );
+ assertEquals( "hello markhello bob",
+ new String( this.baos.toByteArray() ) );
+ }
+
+ public void testBlockEval() {
+ String text = "(import org.drools.*)";
+ text += "(defrule testRule1 ?p <- (Person (name ?name&mark) ) => (printout t hello) (printout t \" \" ?name) (modify ?p (name bob) ) )";
+ text += "(defrule testRule2 (Person (name ?name&bob) ) => (printout t hello) (printout t \" \" ?name))";
+ text += "(assert (Person (name mark) ) )";
+ text += "(run)";
+ this.shell.eval( text );
+ 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) )" );
+ this.shell.eval( "(assert (Person (name mark) (age 27) ) )" );
+ this.shell.eval( "(assert (Person (name bob) (age 35) ) )" );
+ this.shell.eval( "(run)" );
+ assertEquals( "hello bob",
+ 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) )" );
+ this.shell.eval( "(assert (Person (name mark) (age 32) ) )" );
+ this.shell.eval( "(assert (Person (name bob) (age 35) ) )" );
+ this.shell.eval( "(run)" );
+ assertEquals( "hello mark",
+ 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) )" );
+ this.shell.eval( "(assert (Person (name mark) (age 32) ) )" );
+ this.shell.eval( "(assert (Person (name bob) (age 35) ) )" );
+ this.shell.eval( "(run)" );
+ assertEquals( "hello",
+ new String( this.baos.toByteArray() ) );
+ }
+
+ public void testRun() {
+ this.shell.eval( "(run)" );
+ }
+
+}
Deleted: 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 20:09:07 UTC (rev 20822)
+++ labs/jbossrules/trunk/drools-clips/src/test/java/org/drools/clips/ShellTest.java 2008-06-26 20:41:43 UTC (rev 20823)
@@ -1,394 +0,0 @@
-package org.drools.clips;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import org.drools.Person;
-import org.drools.WorkingMemory;
-import org.drools.clips.FunctionHandlers;
-import org.drools.clips.Shell;
-import org.drools.clips.functions.AssertFunction;
-import org.drools.clips.functions.BindFunction;
-import org.drools.clips.functions.CallFunction;
-import org.drools.clips.functions.CreateListFunction;
-import org.drools.clips.functions.EqFunction;
-import org.drools.clips.functions.GetFunction;
-import org.drools.clips.functions.IfFunction;
-import org.drools.clips.functions.LessThanFunction;
-import org.drools.clips.functions.MinusFunction;
-import org.drools.clips.functions.ModifyFunction;
-import org.drools.clips.functions.MoreThanFunction;
-import org.drools.clips.functions.MultiplyFunction;
-import org.drools.clips.functions.NewFunction;
-import org.drools.clips.functions.PlusFunction;
-import org.drools.clips.functions.PrintoutFunction;
-import org.drools.clips.functions.PrognFunction;
-import org.drools.clips.functions.ReturnFunction;
-import org.drools.clips.functions.RunFunction;
-import org.drools.clips.functions.SetFunction;
-import org.drools.clips.functions.SwitchFunction;
-import org.drools.rule.Package;
-import org.drools.rule.Rule;
-
-public class ShellTest extends TestCase {
- private ByteArrayOutputStream baos;
-
- Shell shell;
-
- public void setUp() {
- FunctionHandlers handlers = FunctionHandlers.getInstance();
- handlers.registerFunction( new PlusFunction() );
- handlers.registerFunction( new MinusFunction() );
- handlers.registerFunction( new MultiplyFunction() );
- handlers.registerFunction( new ModifyFunction() );
- handlers.registerFunction( new CreateListFunction() );
- handlers.registerFunction( new PrintoutFunction() );
- handlers.registerFunction( new PrognFunction() );
- handlers.registerFunction( new IfFunction() );
- handlers.registerFunction( new LessThanFunction() );
- handlers.registerFunction( new MoreThanFunction() );
- handlers.registerFunction( new EqFunction() );
- handlers.registerFunction( new SwitchFunction() );
- //handlers.registerFunction( new DeffunctionFunction() );
- handlers.registerFunction( new ReturnFunction() );
- handlers.registerFunction( new RunFunction() );
- handlers.registerFunction( new BindFunction() );
- handlers.registerFunction( new NewFunction() );
- handlers.registerFunction( new SetFunction() );
- handlers.registerFunction( new GetFunction() );
- handlers.registerFunction( new CallFunction() );
- handlers.registerFunction( new AssertFunction() );
-
- this.shell = new Shell();
-
- this.baos = new ByteArrayOutputStream();
- shell.addRouter( "t",
- new PrintStream( baos ) );
- }
-
- // 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();
- // for ( SExpression sExpression : lisplists ) {
- // FunctionHandlers.dump( sExpression, appendable, context );
- // }
- //
- // System.out.println( appendable );
- // }
-
- public void testBind() {
- String expr = "(bind ?x (create$ 10 20 30) ) (printout t ?x)";
-
- this.shell.eval( expr );
-
- assertEquals( "[10, 20, 30]",
- new String( baos.toByteArray() ) );
- }
-
- public void testProgn() {
- String expr = "(progn (?x (create$ 10 20 30) ) (printout t ?x) )";
-
- this.shell.eval( expr );
-
- assertEquals( "102030",
- new String( baos.toByteArray() ) );
- }
-
- public void testIf() {
- String expr = "(if (< 1 3) then (printout t hello) (printout t hello) )";
-
- this.shell.eval( expr );
-
- assertEquals( "hellohello",
- new String( baos.toByteArray() ) );
- }
-
- public void testIfElse() {
- String expr = "(if (eq 1 3) then (printout t hello) (printout t 1) else (printout t hello) (printout t 2))";
-
- this.shell.eval( expr );
-
- assertEquals( "hello2",
- new String( baos.toByteArray() ) );
- }
-
- public void testSwitch() throws IOException {
- String expr = "(switch (?x) (case a then (printout t hello)(printout t 1)) (case b then (printout t hello)(printout t 2)) (default (printout t hello)(printout t 3)) )";
-
- // check case a
- this.shell.addVariable( "$x",
- "a" );
- this.shell.eval( expr );
- assertEquals( "hello1",
- new String( baos.toByteArray() ) );
-
- // check default
- this.shell.addVariable( "$x",
- "M" );
- this.shell.eval( expr );
- assertEquals( "hello1hello3",
- new String( baos.toByteArray() ) );
-
- // check case b
- this.shell.addVariable( "$x",
- "b" );
- this.shell.eval( expr );
- assertEquals( "hello1hello3hello2",
- new String( baos.toByteArray() ) );
- }
-
- // @FIXME - org.mvel.CompileException: unable to resolve property: unable to resolve method: org.drools.clips.Shell.max(java.lang.Integer, java.lang.Integer) [arglength=2]
- public void testDeffunction() {
- String function = "(deffunction max (?a ?b) (if (> ?a ?b) then (return ?a) else (return ?b) ) )";
- this.shell.eval( function );
-
- String expr = "(if (eq (max 3 5) 5) then (printout t hello) )";
- this.shell.eval( expr );
- assertEquals( "hello",
- new String( baos.toByteArray() ) );
-
- expr = "(if (eq (max ?a ?b) 5) then (printout t hello) )";
- this.shell.addVariable( "$a",
- "3" );
- this.shell.addVariable( "$b",
- "5" );
- this.shell.eval( expr );
- assertEquals( "hellohello",
- new String( baos.toByteArray() ) );
- }
-
- public void testDirectImportAndNew() {
- String t = "(import org.drools.Person) (bind ?p (new Person mark cheddar) ) (printout t ?p)";
- this.shell.eval( t );
- assertEquals( "[Person name='mark']",
- new String( this.baos.toByteArray() ) );
- }
-
- public void testDynamicImportAndNew() {
- String t = "(import org.drools.*) (bind ?p (new Person mark cheddar) ) (printout t ?p)";
- this.shell.eval( t );
- assertEquals( "[Person name='mark']",
- new String( this.baos.toByteArray() ) );
- }
-
- public void testSet() {
- String t = "(import org.drools.*) (bind ?p (new Person mark cheddar) ) (set ?p name bob) (printout t ?p)";
- this.shell.eval( t );
- assertEquals( "[Person name='bob']",
- new String( this.baos.toByteArray() ) );
- }
-
- public void testGet() {
- String t = "(import org.drools.*) (bind ?p (new Person mark cheddar) )(printout t (get ?p name))";
- this.shell.eval( t );
- assertEquals( "mark",
- new String( this.baos.toByteArray() ) );
- }
-
-
- public void testExplicitCall() {
- String t = "(import org.drools.*) (bind ?p (new Person mark cheddar) ) (call ?p setFields bob stilton 35) (printout t (call ?p toLongString))";
- this.shell.eval( t );
- assertEquals( "[Person name='bob' likes='stilton' age='35']",
- new String( this.baos.toByteArray() ) );
- }
-
- public void testImplicitCall() {
- String t = "(import org.drools.*) (bind ?p (new Person mark cheddar) ) (?p setFields bob stilton 35) (printout t (call ?p toLongString))";
- this.shell.eval( t );
- assertEquals( "[Person name='bob' likes='stilton' age='35']",
- new String( this.baos.toByteArray() ) );
- }
-
- public void testRuleCreation() {
- this.shell.eval( "(import org.drools.Person)" );
-
- this.shell.eval( "(defrule yyy => (printout t yy \" \" (eq 1 1) ) ) )" );
- Package pkg = shell.getStatefulSession().getRuleBase().getPackage( "MAIN" );
-
- Rule rule = pkg.getRule( "yyy" );
- assertEquals( "yyy",
- rule.getName() );
-
- this.shell.eval( "(defrule xxx (Person (name ?name&bob) (age 30) ) (Person (name ?name) (age 35)) => (printout t xx \" \" (eq 1 1) ) )" );
-
- rule = pkg.getRule( "xxx" );
- assertEquals( "xxx",
- rule.getName() );
-
- assertEquals( 2,
- pkg.getRules().length );
-
- assertTrue( pkg.getImports().containsKey( "org.drools.Person" ) );
-
- WorkingMemory wm = shell.getStatefulSession();
- wm.insert( new Person( "bob",
- "cheddar",
- 30 ) );
- wm.insert( new Person( "bob",
- "stilton",
- 35 ) );
- wm.fireAllRules();
- assertEquals( "yy truexx true",
- 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) ) )" );
-
- this.shell.eval( "(defrule xxx (Person (name ?name&bob) (age 30) ) => (printout t hello bob ) )" );
-
- this.shell.eval( "(assert (Person (name bob) (age 30) ) )" );
- this.shell.eval( "(run)" );
-
- assertEquals( "hellobob",
- new String( this.baos.toByteArray() ) );
- }
-
- public void testTemplateCreationWithJava() throws Exception {
- this.shell.eval( "(deftemplate Person (slot name (type String) ) (slot age (type int) ) )" );
-
- this.shell.eval( "(defrule yyy => (printout t yy \" \" (eq 1 1) ) ) )" );
- Package pkg = shell.getStatefulSession().getRuleBase().getPackage( "MAIN" );
-
- Rule rule = pkg.getRule( "yyy" );
- assertEquals( "yyy",
- rule.getName() );
-
- this.shell.eval( "(defrule xxx (Person (name ?name&bob) (age 30) ) (Person (name ?name) (age 35)) => (printout t xx \" \" (eq 1 1) ) )" );
-
- rule = pkg.getRule( "xxx" );
- assertEquals( "xxx",
- rule.getName() );
-
- assertEquals( 2,
- pkg.getRules().length );
-
- 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} );
- wm.insert( bob1 );
- wm.insert( bob2 );
-
-
- wm.fireAllRules();
- assertEquals( "yy truexx true",
- new String( this.baos.toByteArray() ) );
- }
-
- public void testEmptyLHSRule() {
- String rule1 = "(defrule testRule => (printout t hello) (printout t goodbye))";
- this.shell.eval( rule1 );
- assertEquals( "hellogoodbye",
- new String( this.baos.toByteArray() ) );
- }
-
- public void testSimpleLHSRule() {
- this.shell.eval( "(import org.drools.*)" );
- this.shell.eval( "(defrule testRule (Person (name ?name&mark) ) => (printout t hello) (printout t \" \" ?name))" );
- this.shell.eval( "(assert (Person (name mark) ) )" );
- this.shell.eval( "(run)" );
- assertEquals( "hello mark",
- new String( this.baos.toByteArray() ) );
- }
-
- 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() ) );
- }
-
- 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) ) )" );
- this.shell.eval( "(defrule testRule2 (Person (name ?name&bob) ) => (printout t hello) (printout t \" \" ?name))" );
- this.shell.eval( "(assert (Person (name mark) ) )" );
- this.shell.eval( "(run)" );
- assertEquals( "hello markhello bob",
- new String( this.baos.toByteArray() ) );
- }
-
- public void testBlockEval() {
- String text = "(import org.drools.*)";
- text += "(defrule testRule1 ?p <- (Person (name ?name&mark) ) => (printout t hello) (printout t \" \" ?name) (modify ?p (name bob) ) )";
- text += "(defrule testRule2 (Person (name ?name&bob) ) => (printout t hello) (printout t \" \" ?name))";
- text += "(assert (Person (name mark) ) )";
- text += "(run)";
- this.shell.eval( text );
- 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) )" );
- this.shell.eval( "(assert (Person (name mark) (age 27) ) )" );
- this.shell.eval( "(assert (Person (name bob) (age 35) ) )" );
- this.shell.eval( "(run)" );
- assertEquals( "hello bob",
- 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) )" );
- this.shell.eval( "(assert (Person (name mark) (age 32) ) )" );
- this.shell.eval( "(assert (Person (name bob) (age 35) ) )" );
- this.shell.eval( "(run)" );
- assertEquals( "hello mark",
- 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) )" );
- this.shell.eval( "(assert (Person (name mark) (age 32) ) )" );
- this.shell.eval( "(assert (Person (name bob) (age 35) ) )" );
- this.shell.eval( "(run)" );
- assertEquals( "hello",
- new String( this.baos.toByteArray() ) );
- }
-
- public void testRun() {
- this.shell.eval( "(run)" );
- }
-
-}
More information about the jboss-svn-commits
mailing list