[jboss-svn-commits] JBL Code SVN: r36714 - in labs/jbossrules/tags/5.2.0.M1: drools-templates and 24 other directories.
jboss-svn-commits at lists.jboss.org
jboss-svn-commits at lists.jboss.org
Thu Feb 24 12:54:44 EST 2011
Author: ge0ffrey
Date: 2011-02-24 12:54:43 -0500 (Thu, 24 Feb 2011)
New Revision: 36714
Added:
labs/jbossrules/tags/5.2.0.M1/drools-templates/
labs/jbossrules/tags/5.2.0.M1/drools-templates/.gitignore
labs/jbossrules/tags/5.2.0.M1/drools-templates/build.properties
labs/jbossrules/tags/5.2.0.M1/drools-templates/pom.xml
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/DataProvider.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/DataProviderCompiler.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/ObjectDataCompiler.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/jdbc/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/jdbc/ResultSetGenerator.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Condition.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Consequence.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/DRLElement.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/DRLJavaEmitter.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/DRLOutput.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Functions.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Global.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Import.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Package.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Queries.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Rule.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/SnippetBuilder.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/objects/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/objects/ArrayDataProvider.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/objects/ObjectDataProvider.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/AbstractColumn.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/ArrayCell.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/ArrayColumn.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/BooleanCell.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/BooleanColumn.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Cell.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Column.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/ColumnFactory.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DataListener.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DecisionTableParseException.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultGenerator.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultTemplateColumn.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultTemplateContainer.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultTemplateRuleBase.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Generator.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/LongCell.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/LongColumn.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Row.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/RuleTemplate.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/StringCell.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/StringColumn.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateColumn.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateContainer.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateDataListener.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateRuleBase.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/resources/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/resources/org/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/resources/org/drools/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/resources/org/drools/template/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/resources/org/drools/template/package.html
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/DataProviderCompilerIntegrationTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/Cheese.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/Person.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/ResultSetGeneratorTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/FunctionsRenderTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/PackageRenderTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/QueriesRenderTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/RuleRenderTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/SnippetBuilderTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/ColumnFactoryTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/DefaultGeneratorTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/DefaultTemplateContainerTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/DefaultTemplateRuleBaseTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/ExternalSheetListenerTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/RuleTemplateTest.java
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/Cheese.drt
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/rule_template_1.drl
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_complex.drl
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_conditions.drl
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid1.drl
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid2.drl
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid3.drl
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid4.drl
labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_simple.drl
Log:
All monolothic build versions (<= 5.2.0.M1) stay in subversion
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/.gitignore
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/.gitignore (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/.gitignore 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,13 @@
+/target
+/local
+
+# Eclipse, Netbeans and IntelliJ files
+/.*
+!.gitignore
+/nbproject
+/*.ipr
+/*.iws
+/*.iml
+
+# The META-INF directory is generated by the maven-felix-plugin
+META-INF
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/build.properties
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/build.properties (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/build.properties 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,12 @@
+src.includes = .,\
+ build.properties,\
+ META-INF/,\
+ src/,\
+ pom.xml
+bin.includes = .,\
+ META-INF/,\
+ build.properties
+source.. = src/main/java/,\
+ src/main/resources/
+output.. = target/classes/
+jars.compile.order = .
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/pom.xml
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/pom.xml (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/pom.xml 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.drools</groupId>
+ <artifactId>drools</artifactId>
+ <version>5.2.0.M1</version>
+ </parent>
+ <artifactId>drools-templates</artifactId>
+ <packaging>jar</packaging>
+ <name>Drools :: Templates</name>
+
+ <dependencies>
+ <!-- Internal dependencies -->
+ <dependency>
+ <groupId>org.drools</groupId>
+ <artifactId>drools-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.drools</groupId>
+ <artifactId>drools-compiler</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.hsqldb</groupId>
+ <artifactId>hsqldb</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-jar-plugin</artifactId>
+ <configuration>
+ <archive>
+ <manifestFile>META-INF/MANIFEST.MF</manifestFile>
+ </archive>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <executions>
+ <execution>
+ <id>manifest</id>
+ <phase>process-classes</phase>
+ <goals>
+ <goal>manifest</goal>
+ </goals>
+ </execution>
+ </executions>
+ <configuration>
+ <manifestLocation>META-INF</manifestLocation>
+ <instructions>
+ <Bundle-SymbolicName>org.drools.templates;singleton:=true</Bundle-SymbolicName>
+ <_removeheaders>Ignore-Package</_removeheaders>
+ <Require-Bundle>org.drools.core;bundle-version="5.2.0.M1"</Require-Bundle>
+ <Import-Package>!org.drools.*, *</Import-Package>
+ <Export-Package>org.drools.*</Export-Package>
+ <DynamicImport-Package>org.drools.*</DynamicImport-Package>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/DataProvider.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/DataProvider.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/DataProvider.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,9 @@
+package org.drools.template;
+
+public interface DataProvider {
+
+ boolean hasNext();
+
+ String[] next();
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/DataProviderCompiler.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/DataProviderCompiler.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/DataProviderCompiler.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.drools.template;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.drools.template.parser.DataListener;
+import org.drools.template.parser.DefaultTemplateContainer;
+import org.drools.template.parser.TemplateContainer;
+import org.drools.template.parser.TemplateDataListener;
+
+/**
+ * An object of this class acts as a template compiler, inserting spreadsheet
+ * data into templates. Template data may come from a resource or an
+ * InputStream, or you may provide a TemplateDataListener.
+ */
+public class DataProviderCompiler {
+
+ /**
+ * Generates DRL from a data provider for the spreadsheet data and templates.
+ * @param dataProvider the data provider for the spreadsheet data
+ * @param template the string containing the template resource name
+ * @return the generated DRL text as a String
+ */
+ public String compile(final DataProvider dataProvider,
+ final String template) {
+ final InputStream templateStream = this.getClass().getResourceAsStream( template );
+ return compile( dataProvider,
+ templateStream );
+ }
+
+ /**
+ * Generates DRL from a data provider for the spreadsheet data and templates.
+ * @param dataProvider the data provider for the spreadsheet data
+ * @param templateStream the InputStream for reading the templates
+ * @return the generated DRL text as a String
+ */
+ public String compile(final DataProvider dataProvider,
+ final InputStream templateStream) {
+ TemplateContainer tc = new DefaultTemplateContainer( templateStream );
+ closeStream( templateStream );
+ return compile( dataProvider,
+ new TemplateDataListener( tc ) );
+ }
+
+ /**
+ * Generates DRL from a data provider for the spreadsheet data and templates.
+ * @param dataProvider the data provider for the spreadsheet data
+ * @param listener a template data listener
+ * @return the generated DRL text as a String
+ */
+ public String compile(final DataProvider dataProvider,
+ final TemplateDataListener listener) {
+ List<DataListener> listeners = new ArrayList<DataListener>();
+ listeners.add( listener );
+ processData( dataProvider,
+ listeners );
+ return listener.renderDRL();
+ }
+
+ private void processData(final DataProvider dataProvider,
+ List<DataListener> listeners) {
+ for ( int i = 0; dataProvider.hasNext(); i++ ) {
+ String[] row = dataProvider.next();
+ newRow( listeners,
+ i,
+ row.length );
+ for ( int cellNum = 0; cellNum < row.length; cellNum++ ) {
+ String cell = row[cellNum];
+
+ newCell( listeners,
+ i,
+ cellNum,
+ cell,
+ DataListener.NON_MERGED );
+ }
+ }
+ finishData( listeners );
+ }
+
+ private void finishData(List<DataListener> listeners) {
+ for ( DataListener listener : listeners ) {
+ listener.finishSheet();
+ }
+ }
+
+ private void newRow(List<DataListener> listeners,
+ int row,
+ int cols) {
+ for ( DataListener listener : listeners ) {
+ listener.newRow( row,
+ cols );
+ }
+ }
+
+ public void newCell(List<DataListener> listeners,
+ int row,
+ int column,
+ String value,
+ int mergedColStart) {
+ for ( DataListener listener : listeners ) {
+ listener.newCell( row,
+ column,
+ value,
+ mergedColStart );
+ }
+ }
+
+ protected void closeStream(final InputStream stream) {
+ try {
+ stream.close();
+ } catch ( final Exception e ) {
+ System.err.print( "WARNING: Wasn't able to correctly close stream for rule template. " + e.getMessage() );
+ }
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/ObjectDataCompiler.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/ObjectDataCompiler.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/ObjectDataCompiler.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,47 @@
+package org.drools.template;
+
+import java.io.InputStream;
+import java.util.Collection;
+
+import org.drools.template.parser.DefaultTemplateContainer;
+import org.drools.template.parser.TemplateContainer;
+import org.drools.template.parser.TemplateDataListener;
+
+import org.drools.template.objects.ObjectDataProvider;
+
+/**
+ * This class provides additional methods for invoking the template
+ * compiler, taking the actual parameters from maps or objects.
+ *
+ * @author Wolfgang Laun
+ *
+ */
+public class ObjectDataCompiler extends DataProviderCompiler {
+
+ /**
+ * Compile templates, substituting from a collection of maps or objects
+ * into the given template.
+ * @param objs the collection of maps or objects
+ * @param template the template resource pathname
+ * @return the expanded rules as a string
+ */
+ public String compile(final Collection<?> objs, final String template) {
+ final InputStream templateStream = this.getClass().getResourceAsStream( template );
+ return compile( objs, templateStream );
+ }
+
+ /**
+ * Compile templates, substituting from a collection of maps or objects
+ * into the given template.
+ * @param objs objs the collection of maps or objects
+ * @param templateStream the template as a stream
+ * @return the expanded rules as a string
+ */
+ public String compile(final Collection<?> objs,
+ final InputStream templateStream) {
+ TemplateContainer tc = new DefaultTemplateContainer( templateStream );
+ closeStream( templateStream );
+ return compile( new ObjectDataProvider( tc, objs ),
+ new TemplateDataListener( tc ) );
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/jdbc/ResultSetGenerator.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/jdbc/ResultSetGenerator.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/jdbc/ResultSetGenerator.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,153 @@
+package org.drools.template.jdbc;
+
+import org.drools.template.parser.TemplateContainer;
+import org.drools.template.parser.DefaultTemplateContainer;
+import org.drools.template.parser.TemplateDataListener;
+import org.drools.template.parser.DataListener;
+
+import java.io.InputStream;
+import java.util.List;
+import java.util.ArrayList;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+
+/**
+ * <p> A Drools template compiler which takes a ResultSet and compiles it into
+ * a template using DefaultTemplateContainer.</p>
+ *
+ * To use simply you need a JDBC ResultSet - with the field names mapping to the field names used in the template !
+ *
+ * @author <a href="mailto:javatestcase at yahoo.com">Bill Tarr</a>
+ */
+public class ResultSetGenerator {
+
+/**
+ * Generates DRL from a data provider for the spreadsheet data and templates.
+ *
+ * @param rs the resultset for the table data
+ * @param template the string containing the template resource name
+ * @return the generated DRL text as a String
+ */
+public String compile(final ResultSet rs,
+ final String template) {
+ final InputStream templateStream = this.getClass().getResourceAsStream(template);
+ return compile(rs,
+ templateStream);
+}
+
+/**
+ * Generates DRL from a data provider for the spreadsheet data and templates.
+ *
+ * @param rs the resultset for the table data
+ * @param templateStream the InputStream for reading the templates
+ * @return the generated DRL text as a String
+ */
+public String compile(final ResultSet rs,
+ final InputStream templateStream) {
+ TemplateContainer tc = new DefaultTemplateContainer(templateStream);
+ closeStream(templateStream);
+ return compile(rs,
+ new TemplateDataListener(tc));
+}
+
+/**
+ * Generates DRL from a data provider for the spreadsheet data and templates.
+ *
+ * @param rs the resultset for the table data
+ * @param listener a template data listener
+ * @return the generated DRL text as a String
+ */
+public String compile(final ResultSet rs,
+ final TemplateDataListener listener) {
+ List<DataListener> listeners = new ArrayList<DataListener>();
+ listeners.add(listener);
+ processData(rs,
+ listeners);
+ return listener.renderDRL();
+}
+
+/**
+ * Iterate through the resultset.
+ * @param rs the resultset for the table data
+ * @param listeners list of template data listener
+ */
+private void processData(final ResultSet rs,
+ List<DataListener> listeners) {
+
+ try {
+ ResultSetMetaData rsmd = rs.getMetaData();
+ int colCount = rsmd.getColumnCount();
+
+ int i = 0;
+
+ while (rs.next()) {
+ newRow(listeners, i, colCount);
+ for (int cellNum = 1; cellNum < colCount + 1; cellNum++) {
+ String cell;
+
+ int sqlType = rsmd.getColumnType(cellNum);
+ switch (sqlType) {
+ case java.sql.Types.DATE:
+ cell = rs.getDate(cellNum).toString();
+ break;
+ case java.sql.Types.INTEGER:
+ case java.sql.Types.DOUBLE:
+ cell = String.valueOf(rs.getInt(cellNum));
+ break;
+ default:
+ cell = rs.getString(cellNum);
+ }
+
+ newCell(listeners,
+ i,
+ cellNum -1,
+ cell,
+ DataListener.NON_MERGED);
+ }
+ i++;
+ }
+
+ } catch (SQLException e) {
+ //TODO: you need to throw or handle
+ }
+
+ finishData(listeners);
+}
+
+private void finishData(List<DataListener> listeners) {
+ for (DataListener listener : listeners) {
+ listener.finishSheet();
+ }
+}
+
+private void newRow(List<DataListener> listeners,
+ int row,
+ int cols) {
+ for (DataListener listener : listeners) {
+ listener.newRow(row,
+ cols);
+ }
+}
+
+public void newCell(List<DataListener> listeners,
+ int row,
+ int column,
+ String value,
+ int mergedColStart) {
+ for (DataListener listener : listeners) {
+ listener.newCell(row,
+ column,
+ value,
+ mergedColStart);
+ }
+}
+
+protected void closeStream(final InputStream stream) {
+ try {
+ stream.close();
+ } catch (final Exception e) {
+ System.err.print("WARNING: Wasn't able to correctly close stream for rule template. " + e.getMessage());
+ }
+}
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/AttributedDRLElement.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,103 @@
+/*
+ * Copyright 2011 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+
+/**
+ * Intermediary class, extending DRLElement with the capability of
+ * storing attributes, as required for rules and the package itself.
+ *
+ * @author Wolfgang Laun
+ */
+public abstract class AttributedDRLElement extends DRLElement {
+
+ private Map<String,String> _attr2value = new HashMap<String,String>();
+
+ protected AttributedDRLElement(){
+ }
+
+ protected AttributedDRLElement( final Integer salience ){
+ if( salience != null ){
+ this._attr2value.put( "salience", Integer.toString( salience ) );
+ }
+ }
+
+ protected void renderDRL(final DRLOutput out) {
+ for( Map.Entry<String, String> entry: _attr2value.entrySet() ){
+ String attribute = entry.getKey();
+ String value = entry.getValue();
+ out.writeLine( "\t" + attribute + " " + value );
+ }
+ }
+
+ protected String asStringLiteral( String value ){
+ // Keep the quotes if they come in the right places.
+ if( value.startsWith( "\"" ) && value.endsWith( "\"" ) && value.length() >= 2 ){
+ value = value.substring( 1, value.length() - 1 );
+ }
+ return '"' + value.replaceAll( "\"", Matcher.quoteReplacement( "\\\"" ) ) + '"';
+ }
+
+ public void setSalience( final Integer value ){
+ this._attr2value.put( "salience", Integer.toString( value ) );
+ }
+
+ public void setSalience( final String value ){
+ this._attr2value.put( "salience", value );
+ }
+
+ public void setDuration(final Long value) {
+ this._attr2value.put( "duration", Long.toString( value ) );
+ }
+
+ public void setActivationGroup(final String value) {
+ this._attr2value.put( "activation-group", asStringLiteral( value ) );
+ }
+
+ public void setRuleFlowGroup(final String value) {
+ this._attr2value.put( "ruleflow-group", asStringLiteral( value ) );
+ }
+
+ public void setAgendaGroup( final String value) {
+ this._attr2value.put( "agenda-group", asStringLiteral( value ) );
+ }
+
+ public void setNoLoop(final boolean value) {
+ this._attr2value.put( "no-loop", Boolean.toString( value ) );
+ }
+
+ public void setLockOnActive(final boolean value) {
+ this._attr2value.put( "lock-on-active", Boolean.toString( value ) );
+ }
+
+ public void setAutoFocus(final boolean value) {
+ this._attr2value.put( "auto-focus", Boolean.toString( value ) );
+ }
+
+ public String getAttribute( String name ){
+ return this._attr2value.get( name ).toString();
+ }
+
+ public String getSalience(){
+ return this._attr2value.get( "salience" );
+ }
+
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Condition.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Condition.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Condition.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+/**
+ * This class represents a single LHS item (which will be the same as a line in
+ * traditional DRL).
+ * @author <a href="mailto:michael.neale at gmail.com"> Michael Neale </a>
+ */
+public class Condition extends DRLElement
+ implements
+ DRLJavaEmitter {
+
+ public String _snippet;
+
+ /**
+ * @param snippet
+ * The snippet to set.
+ */
+ public void setSnippet(final String snippet) {
+ this._snippet = snippet;
+ }
+
+ public String getSnippet() {
+ return this._snippet;
+ }
+
+ public void renderDRL(final DRLOutput out) {
+ out.writeLine( "\t\t" + this._snippet );
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Consequence.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Consequence.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Consequence.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+/**
+ * This represents a RHS fragement. A rule may have many of these, or just one.
+ * They are all mushed together.
+ *
+ * @author <a href="mailto:michael.neale at gmail.com"> Michael Neale </a>
+ */
+public class Consequence extends DRLElement
+ implements
+ DRLJavaEmitter {
+
+ private String _snippet;
+
+ /**
+ * @param _snippet
+ * The _snippet to set.
+ */
+ public void setSnippet(final String snippet) {
+ this._snippet = snippet;
+ }
+
+ public String getSnippet() {
+ return this._snippet;
+ }
+
+ public void renderDRL(final DRLOutput out) {
+ out.writeLine( "\t\t" + this._snippet );
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/DRLElement.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/DRLElement.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/DRLElement.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+/**
+ * @author <a href="mailto:michael.neale at gmail.com"> Michael Neale </a>
+ *
+ * The LayerSupertype for this model/parse tree.
+ */
+public abstract class DRLElement {
+
+ private String _comment;
+
+ public void setComment(final String comment) {
+ this._comment = comment;
+ }
+
+ String getComment() {
+ return this._comment;
+ }
+
+ boolean isCommented() {
+ return (this._comment != null && !("".equals( this._comment )));
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/DRLJavaEmitter.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/DRLJavaEmitter.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/DRLJavaEmitter.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+/**
+ * @author <a href="mailto:michael.neale at gmail.com"> Michael Neale </a>
+ *
+ * Classes that implement this interface should generate DRL fragments according
+ * to the drools java semantic module.
+ *
+ */
+public interface DRLJavaEmitter {
+
+ /** Each node can add its contribution to the output */
+ void renderDRL(DRLOutput out);
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/DRLOutput.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/DRLOutput.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/DRLOutput.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+import java.io.StringWriter;
+
+/**
+ * This contains the DRL output that each piece of the parser spreadsheet will contribute to
+ *
+ * @author Michael Neale
+ *
+ */
+public class DRLOutput {
+
+ private StringWriter writer;
+
+ public void writeLine(final String line) {
+ final StringBuffer buf = this.writer.getBuffer();
+ buf.append( line );
+ buf.append( '\n' );
+ }
+
+ public DRLOutput() {
+ this.writer = new StringWriter();
+ }
+
+ /** Return the rendered DRL so far */
+ public String getDRL() {
+ return this.writer.toString();
+ }
+
+ public String toString() {
+ return getDRL();
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Functions.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Functions.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Functions.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+/**
+ * Wrapper for functions. Functions must be written in the appropriate style, no
+ * formatting is contributed here.
+ *
+ * @author Michael Neale
+ */
+public class Functions
+ implements
+ DRLJavaEmitter {
+
+ private String functionsListing;
+
+ public void setFunctionsListing(final String functionsListing) {
+ this.functionsListing = functionsListing;
+ }
+
+ public void renderDRL(final DRLOutput out) {
+ if ( this.functionsListing != null ) {
+ out.writeLine( this.functionsListing );
+ }
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Global.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Global.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Global.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+/**
+ * @author <a href="mailto:ricardo.rojas at bluesoft.cl"> Ricardo Rojas </a>
+ *
+ * Represents an application-data tag (nominally at the rule-set level). The idea of this can
+ * be extended to other ruleset level settings.
+ */
+public class Global extends DRLElement
+ implements
+ DRLJavaEmitter {
+
+ private String identifier;
+ private String className;
+
+ /**
+ * @return Returns the className.
+ */
+ public String getClassName() {
+ return this.className;
+ }
+
+ /**
+ * @return Returns the varName.
+ */
+ public String getIdentifier() {
+ return this.identifier;
+ }
+
+ /**
+ * @param className
+ * The className to set.
+ */
+ public void setClassName(final String clazz) {
+ this.className = clazz;
+ }
+
+ /**
+ * @param varName
+ * The varName to set.
+ */
+ public void setIdentifier(final String namez) {
+ this.identifier = namez;
+ }
+
+ public void renderDRL(final DRLOutput out) {
+ out.writeLine( "global " + this.className + " " + this.identifier + ";" );
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Import.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Import.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Import.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+/**
+ * @author <a href="mailto:michael.neale at gmail.com"> Michael Neale </a>
+ *
+ * Represents an import (nominally at the rule-set level). The idea of this can
+ * be extended to other ruleset level settings.
+ */
+public class Import extends DRLElement
+ implements
+ DRLJavaEmitter {
+
+ private String className;
+
+ /**
+ * @return Returns the className.
+ */
+ public String getClassName() {
+ return this.className;
+ }
+
+ /**
+ * @param className
+ * The className to set.
+ */
+ public void setClassName(final String clazz) {
+ this.className = clazz;
+ }
+
+ public void renderDRL(final DRLOutput out) {
+ out.writeLine( "import " + this.className + ";" );
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Package.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Package.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Package.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * @author <a href="mailto:michael.neale at gmail.com"> Michael Neale </a>
+ *
+ * This is the top of the parse tree. Represents a package of rules once it has
+ * been parsed from the spreadsheet. Also is the launching point for dumping out
+ * the DRL.
+ */
+public class Package extends AttributedDRLElement
+ implements
+ DRLJavaEmitter {
+
+ private String _name;
+
+ private List<Import> _imports;
+
+ private List<Global> _variables; // List of the application data Variable Objects
+
+ private List<Rule> _rules;
+
+ private Functions _functions;
+
+ private Queries _queries;
+
+ public Package(final String name) {
+ this._name = name;
+ this._imports = new LinkedList<Import>();
+ this._variables = new LinkedList<Global>();
+ this._rules = new LinkedList<Rule>();
+ this._functions = new Functions();
+ this._queries = new Queries();
+ }
+
+ public void addImport(final Import imp) {
+ this._imports.add( imp );
+ }
+
+ public void addVariable(final Global varz) {
+ this._variables.add( varz );
+ }
+
+ public void addRule(final Rule rule) {
+ this._rules.add( rule );
+ }
+
+ public void addFunctions(final String listing) {
+ this._functions.setFunctionsListing( listing );
+ }
+ public void addQueries(final String listing) {
+ this._queries.setQueriesListing( listing );
+ }
+
+ public String getName() {
+ return this._name;
+ }
+
+ public List<Import> getImports() {
+ return this._imports;
+ }
+
+ public List<Global> getVariables() {
+ return this._variables;
+ }
+
+ public List<Rule> getRules() {
+ return this._rules;
+ }
+
+ public void renderDRL(final DRLOutput out) {
+ if (_name != null) {
+ out.writeLine( "package " + this._name.replace( ' ',
+ '_' ) + ";" );
+ }
+ out.writeLine( "#generated from Decision Table" );
+ renderDRL( this._imports,
+ out );
+ renderDRL( this._variables,
+ out );
+ this._functions.renderDRL( out );
+ this._queries.renderDRL(out);
+
+ // attributes
+ super.renderDRL( out );
+
+ renderDRL( this._rules,
+ out );
+
+ }
+
+ private void renderDRL(final List<? extends DRLJavaEmitter> list,
+ final DRLOutput out) {
+ for ( DRLJavaEmitter emitter : list ) {
+ emitter.renderDRL( out );
+ }
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Queries.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Queries.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Queries.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+/**
+ * Wrapper for queries. Queries must be written in the appropriate style, no
+ * formatting is contributed here.
+ *
+ * @author salaboy
+ */
+public class Queries
+ implements
+ DRLJavaEmitter {
+
+ private String queriesListing;
+
+ public void setQueriesListing(final String queriesListing) {
+ this.queriesListing = queriesListing;
+ }
+
+ public void renderDRL(final DRLOutput out) {
+ if ( this.queriesListing != null ) {
+ out.writeLine( this.queriesListing );
+ }
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Rule.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Rule.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/Rule.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,151 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * @author <a href="mailto:michael.neale at gmail.com"> Michael Neale </a>
+ *
+ * Represents a rule.
+ */
+public class Rule extends AttributedDRLElement
+ implements DRLJavaEmitter {
+
+ private static final int MAX_ROWS = 65535;
+
+ private String _name;
+ private String _description;
+
+ private List<String> _metadata;
+ private List<Condition> _lhs;
+ private List<Consequence> _rhs;
+ private int _spreadsheetRow;
+
+ /**
+ * Create a new rule. Note that the rule name should be post-fixed with the row number,
+ * as one way of providing tracability for errors back to the originating spreadsheet.
+ * @param name The name of the rule. This may be used to calculate DRL row error
+ * to Spreadsheet row error (just need to keep track of output lines, and map spreadsheetRow to a start
+ * and end range in the rendered output).
+ * @param salience
+ * @param spreadsheetRow The phyical row number from the spreadsheet.
+ */
+ public Rule(final String name,
+ final Integer salience,
+ final int spreadsheetRow) {
+ super( salience );
+ this._name = asStringLiteral( name );
+ this._description = null;
+ this._metadata = new LinkedList<String>();
+ this._lhs = new LinkedList<Condition>();
+ this._rhs = new LinkedList<Consequence>();
+ this._spreadsheetRow = spreadsheetRow;
+ }
+
+ public void addMetadata(final String meta) {
+ this._metadata.add( meta );
+ }
+
+ public void addCondition(final Condition con) {
+ this._lhs.add( con );
+ }
+
+ public void addConsequence(final Consequence con) {
+ this._rhs.add( con );
+ }
+
+ public void renderDRL(final DRLOutput out) {
+ if ( isCommented() ) {
+ out.writeLine( "#" + getComment() );
+ }
+ out.writeLine( "rule " + this._name );
+ if ( this._description != null ) {
+ out.writeLine( "\t# " + this._description );
+ }
+
+ // metadata
+ for(String ms: this._metadata ){
+ out.writeLine( "\t@" + ms );
+ }
+
+ // attributes
+ super.renderDRL( out );
+
+ out.writeLine( "\twhen" );
+ renderDRL( this._lhs, out );
+ out.writeLine( "\tthen" );
+ renderDRL( this._rhs, out );
+ out.writeLine( "end\n" );
+ }
+
+ private void renderDRL(final List<? extends DRLJavaEmitter> list,
+ final DRLOutput out) {
+ for ( DRLJavaEmitter item : list ) {
+ item.renderDRL( out );
+ }
+ }
+
+ public static int calcSalience(final int rowNumber) {
+ if ( rowNumber > Rule.MAX_ROWS ) {
+ throw new IllegalArgumentException( "That row number is above the max: " + Rule.MAX_ROWS );
+ }
+ return Rule.MAX_ROWS - rowNumber;
+ }
+
+ public List<String> getMetadata() {
+ return this._metadata;
+ }
+
+ public List<Condition> getConditions() {
+ return this._lhs;
+ }
+
+ public List<Consequence> getConsequences() {
+ return this._rhs;
+ }
+
+ public void setName(final String value){
+ this._name = asStringLiteral( value );
+ }
+
+ public String getName() {
+ return this._name;
+ }
+
+
+ public void setDescription(final String value){
+ this._description = value;
+ }
+
+ public void appendDescription(final String value){
+ this._description += value;
+ }
+
+
+ /**
+ * @return The row in the spreadsheet this represents.
+ * This can be handy when mapping a line error from Parser back to the rule row.
+ * Will need to have a map of ranges of line numbers that each rule covers.
+ * Then can find out the rule that cause it, and this will give the row number to report.
+ */
+ public int getSpreadsheetRowNumber() {
+ return this._spreadsheetRow;
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/SnippetBuilder.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/SnippetBuilder.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/model/SnippetBuilder.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * @author <a href="mailto:michael.neale at gmail.com"> Michael Neale </a>
+ *
+ * This utility class exists to convert rule script snippets to actual code. The
+ * snippets contain place holders for values to be substituted into. See the
+ * test case for how it really works !
+ *
+ * Snippet template example: "something.getBlah($param)" $param is the "place
+ * holder". This will get replaced with the "cellValue" that is passed in.
+ *
+ * 12-Oct-2005 change: moved from regex to using simple character based interpolation.
+ * Regex was overkill and couldn't not quite get it right.
+ */
+public class SnippetBuilder {
+
+ public enum SnippetType {
+ SINGLE, PARAM, INDEXED, FORALL
+ };
+
+ public static final String PARAM_PREFIX = "$";
+ public static final String PARAM_SUFFIX = "param";
+ public static final String PARAM_STRING = PARAM_PREFIX + PARAM_SUFFIX;
+ public static final String PARAM_FORALL_STRING = "forall";
+ public static final Pattern PARAM_FORALL_PATTERN = Pattern
+ .compile(PARAM_FORALL_STRING + "\\(([^{}]*)\\)\\{([^{}]+)\\}");
+
+ private final String _template;
+
+ private final SnippetType type;
+
+ private final Pattern delimiter;
+
+ /**
+ * @param snippetTemplate
+ * The snippet including the "place holder" for a parameter. If
+ * no "place holder" is present,
+ */
+ public SnippetBuilder(final String snippetTemplate) {
+ if ( snippetTemplate == null ) {
+ throw new RuntimeException( "Script template is null - check for missing script definition." );
+ }
+ this._template = snippetTemplate;
+ this.type = getType(_template);
+ this.delimiter = Pattern.compile( "(.*?[^\\\\])(,|\\z)" );
+ }
+
+ public static SnippetType getType(String template) {
+ Matcher forallMatcher = PARAM_FORALL_PATTERN.matcher(template);
+ if (forallMatcher.find())
+ return SnippetType.FORALL;
+ else if (template.indexOf(PARAM_PREFIX + "1") != -1)
+ return SnippetType.INDEXED;
+ else if (template.indexOf(PARAM_STRING) != -1)
+ return SnippetType.PARAM;
+ return SnippetType.SINGLE;
+ }
+
+ /**
+ * @param cellValue
+ * The value from the cell to populate the snippet with. If no
+ * place holder exists, will just return the snippet.
+ * @return The final snippet.
+ */
+ public String build(final String cellValue) {
+ switch (type) {
+ case FORALL:
+ return buildForAll(cellValue);
+ case INDEXED:
+ return buildMulti(cellValue);
+ default:
+ return buildSingle(cellValue);
+ }
+ }
+
+ private String buildForAll(final String cellValue) {
+ final String[] cellVals = split(cellValue);
+ Map<String, String> replacements = new HashMap<String, String>();
+ Matcher forallMatcher = PARAM_FORALL_PATTERN.matcher(_template);
+ while (forallMatcher.find()) {
+ replacements.put(forallMatcher.group(), "");
+ for (int paramNumber = 0; paramNumber < cellVals.length; paramNumber++) {
+ replacements.put(forallMatcher.group(), replacements
+ .get(forallMatcher.group())
+ + (paramNumber == 0 ? "" : " " + forallMatcher.group(1)
+ + " ")
+ + replace(forallMatcher.group(2), PARAM_PREFIX,
+ cellVals[paramNumber].trim(), 256));
+ }
+ }
+ String result = _template;
+ for (String key : replacements.keySet())
+ result = replace(result, key, replacements.get(key), 256);
+ return result.equals("") ? _template : result;
+ }
+
+ private String buildMulti(final String cellValue) {
+ final String[] cellVals = split( cellValue );
+ String result = this._template;
+
+ for ( int paramNumber = 0; paramNumber < cellVals.length; paramNumber++ ) {
+ final String replace = PARAM_PREFIX + (paramNumber + 1);
+ result = replace( result,
+ replace,
+ cellVals[paramNumber].trim(),
+ 256 );
+
+ }
+ return result;
+ }
+
+ private String[] split( String input ) {
+ Matcher m = delimiter.matcher( input );
+ List<String> result = new ArrayList<String>();
+ while( m.find() ) {
+ result.add( m.group( 1 ).replaceAll( "\\\\,", "," ) );
+ }
+ return result.toArray( new String[result.size()] );
+
+ }
+
+ /**
+ * @param cellValue
+ * @return
+ */
+ private String buildSingle(final String cellValue) {
+
+ return replace( this._template,
+ PARAM_STRING,
+ cellValue,
+ 256 );
+
+ }
+
+ /**
+ * Simple replacer.
+ * jakarta commons provided the inspiration for this.
+ */
+ private String replace(final String text,
+ final String repl,
+ final String with,
+ int max) {
+ if ( text == null || repl == null || repl.equals( "" ) || with == null || max == 0 ) {
+ return text;
+ }
+
+ final StringBuffer buf = new StringBuffer( text.length() );
+ int start = 0, end = 0;
+ while ( (end = text.indexOf( repl,
+ start )) != -1 ) {
+ buf.append( text.substring( start,
+ end ) ).append( with );
+ start = end + repl.length();
+
+ if ( --max == 0 ) {
+ break;
+ }
+ }
+ buf.append( text.substring( start ) );
+ return buf.toString();
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/objects/ArrayDataProvider.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/objects/ArrayDataProvider.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/objects/ArrayDataProvider.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,29 @@
+package org.drools.template.objects;
+
+import org.drools.template.DataProvider;
+
+public class ArrayDataProvider implements DataProvider {
+
+ private String[][] rows;
+ private int currRow;
+ private int rowsCount;
+
+ public ArrayDataProvider(String[][] rows) {
+ if (rows == null) {
+ this.rows = new String[0][0];
+ } else {
+ this.rows = rows;
+ }
+ this.currRow = 0;
+ this.rowsCount = this.rows.length;
+ }
+
+ public boolean hasNext() {
+ return currRow < rowsCount;
+ }
+
+ public String[] next() {
+ return rows[currRow++];
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/objects/ObjectDataProvider.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/objects/ObjectDataProvider.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/objects/ObjectDataProvider.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,117 @@
+package org.drools.template.objects;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.drools.template.DataProvider;
+import org.drools.template.parser.Column;
+import org.drools.template.parser.TemplateContainer;
+
+/**
+ * An object of this class acts as a DataProvider for rule templates.
+ * It may be created with a collection of maps or objects. The template's
+ * column names are used as keys or Bean-stype accessors to obtain the
+ * actual parameters for the substitution.
+ *
+ * @author Wolfgang Laun
+ */
+public class ObjectDataProvider implements DataProvider {
+
+ private Column[] columns;
+ private Iterator<?> iter;
+
+ /**
+ * Constructor from a template container
+ * @param tcont a template container
+ * @param objs a collection of maps or objects
+ */
+ public ObjectDataProvider( TemplateContainer tcont, Collection<?> objs ) {
+ columns = tcont.getColumns();
+ iter = objs.iterator();
+ }
+
+
+ public boolean hasNext() {
+ return iter.hasNext();
+ }
+
+ private Method getMethod( Class<?> clazz, String field ){
+ String Field = Character.toUpperCase( field.charAt( 0 ) ) + field.substring( 1 );
+ String getter = "get" + Field;
+ try {
+ return clazz.getMethod( getter );
+ } catch (SecurityException e) {
+ return null;
+ } catch (NoSuchMethodException e) {
+ }
+ getter = "is" + Field;
+ try {
+ return clazz.getMethod( getter );
+ } catch (SecurityException e) {
+ return null;
+ } catch (NoSuchMethodException e) {
+ }
+ getter = field;
+ try {
+ return clazz.getMethod( getter );
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ private Field getField( Class<?> clazz, String field ){
+ try {
+ return clazz.getField( field );
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ private String[] nextFromMap( Object obj ) {
+ @SuppressWarnings( "unchecked" )
+ Map<String,Object> map = (Map)obj;
+ String[] values = new String[columns.length];
+ for( int iCol = 0; iCol < columns.length; iCol++ ){
+ Object target = map.get( columns[iCol].getName() );
+ values[iCol] = target == null ? null : target.toString();
+ }
+ return values;
+ }
+
+ private String[] nextFromObject( Object obj ) {
+ Class<?> clazz = obj.getClass();
+ String[] values = new String[columns.length];
+ for( int iCol = 0; iCol < columns.length; iCol++ ){
+ String fieldName = columns[iCol].getName();
+ Object val = null;
+ try {
+ Method method = getMethod( clazz, fieldName );
+ if( method != null ){
+ val = method.invoke( obj );
+ } else {
+ Field field = getField( clazz, fieldName );
+ if( field != null ){
+ val = field.get( obj );
+ }
+ }
+ } catch (Exception e) {
+ // leave it null
+ }
+ values[iCol] = val == null ? null : val.toString();
+ }
+ return values;
+ }
+
+ public String[] next() {
+ Object obj = iter.next();
+ if( obj instanceof Map ){
+ return nextFromMap( obj );
+ } else {
+ return nextFromObject( obj );
+ }
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/AbstractColumn.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/AbstractColumn.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/AbstractColumn.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+import org.drools.core.util.StringUtils;
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * Base column of in a decision table
+ */
+public abstract class AbstractColumn implements Column {
+ private String name;
+
+ public AbstractColumn(String n) {
+ this.name = n;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getCondition(String condition, int index) {
+ StringBuffer conditionString = new StringBuffer(getCellType());
+ conditionString.append("(row == r, column == $param");
+ if (index != -1) {
+ conditionString.append(", index == ").append(index);
+ }
+ if (!StringUtils.isEmpty(condition)) {
+ conditionString.append(", value ").append(condition);
+ }
+ conditionString.append(")");
+ return conditionString.toString();
+ }
+
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/ArrayCell.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/ArrayCell.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/ArrayCell.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * Cell containing an array of values
+ */
+package org.drools.template.parser;
+
+import java.util.Map;
+
+import org.drools.StatefulSession;
+import org.drools.core.util.StringUtils;
+
+public class ArrayCell implements Cell {
+ Row row;
+
+ String value;
+
+ ArrayColumn column;
+
+ private String[] values;
+
+ public ArrayCell(final Row r, final ArrayColumn c) {
+ row = r;
+ column = c;
+ }
+
+ public void addValue(Map<String, Object> vars) {
+ for (int i = 0; i < values.length; i++) {
+ vars.put(column.getName() + i, values[i]);
+ }
+ }
+
+ public Column getColumn() {
+ return column;
+ }
+
+ public Row getRow() {
+ return row;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void insert(StatefulSession session) {
+ session.insert(this);
+ for (int i = 0; i < values.length; i++) {
+ Cell cell = column.getType().createCell(row);
+ cell.setValue(values[i]);
+ cell.setIndex(i);
+ cell.insert(session);
+ }
+ }
+
+ public void setIndex(int i) {
+ throw new RuntimeException("You cannot call setIndex on an ArrayCell");
+ }
+
+ public int getIndex() {
+ return -1;
+ }
+
+ public void setValue(String v) {
+ value = v;
+ values = StringUtils.splitPreserveAllTokens(value, ",");
+ }
+
+ public boolean isEmpty() {
+ return StringUtils.isEmpty(value);
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/ArrayColumn.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/ArrayColumn.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/ArrayColumn.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+import org.drools.core.util.StringUtils;
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * A column in a decision table that represents an array (comma-delimited)
+ * of values.
+ */
+public class ArrayColumn extends AbstractColumn {
+
+ private Column type;
+
+ public ArrayColumn(String n, Column typeColumn) {
+ super(n);
+ this.type = typeColumn;
+ }
+
+ public Cell createCell(Row row) {
+ return new ArrayCell(row, this);
+ }
+
+ public String getCellType() {
+ return type.getCellType();
+ }
+
+ public Column getType() {
+ return type;
+ }
+
+ public String getCondition(String condition, int index) {
+ if (index == -1) {
+ StringBuffer conditionString = new StringBuffer("ArrayCell(row == r, column == $param");
+ if (!StringUtils.isEmpty(condition)) {
+ conditionString.append(", value ").append(condition);
+ }
+ conditionString.append(")");
+ return conditionString.toString();
+ }
+ else
+ {
+ return type.getCondition(condition, index);
+ }
+
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/BooleanCell.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/BooleanCell.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/BooleanCell.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+import java.util.Map;
+
+import org.drools.StatefulSession;
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * A cell in a decision table containing a long value
+ */
+public class BooleanCell implements Cell {
+ Row row;
+
+ Boolean value;
+
+ Column column;
+
+ private int index;
+
+ public BooleanCell() {
+
+ }
+ BooleanCell(Row r, Column c) {
+ row = r;
+ column = c;
+ }
+
+ public String toString() {
+ return "Cell[" + column + ": " + value + "]";
+ }
+
+ public Row getRow() {
+ return row;
+ }
+
+ public Column getColumn() {
+ return column;
+ }
+
+ public Boolean getValue() {
+ return value;
+ }
+
+ public void addValue(Map<String, Object> vars) {
+ vars.put(column.getName(), value);
+ }
+ public void insert(StatefulSession session) {
+ session.insert(this);
+ }
+ public void setIndex(int i) {
+ index = i;
+ }
+ public int getIndex() {
+ return index;
+ }
+ public void setValue(String v) {
+ value = new Boolean(v);
+ }
+ public boolean isEmpty() {
+ return value == null;
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/BooleanColumn.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/BooleanColumn.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/BooleanColumn.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * A column of type Long in a decision table
+ */
+public class BooleanColumn extends AbstractColumn {
+
+ public BooleanColumn(String n) {
+ super(n);
+ }
+//
+// public void addValue(Map vars, Object value) {
+// vars.put(getName(), value);
+// }
+
+ public Cell createCell(Row row) {
+ return new BooleanCell(row, this);
+ }
+
+ public String getCellType() {
+ return "BooleanCell";
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Cell.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Cell.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Cell.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+import java.util.Map;
+
+import org.drools.StatefulSession;
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * A cell in a decision table
+ */
+public interface Cell {
+ public Row getRow();
+
+ public Column getColumn();
+
+ public void setValue(String value);
+
+ public void addValue(Map<String, Object> vars);
+
+ public void insert(StatefulSession session);
+
+ public void setIndex(int i);
+
+ public int getIndex();
+
+ public boolean isEmpty();
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Column.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Column.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Column.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * A column in a decision table
+ */
+public interface Column {
+ String getName();
+
+ Cell createCell(Row row);
+
+ String getCellType();
+
+ String getCondition(String condition, int index);
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/ColumnFactory.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/ColumnFactory.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/ColumnFactory.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * Factory to produce a column of the correct type based on its declaration.
+ * [] indicates a column that represents an array (comma-delimited) of values.
+ */
+public class ColumnFactory {
+ private final static Pattern PATTERN = Pattern.compile( "([a-zA-Z0-9_]*)(\\[\\])?(:\\s*([a-zA-Z]*)(\\[\\])?)?" );
+
+ public Column getColumn(String value) {
+ Matcher m = PATTERN.matcher( value );
+ if ( !m.matches() ) throw new IllegalArgumentException( "value " + value + " is not a valid column definition" );
+ String name = m.group( 1 );
+ String type = m.group( 4 );
+ type = type == null ? "String" : type;
+ boolean array = (m.group( 2 ) != null) || (m.group( 5 ) != null);
+ if ( array ) {
+ return new ArrayColumn( name,
+ createColumn( name,
+ type ) );
+ }
+ return createColumn( name,
+ type );
+ }
+
+ @SuppressWarnings("unchecked")
+ private Column createColumn(String name,
+ String type) {
+ try {
+ Class<Column> klass = (Class<Column>) Class.forName( this.getClass().getPackage().getName() + "." + type + "Column" );
+ Constructor<Column> constructor = klass.getConstructor( new Class[]{String.class} );
+ return constructor.newInstance( new Object[]{name} );
+ } catch ( SecurityException e ) {
+ e.printStackTrace();
+ throw new RuntimeException( e );
+ } catch ( NoSuchMethodException e ) {
+ e.printStackTrace();
+ throw new RuntimeException( e );
+ } catch ( ClassNotFoundException e ) {
+ e.printStackTrace();
+ throw new RuntimeException( e );
+ } catch ( IllegalArgumentException e ) {
+ e.printStackTrace();
+ throw new RuntimeException( e );
+ } catch ( InstantiationException e ) {
+ e.printStackTrace();
+ throw new RuntimeException( e );
+ } catch ( IllegalAccessException e ) {
+ e.printStackTrace();
+ throw new RuntimeException( e );
+ } catch ( InvocationTargetException e ) {
+ e.printStackTrace();
+ throw new RuntimeException( e );
+ }
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DataListener.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DataListener.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DataListener.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+/**
+ * @author <a href="mailto:shaun.addison at gmail.com"> Shaun Addison </a>
+ *
+ * Callback interface for scanning an spreadsheet.
+ */
+public interface DataListener {
+
+ public static final int NON_MERGED = -1;
+
+ /**
+ * Start a new sheet
+ *
+ * @param name
+ * the sheet name
+ */
+ public void startSheet(String name);
+
+ /**
+ * Come to the end of the sheet.
+ */
+ public void finishSheet();
+
+ /**
+ * Enter a new row.
+ *
+ *
+ * @param rowNumber
+ *
+ * @param columns
+ *
+ */
+ public void newRow(int rowNumber,
+ int columns);
+
+ /**
+ * Enter a new cell.
+ * Do NOT call this event for trailling cells at the end of the line.
+ * It will just confuse the parser. If all the trailing cells are empty, just
+ * stop raising events.
+ *
+ *
+ * @param row
+ * the row number
+ * @param column
+ * the column alpha character label
+ * @param value
+ * the string value of the cell
+ * @param mergedCol
+ * the "source" column if it is merged. -1 otherwise.
+ */
+ public void newCell(int row,
+ int column,
+ String value,
+ int mergedColStart);
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DecisionTableParseException.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DecisionTableParseException.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DecisionTableParseException.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+public class DecisionTableParseException extends RuntimeException {
+
+ private static final long serialVersionUID = 510l;
+
+ public DecisionTableParseException(final String message) {
+ super( message );
+ }
+
+ public DecisionTableParseException(final String message,
+ final Throwable cause) {
+ super( message,
+ cause );
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultGenerator.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultGenerator.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultGenerator.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,103 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.mvel2.templates.CompiledTemplate;
+import org.mvel2.templates.SimpleTemplateRegistry;
+import org.mvel2.templates.TemplateCompiler;
+import org.mvel2.templates.TemplateRegistry;
+import org.mvel2.templates.TemplateRuntime;
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * Generate the rules for a decision table row from a rule template.
+ */
+public class DefaultGenerator
+ implements
+ Generator {
+
+ private Map<String, RuleTemplate> ruleTemplates;
+
+ private TemplateRegistry registry = new SimpleTemplateRegistry();
+
+ private List<String> rules = new ArrayList<String>();
+
+ public DefaultGenerator(final Map<String, RuleTemplate> t) {
+ ruleTemplates = t;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.drools.decisiontable.parser.Generator#generate(java.lang.String,
+ * org.drools.decisiontable.parser.Row)
+ */
+ public void generate(String templateName,
+ Row row) {
+ try {
+ CompiledTemplate template = getTemplate( templateName );
+ Map<String, Object> vars = new HashMap<String, Object>();
+ vars.put( "row",
+ row );
+
+ for ( Cell cell : row.getCells() ) {
+ cell.addValue( vars );
+ }
+
+ String drl = String.valueOf( TemplateRuntime.execute( template,
+ vars,
+ registry ) );
+
+ rules.add( drl );
+ } catch ( Exception e ) {
+ throw new RuntimeException( e );
+ }
+ }
+
+ private CompiledTemplate getTemplate(String templateName) throws IOException {
+ CompiledTemplate contents;
+ if ( !registry.contains( templateName ) ) {
+ RuleTemplate template = ruleTemplates.get( templateName );
+ contents = TemplateCompiler.compileTemplate( template.getContents() );
+ registry.addNamedTemplate( templateName,
+ contents );
+ } else {
+ contents = registry.getNamedTemplate( templateName );
+ }
+ return contents;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.drools.decisiontable.parser.Generator#getDrl()
+ */
+ public String getDrl() {
+ StringBuffer sb = new StringBuffer();
+ for ( String rule : rules ) {
+ sb.append( rule ).append( "\n" );
+ }
+ return sb.toString();
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultTemplateColumn.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultTemplateColumn.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultTemplateColumn.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.drools.core.util.StringUtils;
+import org.drools.template.model.Condition;
+import org.drools.template.model.Rule;
+import org.drools.template.model.SnippetBuilder;
+
+/**
+ *
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * The default column condition for a rule template to be generated. If the
+ * conditon starts with "!" then the template will only be generated if the
+ * column condition does not exist. If there is no condition string then the
+ * template will be generated only if the column contains a value. The condition
+ * can be any valid rule condition.
+ */
+class DefaultTemplateColumn implements TemplateColumn {
+ private static final Pattern COLUMN_PATTERN = Pattern
+ .compile("^(!?)([a-zA-Z0-9_]*)(\\[([0-9]+)\\])?\\s*(.*)");
+
+ private boolean notCondition;
+
+ private String columnName;
+
+ private String condition;
+
+ private TemplateContainer templateContainer;
+
+ private int index = -1;
+
+ DefaultTemplateColumn(TemplateContainer tc, String columnString) {
+ templateContainer = tc;
+ Matcher matcher = COLUMN_PATTERN.matcher(columnString);
+ if (!matcher.matches())
+ throw new IllegalArgumentException("column " + columnString
+ + " is not valid");
+ notCondition = !StringUtils.isEmpty(matcher.group(1));
+ columnName = matcher.group(2);
+ String indexString = matcher.group(4);
+ condition = matcher.group(5);
+ if (!StringUtils.isEmpty(indexString)) {
+ index = Integer.parseInt(indexString);
+ }
+ }
+
+ private void createCellCondition(final Rule rule) {
+ StringBuffer conditionString = new StringBuffer();
+ Column column = templateContainer.getColumn(columnName);
+ column.getCondition(condition, index);
+
+ if (notCondition) {
+ conditionString.append("not ");
+ }
+ conditionString.append("exists ");
+ conditionString.append(column.getCondition(condition, index));
+ SnippetBuilder snip = new SnippetBuilder(conditionString.toString());
+ Condition condition = new Condition();
+ condition.setSnippet(snip.build(columnName));
+ rule.addCondition(condition);
+ }
+
+ private void createColumnCondition(final Rule rule, final String value) {
+ SnippetBuilder colSnip = new SnippetBuilder(
+ "$param : Column(name == \"$param\")");
+ Condition colCondition = new Condition();
+ colCondition.setSnippet(colSnip.build(value));
+ rule.addCondition(colCondition);
+ }
+
+ public void addCondition(Rule rule) {
+ createColumnCondition(rule, columnName);
+ createCellCondition(rule);
+ }
+
+ public String getName() {
+ return columnName;
+ }
+
+ public boolean isNotCondition() {
+ return notCondition;
+ }
+
+ public String getCondition() {
+ return condition;
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultTemplateContainer.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultTemplateContainer.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultTemplateContainer.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,176 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ *
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * Container for a set of templates (residing in one file). This class will
+ * parse the template file.
+ *
+ */
+public class DefaultTemplateContainer implements TemplateContainer {
+ private String header;
+
+ private Map<String, Column> columnMap = new HashMap<String, Column>();
+
+ private List<Column> columns = new ArrayList<Column>();
+
+ private Map<String, RuleTemplate> templates = new HashMap<String, RuleTemplate>();
+
+ public DefaultTemplateContainer(final String template) {
+ this(DefaultTemplateContainer.class.getResourceAsStream(template));
+ }
+
+ public DefaultTemplateContainer(final InputStream templateStream) {
+ parseTemplate(templateStream);
+ validateTemplate();
+ }
+
+ private void validateTemplate() {
+ if (columns.size() == 0) {
+ throw new DecisionTableParseException("Missing header columns");
+ }
+ if (templates.size() == 0) {
+ throw new DecisionTableParseException("Missing templates");
+ }
+
+ }
+
+ private void parseTemplate(final InputStream templateStream) {
+ try {
+ final ColumnFactory cf = new ColumnFactory();
+ final BufferedReader templateReader = new BufferedReader(
+ new InputStreamReader(templateStream));
+ String line = null;
+ StringBuffer header = new StringBuffer();
+ boolean inTemplate = false;
+ boolean inHeader = false;
+ boolean inContents = false;
+ RuleTemplate template = null;
+ StringBuffer contents = new StringBuffer();
+ while ((line = templateReader.readLine()) != null) {
+ if (line.trim().length() > 0) {
+ if (line.startsWith("template header")) {
+ inHeader = true;
+ } else if (line.startsWith("template")) {
+ inTemplate = true;
+ String quotedName = line.substring(8).trim();
+ quotedName = quotedName.substring(1, quotedName
+ .length() - 1);
+ template = new RuleTemplate(quotedName, this);
+ addTemplate(template);
+
+ } else if (line.startsWith("package")) {
+ if (inHeader == false) {
+ throw new DecisionTableParseException(
+ "Missing header");
+ }
+ inHeader = false;
+ header.append(line).append("\n");
+ } else if (inHeader) {
+ addColumn(cf.getColumn(line.trim()));
+ } else if (!inTemplate && !inHeader) {
+ header.append(line).append("\n");
+ } else if (!inContents && line.startsWith("rule")) {
+ inContents = true;
+ contents.append(line).append("\n");
+ } else if (line.equals("end template")) {
+ template.setContents(contents.toString());
+ contents.setLength(0);
+ inTemplate = false;
+ inContents = false;
+ } else if (inContents) {
+ contents.append(line).append("\n");
+ } else if (inTemplate) {
+ template.addColumn(line.trim());
+ }
+ }
+
+ }
+ if (inTemplate) {
+ throw new DecisionTableParseException("Missing end template");
+ }
+ this.header = header.toString();
+
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ } finally {
+ if (templateStream != null)
+ closeStream(templateStream);
+ }
+ }
+
+ private void addTemplate(RuleTemplate template) {
+ templates.put(template.getName(), template);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.drools.decisiontable.parser.TemplateContainer#getTemplates()
+ */
+ public Map<String, RuleTemplate> getTemplates() {
+ return templates;
+ }
+
+ private void addColumn(Column c) {
+ columns.add(c);
+ columnMap.put(c.getName(), c);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.drools.decisiontable.parser.TemplateContainer#getColumns()
+ */
+ public Column[] getColumns() {
+ return (Column[]) columns.toArray(new Column[columns.size()]);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.drools.decisiontable.parser.TemplateContainer#getHeader()
+ */
+ public String getHeader() {
+ return header;
+ }
+
+ private void closeStream(final InputStream stream) {
+ try {
+ stream.close();
+ } catch (final Exception e) {
+ System.err.print("WARNING: Wasn't able to "
+ + "correctly close stream for decision table. "
+ + e.getMessage());
+ }
+ }
+
+ public Column getColumn(final String name) {
+ return (Column) columnMap.get(name);
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultTemplateRuleBase.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultTemplateRuleBase.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/DefaultTemplateRuleBase.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,154 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.drools.RuleBase;
+import org.drools.RuleBaseFactory;
+import org.drools.StatefulSession;
+import org.drools.compiler.PackageBuilder;
+import org.drools.rule.Package;
+import org.drools.template.model.Condition;
+import org.drools.template.model.Consequence;
+import org.drools.template.model.DRLOutput;
+import org.drools.template.model.Global;
+import org.drools.template.model.Import;
+import org.drools.template.model.Rule;
+
+/**
+ *
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * Create a rule base for the set of rule templates in the
+ * TemplateContainer. These rules are used internally by the
+ * engine to generate the actual decision table rules based on
+ * which columns have been filled in.
+ *
+ * Basically, if a rule template requires columns A and B then
+ * the template rule base will generate a rule with columns A and B
+ * as the LHS and a RHS which triggers the rule to be generated.
+ * ie.
+ * rule "template1"
+ * when
+ * r : Row()
+ * column1 : Column(name == "column1")
+ * Cell(row == r, column == column1)
+ * column2 : Column(name == "column2")
+ * Cell(row == r, column == column2, value == "xyz")
+ * then
+ * generator.generate( "template1", r);
+ * end
+ *
+ */
+public class DefaultTemplateRuleBase implements TemplateRuleBase {
+ private RuleBase ruleBase;
+
+ public DefaultTemplateRuleBase(final TemplateContainer tc) {
+ ruleBase = readRule(getDTRules(tc.getTemplates()));
+ }
+
+ /* (non-Javadoc)
+ * @see org.drools.decisiontable.parser.TemplateRuleBase#newWorkingMemory()
+ */
+ public StatefulSession newStatefulSession() {
+ return ruleBase.newStatefulSession();
+ }
+ /**
+ *
+ * @param templates
+ * @return
+ */
+ private String getDTRules(Map<String, RuleTemplate> templates) {
+ org.drools.template.model.Package p = new org.drools.template.model.Package(
+ DefaultTemplateRuleBase.class.getPackage().getName());
+ addImports(p);
+ addGlobals(p);
+ int i = 1;
+ for ( RuleTemplate template : templates.values() ) {
+ createTemplateRule(p, i++, template);
+ }
+ DRLOutput out = new DRLOutput();
+ p.renderDRL(out);
+ return out.getDRL();
+
+ }
+
+ private void createTemplateRule(org.drools.template.model.Package p, int index, RuleTemplate template) {
+ Rule rule = new Rule(template.getName(), null, index);
+ Condition condition = new Condition();
+ condition.setSnippet("r : Row()");
+ rule.addCondition(condition);
+ createColumnConditions(template, rule);
+ rule.addConsequence(createConsequence(template));
+ p.addRule(rule);
+ }
+
+ private void createColumnConditions(RuleTemplate template, Rule rule) {
+ for ( TemplateColumn column : template.getColumns() ) {
+ column.addCondition(rule);
+ }
+ }
+
+
+ private void addGlobals(org.drools.template.model.Package p) {
+ Global global = new Global();
+ global.setClassName(DefaultGenerator.class.getName());
+ global.setIdentifier("generator");
+ p.addVariable(global);
+ }
+
+ private void addImports(org.drools.template.model.Package p) {
+ Import drlImport1 = new Import();
+ drlImport1.setClassName(Map.class.getName());
+ Import drlImport2 = new Import();
+ drlImport2.setClassName(HashMap.class.getName());
+ p.addImport(drlImport1);
+ p.addImport(drlImport2);
+ }
+
+ private Consequence createConsequence(RuleTemplate template) {
+ StringBuffer action = new StringBuffer();
+ action.append("generator.generate( \"");
+ action.append(template.getName()).append("\", r);");
+ final Consequence consequence = new Consequence();
+ consequence.setSnippet(action.toString());
+ return consequence;
+ }
+
+ private RuleBase readRule(String drl) {
+ try {
+// System.out.println(drl);
+ // read in the source
+ Reader source = new StringReader(drl);
+ PackageBuilder builder = new PackageBuilder();
+ builder.addPackageFromDrl(source);
+ Package pkg = builder.getPackage();
+
+ // add the package to a rulebase (deploy the rule package).
+ RuleBase ruleBase = RuleBaseFactory.newRuleBase();
+ ruleBase.addPackage(pkg);
+ return ruleBase;
+
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Generator.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Generator.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Generator.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+/**
+ * <a href="stevearoonie at gmail.com">Steven Williams</a>
+ * Generate the rules for a decision table
+ */
+public interface Generator {
+
+ void generate(String templateName, Row row);
+
+ String getDrl();
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/LongCell.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/LongCell.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/LongCell.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+import java.util.Map;
+
+import org.drools.StatefulSession;
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * A cell in a decision table containing a long value
+ */
+public class LongCell implements Cell {
+ Row row;
+
+ Long value;
+
+ Column column;
+
+ private int index;
+
+ public LongCell() {
+
+ }
+ LongCell(Row r, Column c) {
+ row = r;
+ column = c;
+ }
+
+ public String toString() {
+ return "Cell[" + column + ": " + value + "]";
+ }
+
+ public Row getRow() {
+ return row;
+ }
+
+ public Column getColumn() {
+ return column;
+ }
+
+ public Long getValue() {
+ return value;
+ }
+
+ public void addValue(Map<String, Object> vars) {
+ vars.put(column.getName(), value);
+ }
+ public void insert(StatefulSession session) {
+ session.insert(this);
+ }
+ public void setIndex(int i) {
+ index = i;
+ }
+ public int getIndex() {
+ return index;
+ }
+ public void setValue(String v) {
+ value = new Long(v);
+ }
+ public boolean isEmpty() {
+ return value == null;
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/LongColumn.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/LongColumn.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/LongColumn.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * A column of type Long in a decision table
+ */
+public class LongColumn extends AbstractColumn {
+
+ public LongColumn(String n) {
+ super(n);
+ }
+//
+// public void addValue(Map vars, Object value) {
+// vars.put(getName(), value);
+// }
+
+ public Cell createCell(Row row) {
+ return new LongCell(row, this);
+ }
+
+ public String getCellType() {
+ return "LongCell";
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Row.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Row.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/Row.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+import java.util.ArrayList;
+import java.util.List;
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * Represents a row in a decision table.
+ */
+public class Row {
+ int rowNum;
+ List<Cell> cells = new ArrayList<Cell>();
+
+ public Row() {
+
+ }
+
+ Row(int r, Column[] columns) {
+ rowNum = r;
+ for (int i = 0; i < columns.length; i++) {
+ cells.add(columns[i].createCell(this));
+ }
+ }
+
+ public int getRowNumber() {
+ return rowNum;
+ }
+
+ Cell getCell(int columnIndex)
+ {
+ return cells.get(columnIndex);
+ }
+
+ boolean isEmpty() {
+ for ( Cell cell : cells ) {
+ if (!cell.isEmpty())
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public List<Cell> getCells() {
+ return cells;
+ }
+
+ public String toString() {
+ return "Row " + rowNum + cells + "\n";
+ }
+
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/RuleTemplate.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/RuleTemplate.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/RuleTemplate.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,123 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.drools.core.util.StringUtils;
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * A rule template made up of a name, the decision table columns required, the
+ * decision table columns that must be empty and the contents of the rule.
+ */
+public class RuleTemplate {
+ private String name;
+
+ private String contents;
+
+ private List<TemplateColumn> columns;
+
+ private TemplateContainer templateContainer;
+
+ public RuleTemplate(final String n, final TemplateContainer tc) {
+ name = n;
+ columns = new ArrayList<TemplateColumn>();
+ templateContainer = tc;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public List<TemplateColumn> getColumns() {
+ return columns;
+ }
+
+ public String getContents() {
+ return contents;
+ }
+
+ public void addColumn(String columnString) {
+ TemplateColumn column = new DefaultTemplateColumn(templateContainer, columnString);
+ this.columns.add(column);
+ }
+
+ public void setContents(String contents) {
+ this.contents = replaceOptionals(contents);
+ }
+
+ /**
+ * @see java.lang.Object#toString()
+ */
+ public String toString() {
+ return "RuleTemplate[name," + this.name + "contents," + this.columns
+ + "columns";
+ }
+
+ /*
+ * Replace the optional columns in the rule contents with an if statement.
+ * if (column is empty) do not show the line.
+ */
+ private String replaceOptionals(String contents) {
+ try {
+ final Pattern pattern = Pattern.compile("@\\{(.[^}]*)\\}");
+ final Collection<String> columns = getColumnNames();
+ columns.add("row.rowNumber");
+ final BufferedReader reader = new BufferedReader(new StringReader(
+ contents));
+ String line = null;
+ final StringBuffer newLine = new StringBuffer();
+ while ((line = reader.readLine()) != null) {
+ final Matcher matcher = pattern.matcher(line);
+ int optCols = 0;
+ while (matcher.find()) {
+ final String c = matcher.group(1);
+ if (!columns.contains(c)) {
+ newLine.append("@if{").append(matcher.group(1)).append(
+ " != null}");
+ optCols++;
+ }
+ }
+ newLine.append(line);
+ newLine.append(StringUtils.repeat("@end{}", optCols));
+ newLine.append("\n");
+ }
+// System.out.println("newLine: " + newLine);
+ return newLine.toString();
+
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private Collection<String> getColumnNames() {
+ Collection<String> columnNames = new ArrayList<String>();
+ for ( TemplateColumn column : getColumns() ) {
+ columnNames.add(column.getName());
+ }
+ return columnNames;
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/StringCell.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/StringCell.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/StringCell.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+import java.util.Map;
+
+import org.drools.StatefulSession;
+import org.drools.core.util.StringUtils;
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * A cell in a decision table containing a String value
+ */
+public class StringCell implements Cell {
+ Row row;
+
+ String value;
+
+ Column column;
+
+ private int index;
+
+ public StringCell() {
+
+ }
+ StringCell(Row r, Column c) {
+ row = r;
+ column = c;
+ }
+
+ public String toString() {
+ return "Cell[" + column + ": " + value + "]";
+ }
+
+ public Row getRow() {
+ return row;
+ }
+
+ public Column getColumn() {
+ return column;
+ }
+
+ public Object getValue() {
+ return value;
+ }
+
+ public void addValue(Map<String, Object> vars) {
+ vars.put(column.getName(), value);
+ }
+ public int getIndex() {
+ return index;
+ }
+ public void insert(StatefulSession session) {
+ session.insert(this);
+ }
+ public void setIndex(int i) {
+ index = i;
+ }
+ public void setValue(String v) {
+ value = v;
+ }
+ public boolean isEmpty() {
+ return StringUtils.isEmpty(value);
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/StringColumn.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/StringColumn.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/StringColumn.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+/**
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * A column of type String in a decision table
+ */
+public class StringColumn extends AbstractColumn {
+
+ public StringColumn(String n) {
+ super(n);
+ }
+//
+// public void addValue(Map vars, Object value) {
+// vars.put(getName(), value);
+// }
+
+ public Cell createCell(Row row) {
+ return new StringCell(row, this);
+ }
+
+ public String getCellType() {
+ return "StringCell";
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateColumn.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateColumn.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateColumn.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+import org.drools.template.model.Rule;
+/**
+ *
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ *
+ * A column condition for a rule template to be generated.
+ */
+interface TemplateColumn {
+ void addCondition(final Rule rule);
+
+ String getName();
+
+ boolean isNotCondition();
+
+ String getCondition();
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateContainer.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateContainer.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateContainer.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+import java.util.Map;
+
+public interface TemplateContainer {
+
+ Map<String, RuleTemplate> getTemplates();
+
+ Column[] getColumns();
+
+ Column getColumn(String name);
+
+ String getHeader();
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateDataListener.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateDataListener.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateDataListener.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,168 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+
+import java.io.InputStream;
+
+import org.drools.StatefulSession;
+import org.drools.template.model.DRLOutput;
+
+/**
+ * SheetListener for creating rules from a template
+ *
+ * @author <a href="mailto:stevearoonie at gmail.com">Steven Williams</a>
+ */
+public class TemplateDataListener
+ implements
+ DataListener {
+
+ private int startRow = -1;
+
+ private boolean tableFinished = false;
+
+ private Row currentRow;
+
+ private Column[] columns;
+
+ private StatefulSession session;
+
+ private TemplateContainer templateContainer;
+
+ private int startCol;
+
+ private Generator generator;
+
+ // private WorkingMemoryFileLogger logger;
+
+ public TemplateDataListener(final TemplateContainer tc) {
+ this( 1,
+ 1,
+ tc );
+ }
+
+ public TemplateDataListener(final int startRow,
+ final int startCol,
+ final String template) {
+ this( startRow,
+ startCol,
+ new DefaultTemplateContainer( template ) );
+ }
+
+ public TemplateDataListener(final int startRow,
+ final int startCol,
+ final InputStream templateStream) {
+ this( startRow,
+ startCol,
+ new DefaultTemplateContainer( templateStream ) );
+ }
+
+ public TemplateDataListener(final int startRow,
+ final int startCol,
+ final TemplateContainer tc) {
+ this( startRow,
+ startCol,
+ tc,
+ new DefaultTemplateRuleBase( tc ) );
+ }
+
+ public TemplateDataListener(final int startRow,
+ final int startCol,
+ final TemplateContainer tc,
+ final TemplateRuleBase rb) {
+ this( startRow,
+ startCol,
+ tc,
+ rb,
+ new DefaultGenerator( tc.getTemplates() ) );
+ }
+
+ public TemplateDataListener(final int startRow,
+ final int startCol,
+ final TemplateContainer tc,
+ final TemplateRuleBase ruleBase,
+ final Generator generator) {
+ this.startRow = startRow - 1;
+ this.startCol = startCol - 1;
+ columns = tc.getColumns();
+ this.templateContainer = tc;
+ session = ruleBase.newStatefulSession();
+ // logger = new WorkingMemoryFileLogger(session);
+ // logger.setFileName("log/event");
+ this.generator = generator;
+ session.setGlobal( "generator",
+ generator );
+ assertColumns();
+ }
+
+ private void assertColumns() {
+ for ( int i = 0; i < columns.length; i++ ) {
+ session.insert( columns[i] );
+ }
+ }
+
+ public void finishSheet() {
+ if ( currentRow != null ) {
+ session.insert( currentRow );
+ }
+ session.fireAllRules();
+ // logger.writeToDisk();
+ session.dispose();
+ }
+
+ public void newCell(int row,
+ int column,
+ String value,
+ int mergedColStart) {
+ if ( currentRow != null && column >= startCol && value != null && value.trim().length() > 0 ) {
+
+ int columnIndex = column - startCol;
+ if ( columnIndex < columns.length ) {
+ Cell cell = currentRow.getCell( columnIndex );
+ cell.setValue( value );
+ cell.insert( session );
+ }
+ }
+ }
+
+ public void newRow(int rowNumber,
+ int columnCount) {
+ if ( !tableFinished && rowNumber >= startRow ) {
+ if ( currentRow != null && currentRow.isEmpty() ) {
+ currentRow = null;
+ tableFinished = true;
+ } else {
+ if ( currentRow != null ) session.insert( currentRow );
+ currentRow = new Row( rowNumber,
+ columns );
+ }
+ }
+ }
+
+ public void startSheet(String name) {
+
+ }
+
+ public String renderDRL() {
+ DRLOutput out = new DRLOutput();
+ out.writeLine( templateContainer.getHeader() );
+
+ out.writeLine( generator.getDrl() );
+ // System.err.println(out.getDRL());
+ return out.getDRL();
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateRuleBase.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateRuleBase.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/java/org/drools/template/parser/TemplateRuleBase.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.parser;
+import org.drools.StatefulSession;
+
+public interface TemplateRuleBase {
+
+ StatefulSession newStatefulSession();
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/resources/org/drools/template/package.html
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/resources/org/drools/template/package.html (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/main/resources/org/drools/template/package.html 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,3 @@
+<body>
+ This is a utility for generating rules from templates. Use DataProviderCompiler.
+</body>
\ No newline at end of file
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/DataProviderCompilerIntegrationTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/DataProviderCompilerIntegrationTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/DataProviderCompilerIntegrationTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,217 @@
+package org.drools.template;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.drools.template.parser.Column;
+import org.drools.template.parser.DefaultTemplateContainer;
+import org.drools.template.parser.TemplateContainer;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class DataProviderCompilerIntegrationTest {
+
+ private static final StringBuffer EXPECTED_RULES = new StringBuffer();
+
+ static {
+ String head = "package org.drools.decisiontable;\n#generated from Decision Table\nglobal FeeResult result;\n\n";
+ String rule3_a = "rule \"Fee Schedule_3\"\n\tagenda-group \"STANDARD\"\n\twhen\n\t\tFeeEvent(productType == \"SBLC\",\n";
+ String rule3_b = "\t\t\tactivityType == \"ISS\",\n\t\t\tfeeType == \"Telex\",\n\n\n\t\t\tamount < 30000,\n\t\t\tccy == \"YEN\"\n\t\t)\n";
+ String rule3_then = "\tthen\n\t\tresult.setSchedule(new FeeSchedule(\"62\", \"STANDARD\", 45));\nend\n\n";
+
+ String rule2_a = "rule \"Fee Schedule_2\"\n\tagenda-group \"STANDARD\"\n\twhen\n\t\tFeeEvent(productType == \"SBLC\",\n";
+ String rule2_b = "\t\t\tactivityType == \"ISS\",\n\t\t\tfeeType == \"Postage\",\n\n\n\n\t\t\tccy == \"YEN\"\n\t\t)\n";
+ String rule2_then = "\tthen\n\t\tresult.setSchedule(new FeeSchedule(\"12\", \"STANDARD\", 40));\nend\n\n";
+
+ String rule1_a = "rule \"Fee Schedule_1\"\n\tagenda-group \"STANDARD\"\n\twhen\n\t\tFeeEvent(productType == \"SBLC\",\n";
+ String rule1_b = "\t\t\tactivityType == \"ISS\",\n\t\t\tfeeType == \"Commission\",\n\n\t\t\tentityBranch == \"Entity Branch 1\",\n\n\t\t\tccy == \"YEN\"\n\t\t)\n";
+ String rule1_then = "\tthen\n\t\tresult.setSchedule(new FeeSchedule(\"15\", \"STANDARD\", 1600));\nend\n\n";
+
+ String rule0_a = "rule \"Fee Schedule_0\"\n\tagenda-group \"STANDARD\"\n\twhen\n\t\tFeeEvent(productType == \"SBLC\",\n";
+ String rule0_b = "\t\t\tactivityType == \"ISS\",\n\t\t\tfeeType == \"Commission\",\n\t\t\ttxParty == \"Party 1\",\n\n\n\t\t\tccy == \"USD\"\n\t\t)\n";
+ String rule0_then = "\tthen\n\t\tresult.setSchedule(new FeeSchedule(\"1\", \"STANDARD\", 750));\nend\n\n\n";
+
+ EXPECTED_RULES.append( head );
+ EXPECTED_RULES.append( rule3_a ).append( rule3_b ).append( rule3_then );
+ EXPECTED_RULES.append( rule2_a ).append( rule2_b ).append( rule2_then );
+ EXPECTED_RULES.append( rule1_a ).append( rule1_b ).append( rule1_then );
+ EXPECTED_RULES.append( rule0_a ).append( rule0_b ).append( rule0_then );
+ }
+
+ private class TestDataProvider implements DataProvider {
+ private Iterator<String[]> iterator;
+
+ TestDataProvider(List<String[]> rows) {
+ this.iterator = rows.iterator();
+ }
+
+ public boolean hasNext() {
+ return iterator.hasNext();
+ }
+
+ public String[] next() {
+ return iterator.next();
+ }
+ }
+
+ private ArrayList<String[]> rows = new ArrayList<String[]>();
+
+ @Before
+ public void setUp(){
+ rows.add( new String[]{ "1",
+ "STANDARD",
+ "FLAT",
+ null,
+ "SBLC",
+ "ISS",
+ "Commission",
+ "Party 1",
+ "USD",
+ null,
+ "750",
+ "dummy"} );
+ rows.add( new String[]{ "15",
+ "STANDARD",
+ "FLAT",
+ "Entity Branch 1",
+ "SBLC",
+ "ISS",
+ "Commission",
+ null,
+ "YEN",
+ null,
+ "1600",
+ "dummy" } );
+ rows.add( new String[]{ "12",
+ "STANDARD",
+ "FLAT",
+ null,
+ "SBLC",
+ "ISS",
+ "Postage",
+ null,
+ "YEN",
+ null,
+ "40",
+ "dummy" } );
+ rows.add( new String[]{ "62",
+ "STANDARD",
+ "FLAT",
+ null,
+ "SBLC",
+ "ISS",
+ "Telex",
+ null,
+ "YEN",
+ "< 30000",
+ "45",
+ "dummy" } );
+ }
+
+ @Test
+ public void testCompiler() throws Exception {
+ TestDataProvider tdp = new TestDataProvider( rows );
+ final DataProviderCompiler converter = new DataProviderCompiler();
+ final String drl = converter.compile( tdp,
+ "/templates/rule_template_1.drl" );
+ System.out.println( drl );
+ assertEquals( EXPECTED_RULES.toString(), drl );
+ }
+
+ @Test
+ public void testCompilerMaps() throws Exception {
+ Collection<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
+ final ObjectDataCompiler converter = new ObjectDataCompiler();
+ InputStream templateStream =
+ this.getClass().getResourceAsStream( "/templates/rule_template_1.drl" );
+ TemplateContainer tc = new DefaultTemplateContainer( templateStream );
+ Column[] columns = tc.getColumns();
+
+ for( String[] row: rows ){
+ Map<String,Object> map = new HashMap<String,Object>();
+ for( int icol = 0; icol < columns.length; icol++ ){
+ Object value = row[icol];
+ if( value != null ){
+ map.put( columns[icol].getName(), value );
+ }
+ }
+ maps.add( map );
+ }
+ templateStream =
+ this.getClass().getResourceAsStream( "/templates/rule_template_1.drl" );
+ final String drl = converter.compile( maps, templateStream );
+ System.out.println( drl );
+ assertEquals( EXPECTED_RULES.toString(), drl );
+ }
+
+ public static class OBJ {
+ private final String FEE_SCHEDULE_ID;
+ private final String FEE_SCHEDULE_TYPE;
+ private final String FEE_MODE_TYPE;
+ private final String ENTITY_BRANCH;
+ private final String PRODUCT_TYPE;
+ private final String ACTIVITY_TYPE;
+ public final String FEE_TYPE;
+ public final String OWNING_PARTY;
+ public final String CCY;
+ public final String LC_AMOUNT;
+ public final String AMOUNT;
+ OBJ( String[] vals ){
+ FEE_SCHEDULE_ID = vals[0];
+ FEE_SCHEDULE_TYPE = vals[1];
+ FEE_MODE_TYPE = vals[2];
+ ENTITY_BRANCH = vals[3];
+ PRODUCT_TYPE = vals[4];
+ ACTIVITY_TYPE = vals[5];
+ FEE_TYPE = vals[6];
+ OWNING_PARTY = vals[7];
+ CCY = vals[8];
+ LC_AMOUNT = vals[9];
+ AMOUNT = vals[10];
+ }
+ public String getFEE_SCHEDULE_ID() {
+ return FEE_SCHEDULE_ID;
+ }
+ public String getFEE_SCHEDULE_TYPE() {
+ return FEE_SCHEDULE_TYPE;
+ }
+ public String getFEE_MODE_TYPE() {
+ return FEE_MODE_TYPE;
+ }
+ public String ENTITY_BRANCH() {
+ return ENTITY_BRANCH;
+ }
+ public String PRODUCT_TYPE() {
+ return PRODUCT_TYPE;
+ }
+ public String ACTIVITY_TYPE() {
+ return ACTIVITY_TYPE;
+ }
+ }
+
+ @Test
+ public void testCompilerObjs() throws Exception {
+ Collection<Object> objs = new ArrayList<Object>();
+ final ObjectDataCompiler converter = new ObjectDataCompiler();
+ final InputStream templateStream =
+ this.getClass().getResourceAsStream( "/templates/rule_template_1.drl" );
+
+ for( String[] row: rows ){
+ OBJ obj = new OBJ( row );
+ objs.add( obj );
+ }
+ final String drl = converter.compile( objs, templateStream );
+ System.out.println( drl );
+ assertEquals( EXPECTED_RULES.toString(), drl );
+ }
+
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/Cheese.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/Cheese.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/Cheese.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,32 @@
+package org.drools.template.jdbc;
+
+/**
+ * @author Michael Neale
+ */
+public class Cheese {
+ private String type;
+ private int price;
+
+ public Cheese() {
+
+ }
+ public Cheese(final String type,
+ final int price) {
+ super();
+ this.type = type;
+ this.price = price;
+ }
+
+ public int getPrice() {
+ return this.price;
+ }
+
+ public String getType() {
+ return this.type;
+ }
+
+ public void setPrice(final int price) {
+ this.price = price;
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/Person.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/Person.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/Person.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,93 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.jdbc;
+
+public class Person {
+ private String name;
+ private String likes;
+ private int age;
+
+ private char sex;
+
+ private boolean alive;
+
+ private String status;
+
+ public Person() {
+
+ }
+ public Person(final String name) {
+ this( name,
+ "",
+ 0 );
+ }
+
+ public Person(final String name,
+ final String likes) {
+ this( name,
+ likes,
+ 0 );
+ }
+
+ public Person(final String name,
+ final String likes,
+ final int age) {
+ this.name = name;
+ this.likes = likes;
+ this.age = age;
+ }
+
+ public String getStatus() {
+ return this.status;
+ }
+
+ public void setStatus(final String status) {
+ this.status = status;
+ }
+
+ public String getLikes() {
+ return this.likes;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public int getAge() {
+ return this.age;
+ }
+
+ public boolean isAlive() {
+ return this.alive;
+ }
+
+ public void setAlive(final boolean alive) {
+ this.alive = alive;
+ }
+
+ public char getSex() {
+ return this.sex;
+ }
+
+ public void setSex(final char sex) {
+ this.sex = sex;
+ }
+
+ public String toString() {
+ return "[Person name='" + this.name + "']";
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/ResultSetGeneratorTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/ResultSetGeneratorTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/jdbc/ResultSetGeneratorTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,131 @@
+package org.drools.template.jdbc;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+import org.drools.RuleBase;
+import org.drools.WorkingMemory;
+import org.drools.RuleBaseFactory;
+import org.drools.compiler.PackageBuilder;
+
+import java.sql.*;
+import java.io.InputStream;
+import java.io.StringReader;
+import java.util.List;
+import java.util.ArrayList;
+
+
+/**
+ * /**
+ * <p>A simple example of using the ResultSetGenerator.
+ * The template used is "Cheese.drt" the same used by SimpleRuleTemplateExample.
+ * Rather than use the spreadsheet ExampleCheese.xls, this example reads the data
+ * from an HSQL database (which is created in this example.)</p>
+ * @author Michael Neale
+ * @author Bill Tarr
+ */
+public class ResultSetGeneratorTest {
+
+
+
+ @Test
+ public void testResultSet() throws Exception {
+
+ // setup the HSQL database with our rules.
+ Class.forName("org.hsqldb.jdbcDriver");
+ Connection conn = DriverManager.getConnection("jdbc:hsqldb:RULES", "sa", "");
+
+ try {
+ update("CREATE TABLE cheese_rules ( id INTEGER IDENTITY, persons_age INTEGER, birth_date DATE, cheese_type VARCHAR(256), log VARCHAR(256) )", conn);
+
+ update("INSERT INTO cheese_rules(persons_age,birth_date,cheese_type,log) VALUES(42, '1950-01-01', 'stilton', 'Old man stilton')", conn);
+ update("INSERT INTO cheese_rules(persons_age,birth_date,cheese_type,log) VALUES(10, '2009-01-01', 'cheddar', 'Young man cheddar')", conn);
+ } catch (SQLException e) {
+ // catch exception for table already existing
+ }
+
+ // query the DB for the rule rows, convert them using the template.
+
+ Statement sta = conn.createStatement();
+ ResultSet rs = sta.executeQuery("SELECT persons_age, cheese_type, log " +
+ " FROM cheese_rules");
+
+ final ResultSetGenerator converter = new ResultSetGenerator();
+ final String drl1 = converter.compile(rs, getRulesStream());
+
+ System.out.println(drl1);
+
+ sta.close();
+
+ String drl = drl1;
+
+ // test that our rules can execute.
+ final RuleBase rb = buildRuleBase(drl);
+
+ WorkingMemory wm = rb.newStatefulSession();
+
+ //now create some test data
+ wm.insert(new Cheese("stilton",
+ 42));
+ wm.insert(new Person("michael",
+ "stilton",
+ 42));
+ final List<String> list = new ArrayList<String>();
+ wm.setGlobal("list",
+ list);
+
+ wm.fireAllRules();
+
+ assertEquals(1, list.size());
+
+ }
+
+ /**
+ * Build the rule base from the generated DRL.
+ * Same method from SimpleRuleTemplateExample.
+ *
+ * @param drls variable length of Drools rules as strings
+ * @return RuleBase built from the rules
+ * @throws Exception Add Exception handling to a real implementation.
+ */
+ private RuleBase buildRuleBase(String... drls) throws Exception {
+ //now we build the rule package and rulebase, as if they are normal rules
+ PackageBuilder builder = new PackageBuilder();
+ for (String drl : drls) {
+ builder.addPackageFromDrl(new StringReader(drl));
+ }
+
+ //add the package to a rulebase (deploy the rule package).
+ RuleBase ruleBase = RuleBaseFactory.newRuleBase();
+ ruleBase.addPackage(builder.getPackage());
+ return ruleBase;
+ }
+
+ /**
+ * simple getter method looks up our template as a Resource
+ *
+ * @return the template as an InputStream
+ */
+ private InputStream getRulesStream() {
+ return this.getClass().getResourceAsStream("/templates/Cheese.drt");
+ }
+
+ /**
+ * An HSQL update wrapper from http://hsqldb.org/doc/guide/apb.html
+ *
+ * @param expression SQL expression
+ * @throws SQLException just rethrowing all the errors for the example
+ */
+ private void update(String expression, Connection conn) throws SQLException {
+ Statement st;
+ st = conn.createStatement();
+ int i = st.executeUpdate(expression);
+ if (i == -1) {
+ System.out.println("db error : " + expression);
+ }
+
+ st.close();
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/FunctionsRenderTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/FunctionsRenderTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/FunctionsRenderTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class FunctionsRenderTest {
+
+ @Test
+ public void testFunctionRender() {
+ final Functions func = new Functions();
+
+ DRLOutput out = new DRLOutput();
+ func.renderDRL( out );
+
+ assertEquals( "",
+ out.toString() );
+
+ func.setFunctionsListing( "function myFunction() {}" );
+ out = new DRLOutput();
+ func.renderDRL( out );
+ final String s = out.toString();
+ assertEquals( "function myFunction() {}\n",
+ s );
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/PackageRenderTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/PackageRenderTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/PackageRenderTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ * @author <a href="mailto:michael.neale at gmail.com"> Michael Neale</a>
+ *
+ * Test rendering and running a whole sample ruleset, from the model classes
+ * down.
+ */
+public class PackageRenderTest {
+
+ public Rule buildRule() {
+ final Rule rule = new Rule( "myrule",
+ new Integer( 42 ),
+ 1 );
+ rule.setComment( "rule comments" );
+
+ final Condition cond = new Condition();
+ cond.setComment( "cond comment" );
+ cond.setSnippet( "cond snippet" );
+ rule.addCondition( cond );
+
+ final Consequence cons = new Consequence();
+ cons.setComment( "cons comment" );
+ cons.setSnippet( "cons snippet" );
+ rule.addConsequence( cons );
+
+ return rule;
+ }
+
+ @Test
+ public void testRulesetRender() {
+ final Package ruleSet = new Package( "my ruleset" );
+ ruleSet.addFunctions( "my functions" );
+ ruleSet.addRule( buildRule() );
+
+ final Rule rule = buildRule();
+ rule.setName( "other rule" );
+ ruleSet.addRule( rule );
+
+ final Import imp = new Import();
+ imp.setClassName( "clazz name" );
+ imp.setComment( "import comment" );
+ ruleSet.addImport( imp );
+
+ final DRLOutput out = new DRLOutput();
+ ruleSet.renderDRL( out );
+
+ final String drl = out.getDRL();
+ assertNotNull( drl );
+ System.out.println( drl );
+ assertTrue( drl.indexOf( "rule \"myrule\"" ) > -1 );
+ assertTrue( drl.indexOf( "salience 42" ) > -1 );
+ assertTrue( drl.indexOf( "#rule comments" ) > -1 );
+ assertTrue( drl.indexOf( "my functions" ) > -1 );
+ assertTrue( drl.indexOf( "package my_ruleset;" ) > -1 );
+ assertTrue( drl.indexOf( "rule \"other rule\"" ) > drl.indexOf( "rule \"myrule\"" ) );
+ }
+
+ @Test
+ public void testRulesetAttribute() {
+ final Package ruleSet = new Package( "my ruleset" );
+ ruleSet.setAgendaGroup( "agroup" );
+ ruleSet.setNoLoop( true );
+ ruleSet.setSalience( 100 );
+ final DRLOutput out = new DRLOutput();
+ ruleSet.renderDRL( out );
+
+ final String drl = out.getDRL();
+ assertTrue( drl.contains( "agenda-group \"agroup\"") );
+ assertTrue( drl.contains( "no-loop true") );
+ assertTrue( drl.contains( "salience 100" ) );
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/QueriesRenderTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/QueriesRenderTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/QueriesRenderTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/*
+ * @author: salaboy
+ */
+public class QueriesRenderTest {
+
+ @Test
+ public void testQueriesRender() {
+ final Queries queries = new Queries();
+
+ DRLOutput out = new DRLOutput();
+ queries.renderDRL( out );
+
+ assertEquals( "",
+ out.toString() );
+
+ queries.setQueriesListing( "query myQuery(String value) Person() end" );
+ out = new DRLOutput();
+ queries.renderDRL( out );
+ final String s = out.toString();
+ assertEquals( "query myQuery(String value) Person() end\n",
+ s );
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/RuleRenderTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/RuleRenderTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/RuleRenderTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,153 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+/**
+ * @author <a href="mailto:michael.neale at gmail.com"> Michael Neale</a>
+ *
+ * Tests how the rule parse tree renders itself to a rule XML fragment.
+ */
+public class RuleRenderTest {
+
+ @Test
+ public void testRuleRender() {
+ final Rule rule = new Rule( "myrule",
+ new Integer( 42 ),
+ 1 );
+ rule.setComment( "rule comments" );
+
+ final Condition cond = new Condition();
+ cond.setComment( "cond comment" );
+ cond.setSnippet( "cond snippet" );
+ rule.addCondition( cond );
+
+ final Consequence cons = new Consequence();
+ cons.setComment( "cons comment" );
+ cons.setSnippet( "cons snippet;" );
+ rule.addConsequence( cons );
+ rule.addConsequence( cons );
+
+ final DRLOutput out = new DRLOutput();
+ rule.renderDRL( out );
+ final String drl = out.getDRL();
+ assertNotNull( drl );
+
+ assertTrue( drl.indexOf( "cond snippet" ) != -1 );
+ assertTrue( drl.indexOf( "cons snippet" ) != -1 );
+ assertTrue( drl.indexOf( "salience 42" ) != -1 );
+ assertTrue( drl.indexOf( "salience 42" ) < drl.indexOf( "when" ) );
+ assertTrue( drl.indexOf( "cond snippet" ) < drl.indexOf( "then" ) );
+ assertTrue( drl.indexOf( "cons snippet;" ) > drl.indexOf( "then" ) );
+ assertTrue( drl.indexOf( "rule" ) != -1 );
+ assertTrue( drl.indexOf( "end" ) > drl.indexOf( "rule " ) );
+ assertTrue( drl.indexOf( "#rule comments" ) > -1 );
+
+ }
+
+ @Test
+ public void testAttributes() throws Exception {
+ Rule rule = new Rule( "la",
+ new Integer( 42 ),
+ 2 );
+
+ rule.setActivationGroup( "foo" );
+ rule.setNoLoop( true );
+ rule.setRuleFlowGroup( "ruleflowgroup" );
+ rule.setDuration( 42L );
+ DRLOutput out = new DRLOutput();
+ rule.renderDRL( out );
+
+ String result = out.toString();
+
+ assertTrue( result.indexOf( "ruleflow-group \"ruleflowgroup\"" ) > -1 );
+ assertTrue( result.indexOf( "no-loop true" ) > -1 );
+ assertTrue( result.indexOf( "activation-group \"foo\"" ) > -1 );
+ assertTrue( result.indexOf( "duration 42" ) > -1 );
+
+ }
+
+ @Test
+ public void testMetadata() throws Exception {
+ Rule rule = new Rule( "la", new Integer( 42 ), 2 );
+
+ rule.addMetadata( "Author( A. U. Thor )" );
+ rule.addMetadata( "Revision( 42 )" );
+ DRLOutput out = new DRLOutput();
+ rule.renderDRL( out );
+
+ String result = out.toString();
+ assertTrue( result.contains( "@Author( A. U. Thor )" ) );
+ assertTrue( result.contains( "@Revision( 42 )" ) );
+
+ }
+
+ @Test
+ public void testSalienceCalculator() {
+ final int rowNumber = 2;
+ final int salience = Rule.calcSalience( rowNumber );
+ assertEquals( 65533,
+ salience );
+ }
+
+ @Test
+ public void testNotEscapeChars() {
+ //bit of a legacy from the olde XML dayes of yesteryeare
+ final Condition cond = new Condition();
+ cond.setSnippet( "a < b" );
+ final DRLOutput out = new DRLOutput();
+ cond.renderDRL( out );
+
+ assertTrue( out.toString().indexOf( "a < b" ) != -1 );
+
+ }
+
+ /**
+ * This checks that if the rule has "nil" salience, then
+ * no salience value should be put in the rule definition.
+ * This allows default salience to work as advertised.
+ *
+ */
+ @Test
+ public void testNilSalience() {
+ Rule rule = new Rule( "MyRule",
+ null,
+ 1 );
+
+ DRLOutput out = new DRLOutput();
+ rule.renderDRL( out );
+ String xml = out.toString();
+ int idx = xml.indexOf( "salience" );
+ assertEquals( -1,
+ idx );
+
+ rule = new Rule( "MyRule",
+ new Integer( 42 ),
+ 1 );
+ out = new DRLOutput();
+ rule.renderDRL( out );
+ xml = out.toString();
+ idx = xml.indexOf( "salience" );
+ assertTrue( idx > -1 );
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/SnippetBuilderTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/SnippetBuilderTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/model/SnippetBuilderTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,167 @@
+/*
+ * Copyright 2005 JBoss Inc
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.drools.template.model;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ * @author <a href="mailto:michael.neale at gmail.com"> Michael Neale</a>
+ *
+ */
+public class SnippetBuilderTest {
+
+ @Test
+ public void testBuildSnippet() {
+ final String snippet = "something.param.getAnother().equals($param);";
+ final SnippetBuilder snip = new SnippetBuilder( snippet );
+ final String cellValue = "$42";
+ final String result = snip.build( cellValue );
+ assertNotNull( result );
+
+ assertEquals( "something.param.getAnother().equals($42);",
+ result );
+ }
+
+ @Test
+ public void testBuildSnippetNoPlaceHolder() {
+ final String snippet = "something.getAnother().equals(blah);";
+ final SnippetBuilder snip = new SnippetBuilder( snippet );
+ final String cellValue = "this is ignored...";
+ final String result = snip.build( cellValue );
+
+ assertEquals( snippet,
+ result );
+ }
+
+ @Test
+ public void testSingleParamMultipleTimes() {
+ final String snippet = "something.param.getAnother($param).equals($param);";
+ final SnippetBuilder snip = new SnippetBuilder( snippet );
+ final String cellValue = "42";
+ final String result = snip.build( cellValue );
+ assertNotNull( result );
+
+ assertEquals( "something.param.getAnother(42).equals(42);",
+ result );
+
+ }
+
+ @Test
+ public void testMultiPlaceHolder() {
+ final String snippet = "something.getAnother($1,$2).equals($2, '$2');";
+ final SnippetBuilder snip = new SnippetBuilder( snippet );
+ final String result = snip.build( "x, y" );
+ assertEquals( "something.getAnother(x,y).equals(y, 'y');",
+ result );
+
+ }
+
+ @Test
+ public void testMultiPlaceHolderSingle() {
+ final String snippet = "something.getAnother($1).equals($1);";
+ final SnippetBuilder snip = new SnippetBuilder( snippet );
+ final String result = snip.build( "x" );
+ assertEquals( "something.getAnother(x).equals(x);",
+ result );
+
+ }
+
+ @Test
+ public void testStartWithParam() {
+ final String snippet = "$1 goo $2";
+ final SnippetBuilder snip = new SnippetBuilder( snippet );
+ final String result = snip.build( "x, y" );
+ assertEquals( "x goo y",
+ result );
+
+ }
+
+ @Test
+ public void testMultiPlaceHolderEscapedComma() {
+ final String snippet = "rulesOutputRouting.set( $1, $2, $3, $4, $5 );";
+ final SnippetBuilder snip = new SnippetBuilder( snippet );
+ final String result = snip.build( "\"80\",\"Department Manager\",toa.getPersonExpense().getEntityCode(\"Part Of\"\\,\"Office\"),10004,30" );
+ assertEquals( "rulesOutputRouting.set( \"80\", \"Department Manager\", toa.getPersonExpense().getEntityCode(\"Part Of\",\"Office\"), 10004, 30 );",
+ result );
+
+ }
+
+ @Test
+ public void testForAllAnd() {
+ final String snippet = "forall(&&){something == $}";
+ final SnippetBuilder snip = new SnippetBuilder(snippet);
+ final String result = snip.build("x");
+ assertEquals("something == x", result);
+ }
+
+ @Test
+ public void testForAllAndCSV() {
+ final String snippet = "forall(&&){something == $}";
+ final SnippetBuilder snip = new SnippetBuilder(snippet);
+ final String result = snip.build("x, y");
+ assertEquals("something == x && something == y", result);
+ }
+
+ @Test
+ public void testForAllAndNone() {
+ final String snippet = "forall(&&){something == $}";
+ final SnippetBuilder snip = new SnippetBuilder(snippet);
+ final String result = snip.build("");
+ assertEquals("forall(&&){something == $}", result);
+ }
+
+ @Test
+ public void testForAllAndCSVMultiple() {
+ final String snippet = "forall(&&){something == $ || something == $}";
+ final SnippetBuilder snip = new SnippetBuilder(snippet);
+ final String result = snip.build("x, y");
+ assertEquals(
+ "something == x || something == x && something == y || something == y",
+ result);
+ }
+
+ @Test
+ public void testForAllOr() {
+ final String snippet = "forall(||){something == $}";
+ final SnippetBuilder snip = new SnippetBuilder(snippet);
+ final String result = snip.build("x");
+ assertEquals("something == x", result);
+ }
+
+ @Test
+ public void testForAllOrMultiple() {
+ final String snippet = "forall(||){something == $} && forall(||){something < $}";
+ final SnippetBuilder snip = new SnippetBuilder(snippet);
+ final String result = snip.build("x, y");
+ assertEquals(
+ "something == x || something == y && something < x || something < y",
+ result);
+ }
+
+ @Test
+ public void testForAllOrAndMultipleWithPrefix() {
+ final String snippet = "something == this && forall(||){something == $} && forall(&&){something < $}";
+ final SnippetBuilder snip = new SnippetBuilder(snippet);
+ final String result = snip.build("x, y");
+ assertEquals(
+ "something == this && something == x || something == y && something < x && something < y",
+ result);
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/ColumnFactoryTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/ColumnFactoryTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/ColumnFactoryTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,65 @@
+package org.drools.template.parser;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class ColumnFactoryTest {
+
+ @Test
+ public void testGetColumn() {
+ ColumnFactory f = new ColumnFactory();
+ Column column = f.getColumn("column");
+ assertTrue(column instanceof StringColumn);
+ assertEquals("column", column.getName());
+ }
+
+ @Test
+ public void testGetStringArrayColumn() {
+ ColumnFactory f = new ColumnFactory();
+ Column column = f.getColumn("column: String[]");
+ assertTrue(column instanceof ArrayColumn);
+ assertEquals("column", column.getName());
+ assertEquals("StringCell", ((ArrayColumn)column).getCellType());
+ }
+
+ @Test
+ public void testGetLongArrayColumn() {
+ ColumnFactory f = new ColumnFactory();
+ Column column = f.getColumn("column: Long[]");
+ assertTrue(column instanceof ArrayColumn);
+ assertEquals("column", column.getName());
+ assertEquals("LongCell", ((ArrayColumn)column).getCellType());
+ }
+
+ @Test
+ public void testGetArrayColumnSimple() {
+ ColumnFactory f = new ColumnFactory();
+ Column column = f.getColumn("column[]");
+ assertTrue(column instanceof ArrayColumn);
+ assertEquals("column", column.getName());
+ assertEquals("StringCell", ((ArrayColumn)column).getCellType());
+
+ }
+
+ @Test
+ public void testGetLongColumn() {
+ ColumnFactory f = new ColumnFactory();
+ Column column = f.getColumn("column: Long");
+ assertTrue(column instanceof LongColumn);
+ assertEquals("column", column.getName());
+ }
+
+ @Test
+ public void testInvalidGetColumn() {
+ try {
+ ColumnFactory f = new ColumnFactory();
+ f.getColumn("column$");
+ fail("IllegalArgumentException expected");
+ } catch (IllegalArgumentException expected) {
+
+ }
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/DefaultGeneratorTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/DefaultGeneratorTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/DefaultGeneratorTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,79 @@
+package org.drools.template.parser;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class DefaultGeneratorTest {
+ private DefaultGenerator g;
+
+ @Before
+ public void setUp() throws Exception {
+ Map<String, RuleTemplate> t = new HashMap<String, RuleTemplate>();
+ TemplateContainer tc = new TemplateContainer() {
+
+ public Column getColumn(String name) {
+ return null;
+ }
+
+ public Column[] getColumns() {
+ return null;
+ }
+
+ public String getHeader() {
+ return null;
+ }
+
+ public Map<String, RuleTemplate> getTemplates() {
+ return null;
+ }
+
+ };
+ RuleTemplate rt1 = new RuleTemplate("rt1", tc);
+ rt1.setContents("Test template 1");
+ RuleTemplate rt2 = new RuleTemplate("rt2", tc);
+ rt2.setContents("Test template 2");
+ RuleTemplate rt3 = new RuleTemplate("rt3", tc);
+ rt3.addColumn("col1");
+ rt3.addColumn("col2");
+ rt3.setContents("@{row.rowNumber} @{col1} @{col2}");
+ t.put("rt1", rt1);
+ t.put("rt2", rt2);
+ t.put("rt3", rt3);
+ g = new DefaultGenerator(t);
+ }
+
+ @Test
+ public void testSelectTemplate() {
+ g.generate("rt2", new Row());
+ String drl = g.getDrl();
+ assertEquals("Test template 2\n\n", drl);
+ }
+
+ @Test
+ public void testGenerate() {
+ g.generate("rt2", new Row());
+ g.generate("rt1", new Row());
+ String drl = g.getDrl();
+ assertEquals("Test template 2\n\nTest template 1\n\n", drl);
+ }
+
+ @Test
+ public void testAddColumns() {
+ Column[] columns = {new StringColumn("col1"), new StringColumn("col2")};
+ Row r = new Row(1, columns);
+ r.getCell(0).setValue("value1");
+ r.getCell(1).setValue("value2");
+// Row r = new Row(1);
+// r.addCell(new StringCell(r, new StringColumn("col1"), "value1"));
+// r.addCell(new StringCell(r, new StringColumn("col2"), "value2"));
+ g.generate("rt3", r);
+ String drl = g.getDrl();
+ assertEquals("1 value1 value2\n\n", drl);
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/DefaultTemplateContainerTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/DefaultTemplateContainerTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/DefaultTemplateContainerTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,168 @@
+package org.drools.template.parser;
+
+import java.io.InputStream;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class DefaultTemplateContainerTest {
+ @Test
+ public void testParseTemplate() {
+ InputStream is = DefaultTemplateContainerTest.class
+ .getResourceAsStream("/templates/test_template_simple.drl");
+ DefaultTemplateContainer t = new DefaultTemplateContainer(is);
+ assertEquals("package This_is_a_ruleset;\n", t.getHeader());
+ assertEquals(1, t.getColumns().length);
+ assertEquals("name", t.getColumns()[0].getName());
+ Map<String, RuleTemplate> templates = t.getTemplates();
+ assertEquals(1, templates.size());
+ RuleTemplate template = templates.get("template1");
+ assertNotNull(template);
+ List<TemplateColumn> columns = template.getColumns();
+ assertEquals(1, columns.size());
+ TemplateColumn column = (TemplateColumn) columns.get(0);
+ assertEquals("name", column.getName());
+ String contents = template.getContents();
+ assertTrue(contents
+ .startsWith("rule \"How cool is @{name} @{row.rowNumber}\""));
+ assertTrue(contents.endsWith("then\nend\n"));
+ }
+
+ @Test
+ public void testParseTemplateConditions() {
+ InputStream is = DefaultTemplateContainerTest.class
+ .getResourceAsStream("/templates/test_template_conditions.drl");
+ DefaultTemplateContainer t = new DefaultTemplateContainer(is);
+ assertEquals("package This_is_a_ruleset;\n", t.getHeader());
+ assertEquals(1, t.getColumns().length);
+ assertEquals("name", t.getColumns()[0].getName());
+ Map<String, RuleTemplate> templates = t.getTemplates();
+ assertEquals(1, templates.size());
+ RuleTemplate template = (RuleTemplate) templates.get("template1");
+ assertNotNull(template);
+ List<TemplateColumn> columns = template.getColumns();
+ assertEquals(1, columns.size());
+ TemplateColumn templateColumn = (TemplateColumn) columns.get(0);
+ assertEquals("name", templateColumn.getName());
+ assertEquals("== \"name1\"", templateColumn.getCondition());
+ String contents = template.getContents();
+ assertTrue(contents
+ .startsWith("rule \"How cool is @{name} @{row.rowNumber}\""));
+ assertTrue(contents.endsWith("then\nend\n"));
+ }
+
+ @Test
+ public void testParseTemplateNoHeader() {
+ try {
+ InputStream is = DefaultTemplateContainerTest.class
+ .getResourceAsStream("/templates/test_template_invalid1.drl");
+ new DefaultTemplateContainer(is);
+ fail("DecisionTableParseException expected");
+ } catch (DecisionTableParseException expected) {
+ assertEquals("Missing header", expected.getMessage());
+ }
+ }
+
+ @Test
+ public void testParseTemplateNoHeaderColumns() {
+ try {
+ InputStream is = DefaultTemplateContainerTest.class
+ .getResourceAsStream("/templates/test_template_invalid2.drl");
+ new DefaultTemplateContainer(is);
+ fail("DecisionTableParseException expected");
+ } catch (DecisionTableParseException expected) {
+ assertEquals("Missing header columns", expected.getMessage());
+ }
+ }
+
+ @Test
+ public void testParseTemplateNoTemplates() {
+ try {
+ InputStream is = DefaultTemplateContainerTest.class
+ .getResourceAsStream("/templates/test_template_invalid3.drl");
+ new DefaultTemplateContainer(is);
+ fail("DecisionTableParseException expected");
+ } catch (DecisionTableParseException expected) {
+ assertEquals("Missing templates", expected.getMessage());
+ }
+ }
+
+ @Test
+ public void testParseTemplateNoEndTemplate() {
+ try {
+ InputStream is = DefaultTemplateContainerTest.class
+ .getResourceAsStream("/templates/test_template_invalid4.drl");
+ new DefaultTemplateContainer(is);
+ fail("DecisionTableParseException expected");
+ } catch (DecisionTableParseException expected) {
+ assertEquals("Missing end template", expected.getMessage());
+ }
+ }
+
+ @Test
+ public void testNullInputStream() {
+ try {
+ new DefaultTemplateContainer((InputStream) null);
+ fail("NullPointerException expected");
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ @Test
+ public void testInvalidTemplatePath() {
+ try {
+ new DefaultTemplateContainer("invalid path");
+ fail("NullPointerException expected");
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ @Test
+ public void testParseComplexTemplate() {
+ InputStream is = DefaultTemplateContainerTest.class
+ .getResourceAsStream("/templates/test_template_complex.drl");
+ DefaultTemplateContainer t = new DefaultTemplateContainer(is);
+ assertEquals("package This_is_a_ruleset;\n", t.getHeader());
+ Column[] columnList = t.getColumns();
+ assertEquals(5, columnList.length);
+ assertEquals("first_name", columnList[0].getName());
+ assertEquals("last_name", columnList[1].getName());
+ assertEquals("age", columnList[2].getName());
+ assertEquals("city", columnList[3].getName());
+ assertEquals("phone", columnList[4].getName());
+ assertEquals(columnList[1], t.getColumn("last_name"));
+ Map<String, RuleTemplate> templates = t.getTemplates();
+ assertEquals(2, templates.size());
+
+ RuleTemplate template = (RuleTemplate) templates.get("template1");
+ assertNotNull(template);
+ List<TemplateColumn> columns = template.getColumns();
+ assertEquals(1, columns.size());
+ TemplateColumn column = (TemplateColumn) columns.get(0);
+ assertEquals("first_name", column.getName());
+
+ String contents = template.getContents();
+ assertTrue(contents
+ .startsWith("rule \"How cool is @{first_name} @{row.rowNumber}\""));
+ assertTrue(contents.endsWith("then\nend\n"));
+
+ template = (RuleTemplate) templates.get("template2");
+ assertNotNull(template);
+ columns = template.getColumns();
+ assertEquals(2, columns.size());
+ column = (TemplateColumn) columns.get(0);
+ assertEquals("first_name", column.getName());
+ TemplateColumn column2 = (TemplateColumn) columns.get(1);
+ assertEquals("last_name", column2.getName());
+ contents = template.getContents();
+ assertTrue(contents
+ .startsWith("rule \"How uncool is @{first_name} @{row.rowNumber}\""));
+ assertTrue(contents.endsWith("then\nend\n"));
+
+
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/DefaultTemplateRuleBaseTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/DefaultTemplateRuleBaseTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/DefaultTemplateRuleBaseTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,102 @@
+package org.drools.template.parser;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+import org.drools.rule.GroupElement;
+import org.drools.rule.LiteralConstraint;
+import org.drools.rule.Package;
+import org.drools.rule.Rule;
+import org.drools.rule.VariableConstraint;
+
+public class DefaultTemplateRuleBaseTest {
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testSimpleTemplate() throws Exception
+ {
+ TemplateContainer tc = new TemplateContainer() {
+ private Column[] columns = new Column[] {
+ new LongColumn("column1"),
+ new LongColumn("column2"),
+ new StringColumn("column3")
+ };
+
+ public Column[] getColumns() {
+ return columns;
+ }
+
+ public String getHeader() {
+ return null;
+ }
+
+ public Map<String, RuleTemplate> getTemplates() {
+ Map<String, RuleTemplate> templates = new HashMap<String, RuleTemplate>();
+ RuleTemplate ruleTemplate = new RuleTemplate("template1", this);
+ ruleTemplate.addColumn("column1 == 10");
+ ruleTemplate.addColumn("column2 < 5 || > 20");
+ ruleTemplate.addColumn("column3 == \"xyz\"");
+ templates.put("template1", ruleTemplate);
+ return templates;
+ }
+
+ public Column getColumn(String name) {
+ return columns[Integer.parseInt(name.substring(6)) - 1];
+ }
+
+ };
+ DefaultTemplateRuleBase ruleBase = new DefaultTemplateRuleBase(tc);
+ Package[] packages = ruleBase.newStatefulSession().getRuleBase().getPackages();
+ assertEquals(1, packages.length);
+ Map<String, String> globals = packages[0].getGlobals();
+ assertEquals(DefaultGenerator.class.getName(), globals.get("generator"));
+ Rule[] rules = packages[0].getRules();
+ assertEquals(1, rules.length);
+ assertEquals("template1", rules[0].getName());
+ GroupElement lhs = rules[0].getLhs();
+ //when
+ // r : Row()
+ // column1 : Column(name == "column1")
+ // exists LongCell(row == r, column == column1, value == 10)
+ // column2 : Column(name == "column2")
+ // exists LongCell(row == r, column == column2, value < 5 | > 20)
+ // column3 : Column(name == "column3")
+ // exists StringCell(row == r, column == column3, value == "xyz")
+ assertEquals(7, lhs.getChildren().size());
+ org.drools.rule.Pattern pattern = (org.drools.rule.Pattern) lhs.getChildren().get(1);
+ assertEquals(1, pattern.getConstraints().size());
+ LiteralConstraint constraint = (LiteralConstraint) pattern.getConstraints().get(0);
+ assertEquals("column1", constraint.getField().getValue());
+ GroupElement exists = (GroupElement) lhs.getChildren().get(2);
+ pattern = (org.drools.rule.Pattern) exists.getChildren().get(0);
+ assertEquals(3, pattern.getConstraints().size());
+ VariableConstraint vconstraint = (VariableConstraint) pattern.getConstraints().get(1);
+ assertEquals(Column.class, vconstraint.getFieldExtractor().getExtractToClass());
+ assertEquals("column1", vconstraint.getRequiredDeclarations()[0].getIdentifier());
+ pattern = (org.drools.rule.Pattern) lhs.getChildren().get(3);
+ assertEquals(1, pattern.getConstraints().size());
+ constraint = (LiteralConstraint) pattern.getConstraints().get(0);
+ assertEquals("column2", constraint.getField().getValue());
+ exists = (GroupElement) lhs.getChildren().get(4);
+ pattern = (org.drools.rule.Pattern) exists.getChildren().get(0);
+ assertEquals(3, pattern.getConstraints().size());
+ vconstraint = (VariableConstraint) pattern.getConstraints().get(1);
+ assertEquals(Column.class, vconstraint.getFieldExtractor().getExtractToClass());
+ assertEquals("column2", vconstraint.getRequiredDeclarations()[0].getIdentifier());
+ pattern = (org.drools.rule.Pattern) lhs.getChildren().get(5);
+ assertEquals(1, pattern.getConstraints().size());
+ constraint = (LiteralConstraint) pattern.getConstraints().get(0);
+ assertEquals("column3", constraint.getField().getValue());
+ exists = (GroupElement) lhs.getChildren().get(6);
+ pattern = (org.drools.rule.Pattern) exists.getChildren().get(0);
+ assertEquals(3, pattern.getConstraints().size());
+ vconstraint = (VariableConstraint) pattern.getConstraints().get(1);
+ assertEquals(Column.class, vconstraint.getFieldExtractor().getExtractToClass());
+ assertEquals("column3", vconstraint.getRequiredDeclarations()[0].getIdentifier());
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/ExternalSheetListenerTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/ExternalSheetListenerTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/ExternalSheetListenerTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,504 @@
+package org.drools.template.parser;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+import org.drools.Agenda;
+import org.drools.FactException;
+import org.drools.FactHandle;
+import org.drools.QueryResults;
+import org.drools.RuleBase;
+import org.drools.StatefulSession;
+import org.drools.WorkingMemoryEntryPoint;
+import org.drools.concurrent.Future;
+import org.drools.event.AgendaEventListener;
+import org.drools.event.RuleBaseEventListener;
+import org.drools.event.WorkingMemoryEventListener;
+import org.drools.process.instance.WorkItemManager;
+import org.drools.runtime.Environment;
+import org.drools.runtime.ObjectFilter;
+import org.drools.runtime.process.ProcessInstance;
+import org.drools.spi.AgendaFilter;
+import org.drools.spi.AgendaGroup;
+import org.drools.spi.AsyncExceptionHandler;
+import org.drools.spi.GlobalResolver;
+import org.drools.time.SessionClock;
+
+public class ExternalSheetListenerTest {
+
+ private TemplateDataListener esl;
+
+ private Map<Row, List<StringCell>> assertedRows = new HashMap<Row, List<StringCell>>();
+
+ private List<StringCell> currentRow = new ArrayList<StringCell>();
+
+ @Before
+ public void setUp() throws Exception {
+ esl = new TemplateDataListener(2, 2, new TestTemplateContainer(),
+ new TestTemplateRuleBase(), new TestGenerator());
+
+ }
+
+ @Test
+ public void testRenderDrl() {
+ String drl = esl.renderDRL();
+ assertEquals("Test Template Header\nTest Generated DRL\n", drl);
+ }
+
+ @Test
+ public void testRowHandling() {
+ esl.newRow(0, 3);
+ esl.newCell(0, 0, "row0col0", 0);
+ esl.newCell(0, 1, "row0col1", 0);
+ esl.newCell(0, 2, "row0col2", 0);
+ esl.newRow(1, 3);
+ esl.newCell(1, 0, "row1col0", 0);
+ esl.newCell(1, 1, "row1col1", 0);
+ esl.newCell(1, 2, "row1col2", 0);
+ esl.newRow(2, 3);
+ esl.newCell(2, 0, "row2col0", 0);
+ esl.newCell(2, 1, "row2col1", 0);
+ esl.newCell(2, 2, "row2col2", 0);
+ esl.finishSheet();
+ assertEquals(2, assertedRows.size());
+ for ( Map.Entry<Row, List<StringCell>> entry : assertedRows.entrySet() ) {
+ Row row = entry.getKey();
+ List<StringCell> cells = entry.getValue();
+ // first column is not part of the decision table
+ int i = 1;
+ for ( StringCell cell : cells ) {
+ assertEquals("row" + row.getRowNumber() + "col" + i, cell.getValue());
+ assertEquals("Pattern " + i, cell.getColumn().getName());
+ i++;
+ }
+ }
+ }
+
+ @Test
+ public void testRowHandlingBlankRows() {
+ esl.newRow(0, 3);
+ esl.newCell(0, 0, "row0col0", 0);
+ esl.newCell(0, 1, "row0col1", 0);
+ esl.newCell(0, 2, "row0col2", 0);
+ esl.newRow(1, 3);
+ esl.newCell(1, 0, "row1col0", 0);
+ esl.newCell(1, 1, "row1col1", 0);
+ esl.newCell(1, 2, "row1col2", 0);
+ esl.newRow(2, 3);
+ esl.newCell(2, 0, "row2col0", 0);
+ esl.newCell(2, 1, "row2col1", 0);
+ esl.newCell(2, 2, "row2col2", 0);
+ esl.newRow(3, 3);
+ esl.newCell(3, 0, "", 0);
+ esl.newCell(3, 1, "", 0);
+ esl.newCell(3, 2, "", 0);
+ esl.newRow(4, 3);
+ esl.newCell(4, 0, "", 0);
+ esl.newCell(4, 1, "", 0);
+ esl.newCell(4, 2, "", 0);
+
+ esl.finishSheet();
+ assertEquals(2, assertedRows.size());
+ }
+
+ private class TestTemplateRuleBase implements TemplateRuleBase {
+
+ public StatefulSession newStatefulSession() {
+ return new StatefulSession() {
+ private static final long serialVersionUID = 510l;
+
+ public void addEventListener(WorkingMemoryEventListener arg0) {
+
+ }
+
+ public void addEventListener(AgendaEventListener arg0) {
+
+ }
+
+ public FactHandle insert(Object fact)
+ throws FactException {
+ if (fact instanceof Row) {
+ assertedRows.put((Row) fact, currentRow);
+ currentRow = new ArrayList<StringCell>();
+ } else if (fact instanceof StringCell) {
+ currentRow.add((StringCell) fact);
+ }
+ return null;
+ }
+
+ public FactHandle insert(Object arg0, boolean arg1)
+ throws FactException {
+ return null;
+ }
+
+ public void clearAgenda() {
+
+ }
+
+ public void clearAgendaGroup(String arg0) {
+
+ }
+
+ public void dispose() {
+
+ }
+
+ public int fireAllRules() throws FactException {
+ return 0;
+ }
+
+ public int fireAllRules(AgendaFilter arg0)
+ throws FactException {
+ return 0;
+ }
+
+ public Agenda getAgenda() {
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public List getAgendaEventListeners() {
+ return null;
+ }
+
+ public FactHandle getFactHandle(Object arg0) {
+ return null;
+ }
+
+ public AgendaGroup getFocus() {
+ return null;
+ }
+
+ public Object getGlobal(String arg0) {
+ return null;
+ }
+
+ public Object getObject(FactHandle arg0) {
+ return null;
+ }
+
+ public QueryResults getQueryResults(String arg0) {
+ return null;
+ }
+
+ public RuleBase getRuleBase() {
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public List getWorkingMemoryEventListeners() {
+ return null;
+ }
+
+ public void update(org.drools.runtime.rule.FactHandle arg0, Object arg1)
+ throws FactException {
+
+ }
+
+ public void removeEventListener(WorkingMemoryEventListener arg0) {
+
+ }
+
+ public void removeEventListener(AgendaEventListener arg0) {
+
+ }
+
+ public void retract(org.drools.runtime.rule.FactHandle arg0) throws FactException {
+
+ }
+
+ public void setAsyncExceptionHandler(AsyncExceptionHandler arg0) {
+
+ }
+
+ public void setFocus(String arg0) {
+
+ }
+
+ public void setFocus(AgendaGroup arg0) {
+
+ }
+
+ public void setGlobal(String arg0, Object arg1) {
+
+ }
+
+ public void setGlobalResolver(GlobalResolver globalResolver) {
+
+ }
+
+ public ProcessInstance startProcess(String processId) {
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Iterator iterateFactHandles() {
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Iterator iterateFactHandles(ObjectFilter filter) {
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Iterator iterateObjects() {
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Iterator iterateObjects(ObjectFilter filter) {
+ return null;
+ }
+
+ public Future asyncInsert(Object object) {
+ return null;
+ }
+
+ public Future asyncInsert(Object[] list) {
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Future asyncInsert(Collection collection) {
+ return null;
+ }
+
+ public Future asyncFireAllRules() {
+ return null;
+ }
+
+ public Future asyncFireAllRules(AgendaFilter agendaFilter) {
+ return null;
+ }
+
+ public Future asyncUpdate(FactHandle factHandle,
+ Object object) {
+
+ return null;
+ }
+
+ public Future asyncRetract(FactHandle factHandle) {
+
+ return null;
+ }
+
+ public QueryResults getQueryResults(String query,
+ Object[] arguments) {
+
+ return null;
+ }
+
+ public void modifyInsert(FactHandle factHandle,
+ Object object) {
+
+
+ }
+
+ public void modifyRetract(FactHandle factHandle) {
+
+
+ }
+
+ public void halt() {
+
+
+ }
+
+ public int fireAllRules(int fireLimit) throws FactException {
+ return 0;
+ }
+
+ public int fireAllRules(AgendaFilter agendaFilter,
+ int fireLimit) throws FactException {
+
+ return 0;
+ }
+
+
+ public GlobalResolver getGlobalResolver() {
+
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public List getRuleFlowEventListeners() {
+
+ return null;
+ }
+
+ public void clearActivationGroup(String group) {
+
+
+ }
+
+ public void clearRuleFlowGroup(String group) {
+
+
+ }
+
+ public void addEventListener(RuleBaseEventListener listener) {
+
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public List getRuleBaseEventListeners() {
+
+ return null;
+ }
+
+ public void removeEventListener(RuleBaseEventListener listener) {
+
+
+ }
+
+ @SuppressWarnings("unchecked")
+ public List getRuleBaseUpdateListeners() {
+
+ return null;
+ }
+
+ public ProcessInstance getProcessInstance(long id) {
+
+ return null;
+ }
+
+ public WorkItemManager getWorkItemManager() {
+
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Collection getProcessInstances() {
+
+ return null;
+ }
+
+ public ProcessInstance startProcess(String processId,
+ Map<String, Object> parameters) {
+
+ return null;
+ }
+
+ public FactHandle getFactHandleByIdentity(Object object) {
+
+ return null;
+ }
+
+ public WorkingMemoryEntryPoint getWorkingMemoryEntryPoint(String id) {
+
+ return null;
+ }
+ public SessionClock getSessionClock() {
+ return null;
+ }
+
+ public void fireUntilHalt() {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void fireUntilHalt(AgendaFilter agendaFilter) {
+ // TODO Auto-generated method stub
+
+ }
+
+ public Object getObject(org.drools.runtime.rule.FactHandle handle) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Environment getEnvironment() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Collection< ? extends org.drools.runtime.rule.FactHandle> getFactHandles() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Collection< ? extends org.drools.runtime.rule.FactHandle> getFactHandles(ObjectFilter filter) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Collection< Object> getObjects() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public Collection< Object> getObjects(ObjectFilter filter) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public String getEntryPointId() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ public long getFactCount() {
+ // TODO Auto-generated method stub
+ return 0;
+ }
+
+ };
+ }
+ }
+
+ private class TestGenerator implements Generator {
+
+ public void generate(String templateName, Row row) {
+ }
+
+ public String getDrl() {
+ return "Test Generated DRL";
+ }
+
+ }
+
+ private class TestTemplateContainer implements TemplateContainer {
+
+ public void addColumn(Column c) {
+ }
+
+ public void addTemplate(RuleTemplate template) {
+ }
+
+ public Column[] getColumns() {
+ return new Column[] { new StringColumn("Pattern 1"),
+ new StringColumn("Pattern 2"), new StringColumn("Pattern 3") };
+ }
+
+ public String getHeader() {
+ return "Test Template Header";
+ }
+
+ public Map<String, RuleTemplate> getTemplates() {
+ return null;
+ }
+
+ public void setHeader(String head) {
+ }
+
+ public void setTemplates(Map<String, RuleTemplate> templates) {
+
+ }
+
+ public Column getColumn(String name) {
+ return null;
+ }
+ }
+
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/RuleTemplateTest.java
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/RuleTemplateTest.java (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/java/org/drools/template/parser/RuleTemplateTest.java 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,71 @@
+package org.drools.template.parser;
+
+import java.util.List;
+import java.util.Map;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+import org.drools.core.util.StringUtils;
+
+public class RuleTemplateTest {
+ @Test
+ public void testSetContents() {
+ RuleTemplate rt = new RuleTemplate("rt1", getTemplateContainer());
+ rt.setContents("Test template");
+ assertEquals("Test template\n", rt.getContents());
+ }
+
+ private TemplateContainer getTemplateContainer() {
+ return new TemplateContainer() {
+
+ public Column getColumn(String name) {
+ return null;
+ }
+
+ public Column[] getColumns() {
+ return null;
+ }
+
+ public String getHeader() {
+ return null;
+ }
+
+ public Map<String, RuleTemplate> getTemplates() {
+ return null;
+ }
+
+ };
+ }
+
+ @Test
+ public void testAddColumn() {
+ RuleTemplate rt = new RuleTemplate("rt1", getTemplateContainer());
+ rt.addColumn("StandardColumn");
+ rt.addColumn("!NotColumn");
+ rt.addColumn("ColumnCondition == \"test\"");
+ rt.addColumn("!NotColumnCondition == \"test2\"");
+ rt.addColumn("ArrayColumnCondition[0] == \"test2\"");
+ List<TemplateColumn> columns = rt.getColumns();
+ assertEquals(5, columns.size());
+ TemplateColumn column1 = (TemplateColumn) columns.get(0);
+ assertEquals("StandardColumn", column1.getName());
+ assertFalse(column1.isNotCondition());
+ assertTrue(StringUtils.isEmpty(column1.getCondition()));
+ TemplateColumn column2 = (TemplateColumn) columns.get(1);
+ assertEquals("NotColumn", column2.getName());
+ assertTrue(column2.isNotCondition());
+ assertTrue(StringUtils.isEmpty(column2.getCondition()));
+ TemplateColumn column3 = (TemplateColumn) columns.get(2);
+ assertEquals("ColumnCondition", column3.getName());
+ assertFalse(column3.isNotCondition());
+ assertEquals("== \"test\"", column3.getCondition());
+ TemplateColumn column4 = (TemplateColumn) columns.get(3);
+ assertEquals("NotColumnCondition", column4.getName());
+ assertTrue(column4.isNotCondition());
+ assertEquals("== \"test2\"", column4.getCondition());
+
+ }
+}
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/Cheese.drt
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/Cheese.drt (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/Cheese.drt 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,19 @@
+template header
+age
+type
+log
+
+package org.drools.template.jdbc;
+
+global java.util.List list;
+
+template "cheesefans"
+
+rule "Cheese fans_@{row.rowNumber}"
+ when
+ Person(age == @{age})
+ Cheese(type == "@{type}")
+ then
+ list.add("@{log}");
+end
+end template
\ No newline at end of file
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/rule_template_1.drl
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/rule_template_1.drl (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/rule_template_1.drl 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,35 @@
+template header
+FEE_SCHEDULE_ID
+FEE_SCHEDULE_TYPE
+FEE_MODE_TYPE
+ENTITY_BRANCH
+PRODUCT_TYPE
+ACTIVITY_TYPE
+FEE_TYPE
+OWNING_PARTY
+CCY
+LC_AMOUNT
+AMOUNT
+
+
+package org.drools.decisiontable;
+#generated from Decision Table
+
+global FeeResult result;
+
+template "Fee Schedule"
+rule "Fee Schedule_@{row.rowNumber}"
+ agenda-group "@{FEE_SCHEDULE_TYPE}"
+ when
+ FeeEvent(productType == "@{PRODUCT_TYPE}",
+ activityType == "@{ACTIVITY_TYPE}",
+ feeType == "@{FEE_TYPE}",
+ txParty == "@{OWNING_PARTY}",
+ entityBranch == "@{ENTITY_BRANCH}",
+ amount @{LC_AMOUNT},
+ ccy == "@{CCY}"
+ )
+ then
+ result.setSchedule(new FeeSchedule("@{FEE_SCHEDULE_ID}", "@{FEE_SCHEDULE_TYPE}", @{AMOUNT}));
+end
+end template
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_complex.drl
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_complex.drl (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_complex.drl 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,27 @@
+template header
+first_name
+last_name
+age
+city
+phone
+
+package This_is_a_ruleset;
+
+template "template1"
+first_name
+rule "How cool is @{first_name} @{row.rowNumber}"
+ when
+ user.getName().equals("@{first_name}")
+ then
+end
+end template
+
+template "template2"
+first_name
+last_name
+rule "How uncool is @{first_name} @{row.rowNumber}"
+ when
+ user.getFirstName().equals("@{first_name}")
+ then
+end
+end template
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_conditions.drl
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_conditions.drl (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_conditions.drl 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,14 @@
+template header
+name
+
+package This_is_a_ruleset;
+
+template "template1"
+name == "name1"
+rule "How cool is @{name} @{row.rowNumber}"
+ when
+ user.getName().equals("@{name}")
+ then
+end
+end template
+
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid1.drl
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid1.drl (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid1.drl 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,11 @@
+package This_is_a_ruleset;
+
+template "template1"
+name
+rule "How cool is @{name} @{row.rowNumber}"
+ when
+ user.getName().equals("@{name}")
+ then
+end
+end template
+
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid2.drl
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid2.drl (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid2.drl 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,13 @@
+template header
+
+package This_is_a_ruleset;
+
+template "template1"
+name
+rule "How cool is @{name} @{row.rowNumber}"
+ when
+ user.getName().equals("@{name}")
+ then
+end
+end template
+
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid3.drl
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid3.drl (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid3.drl 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,13 @@
+template header
+name
+
+package This_is_a_ruleset;
+
+name
+rule "How cool is @{name} @{row.rowNumber}"
+ when
+ user.getName().equals("@{name}")
+ then
+end
+end template
+
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid4.drl
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid4.drl (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_invalid4.drl 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,14 @@
+template header
+name
+
+package This_is_a_ruleset;
+
+template "template1"
+name
+rule "How cool is @{name} @{row.rowNumber}"
+ when
+ user.getName().equals("@{name}"
+ then
+end
+
+
Added: labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_simple.drl
===================================================================
--- labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_simple.drl (rev 0)
+++ labs/jbossrules/tags/5.2.0.M1/drools-templates/src/test/resources/templates/test_template_simple.drl 2011-02-24 17:54:43 UTC (rev 36714)
@@ -0,0 +1,14 @@
+template header
+name
+
+package This_is_a_ruleset;
+
+template "template1"
+name
+rule "How cool is @{name} @{row.rowNumber}"
+ when
+ user.getName().equals("@{name}")
+ then
+end
+end template
+
More information about the jboss-svn-commits
mailing list