[jboss-svn-commits] JBL Code SVN: r15131 - in labs/jbossrules/trunk/drools-ant/src: test/resources and 1 other directory.

jboss-svn-commits at lists.jboss.org jboss-svn-commits at lists.jboss.org
Fri Sep 14 17:18:18 EDT 2007


Author: fmeyer
Date: 2007-09-14 17:18:18 -0400 (Fri, 14 Sep 2007)
New Revision: 15131

Modified:
   labs/jbossrules/trunk/drools-ant/src/main/java/org/drools/contrib/DroolsAntTask.java
   labs/jbossrules/trunk/drools-ant/src/test/resources/DroolsAntTask.xml
Log:
JBRULES-1118 Added support for multiple dsl files

Modified: labs/jbossrules/trunk/drools-ant/src/main/java/org/drools/contrib/DroolsAntTask.java
===================================================================
--- labs/jbossrules/trunk/drools-ant/src/main/java/org/drools/contrib/DroolsAntTask.java	2007-09-14 20:36:54 UTC (rev 15130)
+++ labs/jbossrules/trunk/drools-ant/src/main/java/org/drools/contrib/DroolsAntTask.java	2007-09-14 21:18:18 UTC (rev 15131)
@@ -27,6 +27,7 @@
 import java.io.InputStreamReader;
 import java.io.ObjectOutputStream;
 import java.io.Reader;
+import java.io.StringReader;
 
 import org.apache.tools.ant.AntClassLoader;
 import org.apache.tools.ant.BuildException;
@@ -36,292 +37,329 @@
 import org.apache.tools.ant.types.Reference;
 import org.drools.RuleBase;
 import org.drools.RuleBaseFactory;
+import org.drools.RuntimeDroolsException;
 import org.drools.brms.client.modeldriven.brl.RuleModel;
 import org.drools.brms.server.util.BRDRLPersistence;
 import org.drools.brms.server.util.BRXMLPersistence;
+import org.drools.compiler.DrlParser;
 import org.drools.compiler.DroolsParserException;
 import org.drools.compiler.PackageBuilder;
 import org.drools.compiler.PackageBuilderConfiguration;
+import org.drools.lang.Expander;
+import org.drools.lang.dsl.DSLMappingFile;
+import org.drools.lang.dsl.DefaultExpander;
+import org.drools.lang.dsl.DefaultExpanderResolver;
 
 /**
- * An ant task to allow rulebase compilation and serialization
- * during a build.
+ * An ant task to allow rulebase compilation and serialization during a build.
  * 
  * @author etirelli
  */
 public class DroolsAntTask extends MatchingTask {
-    
-    
-    public static String BRLFILEEXTENSION = ".brl";
-    public static String XMLFILEEXTENSION = ".xml";
-    public static String RULEFLOWFILEEXTENSION = ".rfm";
-    public static String DSLFILEEXTENSION = ".dslr";
-    
-    private File srcdir;
-    private File toFile;
-    private Path classpath;
-    private String dslfile;
-    
-    public String getDslfile() {
-		return dslfile;
+
+	public static String BRLFILEEXTENSION = ".brl";
+	public static String XMLFILEEXTENSION = ".xml";
+	public static String RULEFLOWFILEEXTENSION = ".rfm";
+	public static String DSLFILEEXTENSION = ".dslr";
+
+	private File srcdir;
+	private File toFile;
+	private Path classpath;
+
+	
+	/**
+	 * Source directory to read DRL files from
+	 * 
+	 * @param directory
+	 */
+	public void setSrcDir(File directory) {
+		this.srcdir = directory;
 	}
 
-	public void setDslfile(String dslfile) {
-		this.dslfile = dslfile;
+	/**
+	 * File to serialize the rulebase to
+	 * 
+	 * @param toFile
+	 */
+	public void setToFile(File toFile) {
+		this.toFile = toFile;
 	}
 
 	/**
-     * Source directory to read DRL files from
-     * 
-     * @param directory
-     */
-    public void setSrcDir(File directory) {
-        this.srcdir = directory;
-    }
+	 * The classpath to use when compiling the rulebase
+	 * 
+	 * @param classpath
+	 */
+	public void setClasspath(Path classpath) {
+		createClasspath().append(classpath);
+	}
 
-    /**
-     * File to serialize the rulebase to
-     * 
-     * @param toFile
-     */
-    public void setToFile(File toFile) {
-        this.toFile = toFile;
-    }
+	/**
+	 * Classpath to use, by reference, when compiling the rulebase
+	 * 
+	 * @param r
+	 *            a reference to an existing classpath
+	 */
+	public void setClasspathref(Reference r) {
+		createClasspath().setRefid(r);
+	}
 
-    /**
-     * The classpath to use when compiling the rulebase
-     * 
-     * @param classpath
-     */
-    public void setClasspath(Path classpath) {
-        createClasspath().append( classpath );
-    }
+	/**
+	 * Adds a path to the classpath.
+	 * 
+	 * @return created classpath
+	 */
+	public Path createClasspath() {
+		if (this.classpath == null) {
+			this.classpath = new Path(getProject());
+		}
+		return this.classpath.createPath();
+	}
 
-    /**
-     * Classpath to use, by reference, when compiling the rulebase
-     *
-     * @param r a reference to an existing classpath
-     */
-    public void setClasspathref(Reference r) {
-        createClasspath().setRefid( r );
-    }
+	/**
+	 * Task's main method
+	 */
+	public void execute() throws BuildException {
+		super.execute();
 
-    /**
-     * Adds a path to the classpath.
-     *
-     * @return created classpath
-     */
-    public Path createClasspath() {
-        if ( this.classpath == null ) {
-            this.classpath = new Path( getProject() );
-        }
-        return this.classpath.createPath();
-    }
+		// checking parameters are set
+		if (toFile == null) {
+			throw new BuildException(
+					"Destination rulebase file does not specified.");
+		}
 
-    /**
-     * Task's main method
-     */
-    public void execute() throws BuildException {
-        super.execute();
+		// checking parameters are set
+		if (srcdir == null) {
+			throw new BuildException("Source directory not specified.");
+		}
 
-        // checking parameters are set
-        if ( toFile == null ) {
-            throw new BuildException( "Destination rulebase file does not specified." );
-        }
+		if (!srcdir.exists()) {
+			throw new BuildException("Source directory does not exists."
+					+ srcdir.getAbsolutePath());
+		}
 
-        // checking parameters are set
-        if ( srcdir == null ) {
-            throw new BuildException( "Source directory not specified." );
-        }
+		try {
+			// create a specialized classloader
+			AntClassLoader loader = getClassLoader();
 
-        if ( !srcdir.exists() ) {
-            throw new BuildException( "Source directory does not exists." + srcdir.getAbsolutePath() );
-        }
+			// create a package builder configured to use the given classloader
+			PackageBuilder builder = getPackageBuilder(loader);
 
-        try {
-            // create a specialized classloader
-            AntClassLoader loader = getClassLoader();
+			// get the list of files to be added to the rulebase
+			String[] fileNames = getFileList();
 
-            // create a package builder configured to use the given classloader
-            PackageBuilder builder = getPackageBuilder( loader );
+			for (int i = 0; i < fileNames.length; i++) {
+				// compile rule file and add to the builder
+				compileAndAddFile(builder, fileNames[i]);
+			}
 
-            // get the list of files to be added to the rulebase
-            String[] fileNames = getFileList();
+			// gets the package
+			org.drools.rule.Package pkg = builder.getPackage();
 
-            for ( int i = 0; i < fileNames.length; i++ ) {
-                // compile rule file and add to the builder
-                compileAndAddFile( builder,
-                                   fileNames[i] );
-            }
+			// creates the rulebase
+			RuleBase ruleBase = RuleBaseFactory.newRuleBase();
 
-            // gets the package 
-            org.drools.rule.Package pkg = builder.getPackage();
+			// adds the package
+			ruleBase.addPackage(pkg);
 
-            // creates the rulebase
-            RuleBase ruleBase = RuleBaseFactory.newRuleBase();
+			// serialize the rule base to the destination file
+			serializeRulebase(ruleBase);
 
-            // adds the package
-            ruleBase.addPackage( pkg );
+		} catch (Exception e) {
+			throw new BuildException("RuleBaseTask failed: " + e.getMessage(),
+					e);
+		}
+	}
 
-            // serialize the rule base to the destination file
-            serializeRulebase( ruleBase );
+	/**
+	 * @param ruleBase
+	 * @throws FileNotFoundException
+	 * @throws IOException
+	 */
+	private void serializeRulebase(RuleBase ruleBase)
+			throws FileNotFoundException, IOException {
+		ObjectOutputStream outstream = null;
+		try {
+			FileOutputStream fout = new FileOutputStream(toFile);
+			outstream = new ObjectOutputStream(fout);
+			outstream.writeObject(ruleBase);
+		} finally {
+			if (outstream != null) {
+				outstream.close();
+			}
+		}
+	}
 
-        } catch ( Exception e ) {
-            throw new BuildException( "RuleBaseTask failed: " + e.getMessage(),
-                                      e );
-        }
-    }
+	/**
+	 * @param builder
+	 * @param fileName
+	 * @return
+	 * @throws FileNotFoundException
+	 * @throws DroolsParserException
+	 * @throws IOException
+	 */
+	private void compileAndAddFile(PackageBuilder builder, String fileName)
+			throws FileNotFoundException, DroolsParserException, IOException {
+		InputStreamReader instream = null;
 
-    /**
-     * @param ruleBase
-     * @throws FileNotFoundException
-     * @throws IOException
-     */
-    private void serializeRulebase(RuleBase ruleBase) throws FileNotFoundException,
-                                                     IOException {
-        ObjectOutputStream outstream = null;
-        try {
-            FileOutputStream fout = new FileOutputStream( toFile );
-            outstream = new ObjectOutputStream( fout );
-            outstream.writeObject( ruleBase );
-        } finally {
-            if ( outstream != null ) {
-                outstream.close();
-            }
-        }
-    }
+		try {
 
-    /**
-     * @param builder
-     * @param fileName
-     * @return
-     * @throws FileNotFoundException
-     * @throws DroolsParserException
-     * @throws IOException
-     */
-    private void compileAndAddFile(PackageBuilder builder,
-                                   String fileName) throws FileNotFoundException,
-                                                   DroolsParserException,
-                                                   IOException {
-        InputStreamReader instream = null;
+			if (fileName.endsWith(DroolsAntTask.BRLFILEEXTENSION)) {
 
-        try {
+				RuleModel model = BRXMLPersistence.getInstance().unmarshal(
+						loadResource(fileName));
+				String packagefile = loadResource(resolvePackageFile(this.srcdir
+						.getAbsolutePath()));
+				model.name = fileName.replace(DroolsAntTask.BRLFILEEXTENSION,
+						"");
+				ByteArrayInputStream istream = new ByteArrayInputStream(
+						(packagefile + BRDRLPersistence.getInstance().marshal(
+								model)).getBytes());
+				instream = new InputStreamReader(istream);
 
-            if ( fileName.endsWith( DroolsAntTask.BRLFILEEXTENSION ) ) {
-            	
-                RuleModel model = BRXMLPersistence.getInstance().unmarshal( loadResource( fileName ) );
-                String packagefile = loadResource( resolvePackageFile( this.srcdir.getAbsolutePath() ) );
-                model.name = fileName.replace( DroolsAntTask.BRLFILEEXTENSION, "" );
-                ByteArrayInputStream istream = new ByteArrayInputStream( (packagefile + BRDRLPersistence.getInstance().marshal( model )).getBytes() );
-                instream = new InputStreamReader( istream );
-                
-            } else {
-                File file = new File( this.srcdir, fileName );
-                instream = new InputStreamReader( new FileInputStream( file ) );
-            }
+			} else {
+				File file = new File(this.srcdir, fileName);
+				instream = new InputStreamReader(new FileInputStream(file));
+			}
 
-            if ( fileName.endsWith( DroolsAntTask.RULEFLOWFILEEXTENSION ) ) {
-                builder.addRuleFlow( instream );
-            } else if ( fileName.endsWith( DroolsAntTask.XMLFILEEXTENSION ) ) {
-                builder.addPackageFromXml( instream );
-            } else if (fileName.endsWith(DroolsAntTask.DSLFILEEXTENSION)) {
-                File dslFile = new File( this.srcdir, dslfile );
-                InputStreamReader instreamDsl = new InputStreamReader( new FileInputStream( dslFile ) );
-            	builder.addPackageFromDrl(instream, instreamDsl);
-            } else {
-                builder.addPackageFromDrl( instream );
-            }
-        } finally {
-            if ( instream != null ) {
-                instream.close();
-            }
-        }
-    }
-    
-    private String resolvePackageFile(String dirname) {
+			if (fileName.endsWith(DroolsAntTask.RULEFLOWFILEEXTENSION)) {
+				builder.addRuleFlow(instream);
+			} else if (fileName.endsWith(DroolsAntTask.XMLFILEEXTENSION)) {
+				builder.addPackageFromXml(instream);
+			} else if (fileName.endsWith(DroolsAntTask.DSLFILEEXTENSION)) {
+				DrlParser parser = new DrlParser();
+				String expandedDRL = parser.getExpandedDRL(
+						loadResource(fileName), resolveDSLFiles());
+				builder.addPackageFromDrl(new StringReader(expandedDRL));
+			} else {
+				builder.addPackageFromDrl(instream);
+			}
+		} finally {
+			if (instream != null) {
+				instream.close();
+			}
+		}
+	}
 
-        File dir = new File( dirname );
+	private DefaultExpanderResolver resolveDSLFiles() throws IOException {
 
-        FilenameFilter filter = new FilenameFilter() {
-            public boolean accept(File dir,
-                                  String name) {
-                return name.endsWith( ".package" );
-            }
-        };
+		DefaultExpanderResolver resolver = new DefaultExpanderResolver();
+		final File dir = new File(this.srcdir.getAbsolutePath());
+		DSLMappingFile file = new DSLMappingFile();
 
-        String[] children = dir.list( filter );
-        if ( children.length > 1 ) {
-            throw new BuildException( "There are more than one package configuration file for this directory :" + dirname );
-        }
+		FilenameFilter filter = new FilenameFilter() {
+			public boolean accept(File dir, String name) {
+				return name.endsWith(".dsl");
+			}
+		};
 
-        if ( children.length == 0 ) {
-            throw new BuildException( "There is no package configuration file for this directory:" + dirname );
-        }
+		String[] children = dir.list(filter);
+		if (children.length == 0) {
+			throw new BuildException(
+					"There are no DSL files for this directory:"
+							+ this.srcdir.getAbsolutePath());
+		}
 
-        return children[0];
-    }
+		for (int index = 0; index < children.length; index++) {
+			if (file.parseAndLoad(new StringReader(loadResource(children[index])))) {
+				final Expander expander = new DefaultExpander();
+				expander.addDSLMapping(file.getMapping());
+				resolver.addExpander("*", expander);
+			} else {
+				throw new RuntimeDroolsException(
+						"Error parsing and loading DSL file."
+								+ file.getErrors());
+			}
+		}
 
-    private String loadResource(final String name) throws IOException {
+		return resolver;
+	}
 
-        final InputStream in = new FileInputStream( this.srcdir + "/" + name );
-        final Reader reader = new InputStreamReader( in );
-        final StringBuffer text = new StringBuffer();
-        final char[] buf = new char[1024];
-        int len = 0;
+	private String resolvePackageFile(String dirname) {
 
-        while ( (len = reader.read( buf )) >= 0 ) {
-            text.append( buf,
-                         0,
-                         len );
-        }
+		File dir = new File(dirname);
+		FilenameFilter filter = new FilenameFilter() {
+			public boolean accept(File dir, String name) {
+				return name.endsWith(".package");
+			}
+		};
 
-        return text.toString();
-    }
+		String[] children = dir.list(filter);
+		if (children.length > 1) {
+			throw new BuildException(
+					"There are more than one package configuration file for this directory :"
+							+ dirname);
+		}
 
-    /**
-     * @return
-     */
-    private AntClassLoader getClassLoader() {
-        // defining a new specialized classloader and setting it as the thread context classloader
-        AntClassLoader loader = null;
-        if ( classpath != null ) {
-            loader = new AntClassLoader( PackageBuilder.class.getClassLoader(),
-                                         getProject(),
-                                         classpath,
-                                         false );
-        } else {
-            loader = new AntClassLoader( PackageBuilder.class.getClassLoader(),
-                                         false );
-        }
-        loader.setThreadContextLoader();
-        return loader;
-    }
+		if (children.length == 0) {
+			throw new BuildException(
+					"There is no package configuration file for this directory:"
+							+ dirname);
+		}
 
-    /**
-     * @param loader
-     * @return
-     */
-    private PackageBuilder getPackageBuilder(AntClassLoader loader) {
-        // creating package builder configured with the give classloader
-        PackageBuilderConfiguration conf = new PackageBuilderConfiguration();
-        conf.setClassLoader( loader );
-        PackageBuilder builder = new PackageBuilder( conf );
-        return builder;
-    }
+		return children[0];
+	}
 
-    /**
-     * Returns the list of files to be added into the rulebase
-     * @return
-     */
-    private String[] getFileList() {
-        // scan source directory for rule files
-        DirectoryScanner directoryScanner = getDirectoryScanner( srcdir );
-        String[] fileNames = directoryScanner.getIncludedFiles();
+	private String loadResource(final String name) throws IOException {
 
-        if ( fileNames == null || fileNames.length <= 0 ) {
-            throw new BuildException( "No rule files found in include directory." );
-        }
-        return fileNames;
-    }
+		final InputStream in = new FileInputStream(this.srcdir + "/" + name);
+		final Reader reader = new InputStreamReader(in);
+		final StringBuffer text = new StringBuffer();
+		final char[] buf = new char[1024];
+		int len = 0;
 
+		while ((len = reader.read(buf)) >= 0) {
+			text.append(buf, 0, len);
+		}
+
+		return text.toString();
+	}
+
+	/**
+	 * @return
+	 */
+	private AntClassLoader getClassLoader() {
+		// defining a new specialized classloader and setting it as the thread
+		// context classloader
+		AntClassLoader loader = null;
+		if (classpath != null) {
+			loader = new AntClassLoader(PackageBuilder.class.getClassLoader(),
+					getProject(), classpath, false);
+		} else {
+			loader = new AntClassLoader(PackageBuilder.class.getClassLoader(),
+					false);
+		}
+		loader.setThreadContextLoader();
+		return loader;
+	}
+
+	/**
+	 * @param loader
+	 * @return
+	 */
+	private PackageBuilder getPackageBuilder(AntClassLoader loader) {
+		// creating package builder configured with the give classloader
+		PackageBuilderConfiguration conf = new PackageBuilderConfiguration();
+		conf.setClassLoader(loader);
+		PackageBuilder builder = new PackageBuilder(conf);
+		return builder;
+	}
+
+	/**
+	 * Returns the list of files to be added into the rulebase
+	 * 
+	 * @return
+	 */
+	private String[] getFileList() {
+		// scan source directory for rule files
+		DirectoryScanner directoryScanner = getDirectoryScanner(srcdir);
+		String[] fileNames = directoryScanner.getIncludedFiles();
+
+		if (fileNames == null || fileNames.length <= 0) {
+			throw new BuildException(
+					"No rule files found in include directory.");
+		}
+		return fileNames;
+	}
+
 }

Modified: labs/jbossrules/trunk/drools-ant/src/test/resources/DroolsAntTask.xml
===================================================================
--- labs/jbossrules/trunk/drools-ant/src/test/resources/DroolsAntTask.xml	2007-09-14 20:36:54 UTC (rev 15130)
+++ labs/jbossrules/trunk/drools-ant/src/test/resources/DroolsAntTask.xml	2007-09-14 21:18:18 UTC (rev 15131)
@@ -14,16 +14,14 @@
 		<pathelement location="target"/>
 	</path>	
 	
-	<taskdef name="rulebase" 
-		classname="org.drools.contrib.DroolsAntTask" 
-		classpathref="drools.classpath" />
+	<taskdef name="rulebase" classname="org.drools.contrib.DroolsAntTask" classpathref="drools.classpath" />
 	
 	<target name="dslRules" >
 		<rulebase 
 			srcdir="${eclipsepath}src/test/resources/rules" 		
 			tofile="${eclipsepath}target/cheese.rules"
-			classpathref="cheese.classpath"
-			dslfile="cheese.dsl"> 
+			classpathref="cheese.classpath" > 
+			
 			<include name="*.dslr" />
 		</rulebase>
 	</target>
@@ -36,6 +34,7 @@
 			<include name="*.drl" />
 			<include name="*.brl" />
 			<include name="*.xml" />
+			<include name="*.dslr" />			
 		</rulebase>
 	</target>
 	
@@ -58,4 +57,5 @@
 			<include name="*.brl" />
 		</rulebase>
 	</target>
+
 </project>
\ No newline at end of file




More information about the jboss-svn-commits mailing list